Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

232 KB
Raw Blame
import { z } from 'zod';
import type { ZodError } from 'zod';
import type { TEndpointsConfig, TModelsConfig, TConfig } from './types';
import {
  MAX_SUBAGENTS,
  MAX_SUBAGENTS_CEILING,
  MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,
  MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,
  MAX_CHAT_PROJECT_FILES,
  MAX_CHAT_PROJECT_FILES_CEILING,
  MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING,
  MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING,
  DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
} from './limits';
import {
  filtersConfigSchema,
  MAX_PII_CUSTOM_REGEX_CHARACTERS,
  MAX_PII_CUSTOM_REGEX_INSTRUCTIONS,
  MAX_PII_PATTERN_ID_LENGTH,
  MAX_PII_PATTERN_LABEL_LENGTH,
  MAX_PII_PATTERNS_PER_SOURCE,
  MAX_PII_PATTERN_LENGTH,
} from './filters';
import {
  REFILL_INTERVAL_UNITS,
  BALANCE_DISPLAY_MODES,
  BALANCE_REFILL_MODES,
  MIN_BALANCE_RESERVATION_TTL_MS,
  DEFAULT_BALANCE_RESERVATION_TTL_MS,
} from './balance';
import {
  EModelEndpoint,
  eModelEndpointSchema,
  isAgentsEndpoint,
  eReasoningParameterFormatSchema,
  eReasoningResponseKeySchema,
} from './schemas';
import {
  scheduledMCPResourceBindingSchema,
  scheduledMCPReadOnlyPolicySchema,
} from './types/scheduleConsent';
import { partialWithoutDefaults } from './zod';

export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_DEFAULT = 24 * 1024;
export const AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_HARD_MAX = 64 * 1024;
/** Coalesces a conversation's ready background results into one wake-up turn. */
export const AGENT_BACKGROUND_COMPLETION_RECEIPT_BATCHING_DEFAULT: boolean = true;
export const AGENT_BACKGROUND_SHUTDOWN_INTERRUPT_GRACE_MS_DEFAULT = 5_000;
export const DEFAULT_SKILL_DELETION_BATCH_SIZE = 100;
import {
  DEFAULT_MCP_APP_CSP_LIMITS,
  resolveMCPAppCspLimits,
  type MCPAppCspLimits,
} from './mcp/csp';
import {
  CODE_ENVIRONMENT_DECISION_VERSION,
  CODE_ENVIRONMENT_MOVE_VERSION,
  CODE_ENVIRONMENT_TRANSITION_VERSION,
  CODE_WORKSPACE_RECOVERY_VERSION,
  CODE_WORKSPACE_INHERITANCE_VERSION,
  MAX_AGENT_CODE_ENVIRONMENT_CHOICES,
} from './code/workspace';
import { ComponentTypes, SettingTypes, OptionTypes } from './generate';
import { STATEFUL_CODE_ENVIRONMENTS } from './stateful-code';
import { specsConfigSchema, TSpecsConfig } from './models';
import { fileConfigSchema } from './file-config';
import { clientLimitsSchema } from './clientLimits';
import type { TClientLimits } from './clientLimits';
import {
  PULL_REQUEST_PROVIDERS,
  PULL_REQUEST_BATCH_VERSION,
  PULL_REQUEST_BATCH_TIMEOUT_MAX_SECONDS,
} from './types/pullRequest';
import type { PullRequestProvider } from './types/pullRequest';
import { isActionTool } from './types/tools';
import { apiBaseUrl } from './api-endpoints';
import { FileSources } from './types/files';
import { MCPServersSchema } from './mcp';
export {
  MAX_SUBAGENTS,
  MAX_SUBAGENTS_CEILING,
  getMaxSubagents,
  setMaxSubagents,
  MAX_GRAPH_SUBAGENT_MEMBERS,
  MAX_CHAT_PROJECT_NAME_LENGTH,
  MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,
  DEFAULT_RETAINED_ANSWER_TOKENS,
  DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
  MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH,
  MAX_CHAT_PROJECT_FILES,
  MAX_CHAT_PROJECT_FILES_CEILING,
  MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING,
  MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING,
} from './limits';

/** Legacy mark-unread writers remove this catch-up watermark too. */
export const UNSEEN_REPLY_WATERMARK = '1970-01-01T00:00:00.000Z' as const;

export const defaultSocialLogins = ['google', 'facebook', 'openid', 'github', 'discord', 'saml'];

export const TWO_FACTOR_ENROLLMENT_REQUIRED_CODE = 'TWO_FACTOR_ENROLLMENT_REQUIRED' as const;

/** A write was refused because the deployment requires terms acceptance the user has not given. */
export const TERMS_NOT_ACCEPTED_CODE = 'terms_not_accepted' as const;

/** A federated record was refused a password login, so the only way in is its identity provider. */
export const TWO_FACTOR_FEDERATED_LOGIN_BLOCKED_CODE =
  'TWO_FACTOR_FEDERATED_LOGIN_BLOCKED' as const;

const TWO_FACTOR_POLICY_PROVIDERS = new Set(['local', 'ldap']);

export function isTwoFactorPolicyProvider(provider: string | null | undefined): boolean {
  return provider == null || TWO_FACTOR_POLICY_PROVIDERS.has(provider);
}

/** How long a started social login may take to return to its callback before its `state` expires. */
export const DEFAULT_OAUTH_STATE_TTL_MS = 10 * 60 * 1000;

/** Sections only librechat.yaml sets: no config document, Base included, can change or remove
 * them. `turnstile` stays here until the server verifies Turnstile tokens: until then a stored
 * site key adds no protection, and a wrong one locks users out of sign-in and registration. */
export const BASE_ONLY_CONFIG_SECTIONS = ['filters', 'mcpAppSandbox', 'turnstile'] as const;
/** Sections that may be stored in the tenant's base config document but must
 * not be overridden or tombstoned by role, group, or user config documents. */
export const BASE_PRINCIPAL_CONFIG_SECTIONS = ['langfuse'] as const;
/** Fields inside overridable sections that only the operator's YAML sets: a role, group, user
 * or tenant config document can neither change nor remove them. The pull request provider and
 * host decide where the deployment's token is sent, the OAuth app which credentials users grant
 * and which environment secret is sent with them, and the shared cache's slot count where every
 * replica looks for a shared answer. Vertex AI always authenticates with the deployment's service
 * account: its key file (a path, inline JSON or a URL the server fetches) and its region, which
 * is part of the API host, stay librechat.yaml's. The admin catalog's model-list lifetime is one
 * value for the whole deployment, which `GET /api/admin/config/meta` reports. */
export const BASE_ONLY_CONFIG_PATHS = [
  'endpoints.agents.pullRequests.provider',
  'endpoints.agents.pullRequests.host',
  'endpoints.agents.pullRequests.oauth',
  'endpoints.agents.pullRequests.sharedCacheSlots',
  'endpoints.anthropic.vertex.serviceKeyFile',
  'endpoints.anthropic.vertex.region',
  'endpoints.catalogModelsTtlMs',
] as const;
/** Fields the server derives from another librechat.yaml field, which no config document writes:
 * the merge leaves a document's value or tombstone there out and derives them itself, and writes
 * skip them (`derived_path`). `vertexConfig` is what `endpoints.anthropic.vertex` resolves to,
 * its service key file included, which the Anthropic client loads (a path, inline JSON or a URL
 * it fetches). Each is both an override path and an AppConfig path: its section keeps its name. */
export const DERIVED_CONFIG_PATHS = ['endpoints.anthropic.vertexConfig'] as const;

/** How long the admin config catalog reuses a scope's model lists unless
 * `endpoints.catalogModelsTtlMs` sets it: the two minutes a provider's model list is cached for. */
export const DEFAULT_CATALOG_MODELS_TTL_MS = 120_000;

/**
 * Why a deployment-only path is set in librechat.yaml only:
 * - `startup`: read once when the server starts, so a stored value would never apply.
 * - `operator`: an operator boundary (signed access, rate limits, permission leases, code
 *   modules, which tools load), read from librechat.yaml itself.
 * - `unused`: nothing reads it any more.
 */
export type DeploymentOnlyConfigReason = 'startup' | 'operator' | 'unused';

/**
 * Paths of overridable sections that only librechat.yaml sets, as YAML key paths. No config
 * document, Base included, stores them: admin writes skip them, and the merge keeps
 * librechat.yaml's value. Unlike `BASE_ONLY_CONFIG_PATHS`, their readers never took a value from
 * the merged config (apart from the tool filters, which only gated `ask_user_question` there), so
 * a stored override had no effect rather than a dangerous one.
 */
export const DEPLOYMENT_ONLY_CONFIG_PATHS: Readonly<Record<string, DeploymentOnlyConfigReason>> = {
  'telemetry.stackTraceLimit': 'operator',
  rateLimits: 'operator',
  cloudfront: 'operator',
  permissions: 'operator',
  openapi: 'operator',
  skillDeletion: 'startup',
  includedTools: 'operator',
  filteredTools: 'operator',
  'registration.openidDiscovery': 'startup',
  'registration.oauthStateTtlMs': 'startup',
  'endpoints.agents.subagentActivity': 'startup',
  'endpoints.agents.eventDriven': 'startup',
  'endpoints.agents.backgroundTasks.shutdownInterruptGraceMs': 'startup',
  'endpoints.agents.backgroundTasks.completionResultBatchSize': 'startup',
  'endpoints.agents.backgroundTasks.completionReceiptBatching': 'startup',
  'endpoints.agents.toolApproval.hooks': 'operator',
  'mcpSettings.oauthFailureRetentionMs': 'startup',
  'mcpSettings.catalogRecovery.maxStateEntries': 'startup',
  'mcpSettings.catalogRecovery.maxDetachedDiscoveries': 'startup',
  'mcpSettings.catalogRecovery.authorizationFenceRetryIntervalMs': 'startup',
  'mcpSettings.catalogRecovery.authorizationFenceRetryBatchSize': 'startup',
  cache: 'unused',
};

export const defaultRetrievalModels = [
  'gpt-4o',
  'o1-preview-2024-09-12',
  'o1-preview',
  'o1-mini-2024-09-12',
  'o1-mini',
  'o3-mini',
  'chatgpt-4o-latest',
  'gpt-4o-2024-05-13',
  'gpt-4o-2024-08-06',
  'gpt-4o-mini',
  'gpt-4o-mini-2024-07-18',
  'gpt-4-turbo-preview',
  'gpt-3.5-turbo-0125',
  'gpt-4-0125-preview',
  'gpt-4-1106-preview',
  'gpt-3.5-turbo-1106',
  'gpt-3.5-turbo-0125',
  'gpt-4-turbo',
  'gpt-4-0125',
  'gpt-4-1106',
];

export const excludedKeys = new Set([
  'conversationId',
  'agentEventBinding',
  'agentEventActor',
  'agentEventActorCleanup',
  'agentEventActorSuspension',
  'agentEventActorReconciliations',
  'agentEventActorEpoch',
  'agentEventActorLegacyTurn',
  'subagentThread',
  'title',
  'titleSetByUser',
  'titleRevision',
  'iconURL',
  'greeting',
  'endpoint',
  'endpointType',
  'createdAt',
  'updatedAt',
  'expiredAt',
  'isTemporary',
  'messages',
  'isArchived',
  'pinned',
  'archivedAt',
  'tags',
  'user',
  '__v',
  '_id',
  'tools',
  'model',
  'files',
  'spec',
  'disableParams',
  'chatProjectId',
  'lastResponseAt',
  'lastResponseMessageId',
  'lastResponseIsManual',
  'isMarkedUnread',
  'lastSeenAt',
]);

export enum SettingsViews {
  default = 'default',
  advanced = 'advanced',
}

/**
 * `allowedAddresses` is an SSRF exemption list scoped to private IP space.
 * Validate at config-load time:
 *  - Reject URLs, paths, CIDR ranges, bare host/IP forms, and whitespace.
 *  - Require `host:port` or `[ipv6]:port` entries so an exemption is scoped
 *    to one service port instead of every port on a private host.
 *  - Reject IPv4 literals that fall outside the private/loopback/link-local
 *    ranges. Public IPs are never SSRF targets, so listing one has no
 *    defensive purpose and must not silently grant trust.
 *  - Hostnames pass through; their resolved IP is checked at runtime by
 *    `resolveHostnameSSRF` and only a private resolved IP is meaningful.
 *
 * Mirrors a minimal subset of `isPrivateIP` from `@librechat/api` to avoid a
 * circular package dependency. The runtime helper is the authoritative check;
 * this refinement is a UX guardrail.
 */
function isPrivateIPv4Literal(value: string): boolean {
  const match = value.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
  if (!match) {
    return false;
  }
  const [a, b, c] = match.slice(1).map(Number) as [number, number, number, number];
  if (a === 0 || a === 10 || a === 127) return true;
  if (a === 169 && b === 254) return true;
  if (a === 172 && b >= 16 && b <= 31) return true;
  if (a === 192 && b === 168) return true;
  if (a === 192 && b === 0 && c === 0) return true; // RFC 5736 IETF protocol assignments
  if (a === 100 && b >= 64 && b <= 127) return true;
  if (a === 198 && (b === 18 || b === 19)) return true;
  if (a >= 224) return true; // multicast/reserved
  return false;
}

/**
 * Mirrors `hasPrivateEmbeddedIPv4` in `@librechat/api`'s ip helpers: 6to4, NAT64, and Teredo
 * carry an IPv4 address inside the IPv6 one, and the runtime guard blocks those when the
 * embedded address is private. Kept in sync so an operator can exempt what the runtime blocks.
 */
function hasPrivateEmbeddedIPv4Literal(value: string): boolean {
  const is6to4 = value.startsWith('2002:');
  const isNat64 = value.startsWith('64:ff9b::');
  const isTeredo = value.startsWith('2001::');
  if (!is6to4 && !isNat64 && !isTeredo) {
    return false;
  }

  const segments = value.split(':').filter((segment) => segment !== '');
  const pair = is6to4 ? segments.slice(1, 3) : segments.slice(-2);
  if (pair.length !== 2) {
    return false;
  }

  const hi = parseInt(pair[0], 16);
  const lo = parseInt(pair[1], 16);
  if (isNaN(hi) || isNaN(lo)) {
    return false;
  }

  /** RFC 4380: Teredo stores the external IPv4 as a bitwise complement. */
  const high = isTeredo ? ~hi : hi;
  const low = isTeredo ? ~lo : lo;
  const octets = [(high >> 8) & 0xff, high & 0xff, (low >> 8) & 0xff, low & 0xff];
  return isPrivateIPv4Literal(octets.join('.'));
}

function isPrivateIPv6Literal(value: string): boolean {
  if (!value.includes(':')) return false;
  if (value === '::1' || value === '::') return true;
  if (value.startsWith('fc') || value.startsWith('fd')) return true; // fc00::/7
  // fe80::/10 — first hextet 0xfe80–0xfebf
  const firstHextet = value.split(':', 1)[0];
  if (/^[0-9a-f]{1,4}$/.test(firstHextet ?? '')) {
    const hextet = parseInt(firstHextet, 16);
    if ((hextet & 0xffc0) === 0xfe80) return true;
  }
  // 4-in-6: ::ffff:A.B.C.D
  const mappedMatch = value.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
  if (mappedMatch) return isPrivateIPv4Literal(mappedMatch[1]);
  return hasPrivateEmbeddedIPv4Literal(value);
}

/**
 * Mirrors the allowedAddresses parser in `@librechat/api`'s auth helpers.
 * Kept as a local copy because the data-provider package cannot import from
 * `@librechat/api` without creating a circular dependency. Keep the two
 * implementations in sync.
 */
function normalizePort(port: unknown): string {
  if (typeof port !== 'string' && typeof port !== 'number') return '';
  const portString = String(port).trim();
  if (!/^\d+$/.test(portString)) return '';
  const parsed = Number(portString);
  if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) return '';
  return String(parsed);
}

function parseAllowedAddressEntry(entry: string): { address: string; port: string } | null {
  const trimmed = entry.toLowerCase().trim();
  const bracketedIPv6 = trimmed.match(/^\[([^\]]+)\]:(\d+)$/);
  const hostPort = bracketedIPv6 ? null : trimmed.match(/^([^:]+):(\d+)$/);
  const address = (bracketedIPv6?.[1] ?? hostPort?.[1] ?? '').replace(/^\[|\]$/g, '');
  const port = normalizePort(bracketedIPv6?.[2] ?? hostPort?.[2] ?? '');
  if (!address || !port) return null;
  return { address, port };
}

/**
 * Why an `allowedAddresses` entry is refused, as the `reason` param of its validation issue:
 * - `empty`: the entry is empty or only whitespace.
 * - `format`: a URL, path, CIDR range or whitespace instead of a `host:port` pair.
 * - `missing_port`: no valid port (`localhost`, `10.0.0.5`).
 * - `public_ip`: an IP literal outside private, loopback and link-local space.
 */
export type AllowedAddressIssue = 'empty' | 'format' | 'missing_port' | 'public_ip';

const ALLOWED_ADDRESS_ISSUE_MESSAGES: Readonly<Record<AllowedAddressIssue, string>> = {
  empty: 'allowedAddresses entries must be non-empty',
  format:
    'allowedAddresses entries must be host:port pairs — no URLs, paths, CIDR ranges, or whitespace',
  missing_port:
    'allowedAddresses entries must include a port, for example localhost:11434 or [::1]:11434',
  public_ip:
    'allowedAddresses is scoped to private IP space — public IP literals are not permitted (use hostname:port if it resolves to a private IP)',
};

/**
 * The first rule an `allowedAddresses` entry fails, checked in the order above, or `null` for an
 * entry the schema accepts. A hostname passes: its resolved IP is checked at runtime.
 */
export function getAllowedAddressEntryIssue(entry: string): AllowedAddressIssue | null {
  if (entry.trim().length === 0) {
    return 'empty';
  }
  if (entry.includes('://') || entry.includes('/') || /\s/.test(entry)) {
    return 'format';
  }
  const parsed = parseAllowedAddressEntry(entry);
  if (!parsed) {
    return 'missing_port';
  }
  const { address } = parsed;
  const isIPv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.test(address);
  if (!isIPv4 && !address.includes(':')) {
    return null;
  }
  const isPrivate = isIPv4 ? isPrivateIPv4Literal(address) : isPrivateIPv6Literal(address);
  return isPrivate ? null : 'public_ip';
}

/** One issue per refused entry, with its message and `params.reason`. */
const allowedAddressEntrySchema = z.string().superRefine((entry, ctx) => {
  const reason = getAllowedAddressEntryIssue(entry);
  if (reason) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: ALLOWED_ADDRESS_ISSUE_MESSAGES[reason],
      params: { reason },
    });
  }
});

export const allowedAddressesSchema = z.array(allowedAddressEntrySchema).optional();

/** Storage backend strategies only — use for config fields that set where files are stored. */
const FILE_STORAGE_BACKENDS = [
  FileSources.local,
  FileSources.firebase,
  FileSources.s3,
  FileSources.azure_blob,
  FileSources.cloudfront,
] as const satisfies ReadonlyArray<FileSources>;

export const fileStorageSchema = z.enum(FILE_STORAGE_BACKENDS);

export type FileStorage = z.infer<typeof fileStorageSchema>;

export const fileStrategiesSchema = z
  .object({
    default: fileStorageSchema.optional(),
    avatar: fileStorageSchema.optional(),
    image: fileStorageSchema.optional(),
    document: fileStorageSchema.optional(),
    skills: fileStorageSchema.optional(),
  })
  .optional();

const cloudfrontSigningSchema = z.enum(['none', 'cookies', 'url']);

export const cloudfrontConfigSchema = z
  .object({
    domain: z.string().url(),
    distributionId: z.string().optional(),
    invalidateOnDelete: z.boolean().default(false),
    imageSigning: cloudfrontSigningSchema.default('none'),
    urlExpiry: z.number().positive().default(3600),
    cookieExpiry: z.number().positive().max(604800).default(1800),
    cookieDomain: z
      .string()
      .min(1)
      .refine((d) => d.startsWith('.'), {
        message: 'cookieDomain must start with a dot (e.g., ".example.com") to apply to subdomains',
      })
      .optional(),
    storageRegion: z.string().min(1).optional(),
    includeRegionInPath: z.boolean().default(false),
    requireSignedAccess: z.boolean().default(false),
  })
  .refine((data) => !data.invalidateOnDelete || !!data.distributionId, {
    message: 'distributionId is required when invalidateOnDelete is true',
    path: ['distributionId'],
  })
  .refine((data) => data.imageSigning !== 'cookies' || !!data.cookieDomain, {
    message:
      'cookieDomain is required when imageSigning is "cookies" (e.g., ".example.com" for API at api.example.com and CDN at cdn.example.com)',
    path: ['cookieDomain'],
  })
  .refine((data) => !data.requireSignedAccess || data.imageSigning === 'cookies', {
    message:
      'cloudfront.requireSignedAccess=true requires cloudfront.imageSigning="cookies" (signed URL mode is not yet implemented)',
    path: ['requireSignedAccess'],
  })
  .optional();

export type CloudFrontConfig = z.infer<typeof cloudfrontConfigSchema>;

const skillSyncIdentifierSchema = z
  .string()
  .min(1)
  .max(64)
  .regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/, {
    message:
      'must start with a letter or digit and contain only letters, digits, underscores, or hyphens',
  });

export const SKILL_SYNC_MIN_INTERVAL_MINUTES = 5;
export const SKILL_SYNC_MAX_INTERVAL_MINUTES = Math.floor(2147483647 / 60_000);
export const SKILL_SYNC_DEFAULT_DISCOVERY_DEPTH = 2;
export const SKILL_SYNC_MAX_DISCOVERY_DEPTH = 10;

const skillSyncGitHubOwnerSchema = z
  .string()
  .min(1)
  .max(39)
  .regex(/^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/, {
    message: 'must be a valid GitHub owner name',
  });

const skillSyncGitHubRepoSchema = z
  .string()
  .min(1)
  .max(100)
  .regex(/^[a-zA-Z0-9._-]+$/, {
    message: 'must be a valid GitHub repository name',
  });

const invalidGitRefChars = new Set(['~', '^', ':', '?', '*', '[']);

function hasInvalidGitRefCharacter(value: string): boolean {
  for (const char of value) {
    const code = char.charCodeAt(0);
    if (code <= 32 || code === 127 || invalidGitRefChars.has(char)) {
      return true;
    }
  }
  return false;
}

const skillSyncGitHubRefSchema = z
  .string()
  .min(1)
  .max(255)
  .refine((value) => !value.startsWith('/') && !value.endsWith('/'), {
    message: 'must not start or end with a slash',
  })
  .refine((value) => !value.includes('..') && !value.includes('//') && !value.includes('\\'), {
    message: 'must not contain traversal segments, empty path segments, or backslashes',
  })
  .refine((value) => !value.includes('@{') && value !== '@', {
    message: 'must not contain invalid Git ref syntax',
  })
  .refine((value) => !value.endsWith('.'), {
    message: 'must not end with a dot',
  })
  .refine((value) => !hasInvalidGitRefCharacter(value), {
    message: 'must not contain invalid Git ref characters',
  })
  .refine(
    (value) =>
      value
        .split('/')
        .every((segment) => segment && !segment.startsWith('.') && !segment.endsWith('.lock')),
    {
      message: 'must contain valid Git ref path segments',
    },
  );

const skillSyncPathSchema = z
  .string()
  .max(500)
  .refine((value) => value.trim().length > 0, { message: 'must not be empty' })
  .transform((value) => {
    const trimmed = value.trim().replace(/^\/+|\/+$/g, '');
    return trimmed === '.' ? '' : trimmed;
  })
  .refine((value) => !value.includes('\\') && !value.includes('..'), {
    message: 'must not contain traversal segments or backslashes',
  })
  .refine((value) => value === '' || /^[a-zA-Z0-9._\-/]+$/.test(value), {
    message: 'must contain only letters, digits, dots, underscores, hyphens, and slashes',
  })
  .refine(
    (value) =>
      value === '' || value.split('/').every((segment) => segment.length > 0 && segment !== '.'),
    {
      message: 'must not contain empty or dot path segments',
    },
  );

const skillSyncTokenReferenceSchema = z
  .string()
  .trim()
  .regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/, {
    message: 'must be an environment variable reference like ${GITHUB_SKILLS_TOKEN}',
  });

/**
 * Tenant that owns the skills mirrored from a source. When set, the sync runner
 * executes that source's database writes inside the tenant's async context so
 * synced skills are created, listed, and shared within the tenant under strict
 * tenant isolation. Mirrors the request tenant-id contract: no reserved system id.
 */
const skillSyncTenantIdSchema = z
  .string()
  .max(128)
  .refine((value) => /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(value), {
    message: 'must be a valid tenant id',
  })
  .refine((value) => value !== '__SYSTEM__', {
    message: 'must not be the reserved system tenant id',
  });

/** `owner/name`, or `owner/*` for every repository of one owner; never a bare `*`. */
const pullRequestRepositorySchema = z
  .string()
  .trim()
  .regex(/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+){0,18}\/(?:[A-Za-z0-9_.-]+|\*)$/, {
    message: 'must be owner/name or owner/*, or a nested group path such as group/sub/name',
  })
  .refine((value) => value.split('/').every((segment) => segment !== '.' && segment !== '..'), {
    message: 'must not contain dot segments',
  });

/** A GitHub host name, optionally with a port: `github.com`, an Enterprise Server host such as
 *  `github.example.com`, or a data residency tenant such as `acme.ghe.com`. Never a URL. */
const pullRequestHostSchema = z
  .string()
  .trim()
  .max(253)
  .regex(/^(?=[a-z0-9])[a-z0-9.-]*[a-z0-9](?::[0-9]{1,5})?$/i, {
    message: 'must be a host name like github.example.com, without a scheme or path',
  })
  .refine(
    (value) => {
      const port = value.split(':')[1];
      return port == null || (Number(port) >= 1 && Number(port) <= 65535);
    },
    { message: 'must use a port from 1 to 65535' },
  );

const pullRequestTokenReferenceSchema = z
  .string()
  .trim()
  .regex(/^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/, {
    message: 'must be an environment variable reference like ${GITHUB_PULL_REQUEST_TOKEN}',
  });

export const skillSyncGitHubSourceSchema = z
  .object({
    id: skillSyncIdentifierSchema,
    owner: skillSyncGitHubOwnerSchema,
    repo: skillSyncGitHubRepoSchema,
    ref: skillSyncGitHubRefSchema.default('main'),
    paths: z.array(skillSyncPathSchema).min(1),
    skillDiscoveryDepth: z.number().int().min(0).max(SKILL_SYNC_MAX_DISCOVERY_DEPTH).optional(),
    credentialKey: skillSyncIdentifierSchema.optional(),
    token: skillSyncTokenReferenceSchema.optional(),
    tenantId: skillSyncTenantIdSchema.optional(),
  })
  .superRefine((source, ctx) => {
    if (!source.credentialKey && !source.token) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['credentialKey'],
        message: 'Either credentialKey or token is required',
      });
    }
    if (source.credentialKey && source.token) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['token'],
        message: 'Use either credentialKey or token, not both',
      });
    }
  });

export const skillSyncConfigSchema = z
  .object({
    github: z
      .object({
        enabled: z.boolean().default(false),
        intervalMinutes: z
          .number()
          .int()
          .min(SKILL_SYNC_MIN_INTERVAL_MINUTES)
          .max(SKILL_SYNC_MAX_INTERVAL_MINUTES)
          .default(60),
        runOnStartup: z.boolean().default(false),
        sources: z.array(skillSyncGitHubSourceSchema).default([]),
      })
      .superRefine((github, ctx) => {
        if (github.enabled && github.sources.length === 0) {
          ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: ['sources'],
            message: 'At least one GitHub source is required when skill sync is enabled',
          });
        }
        const seen = new Set<string>();
        for (const source of github.sources) {
          if (seen.has(source.id)) {
            ctx.addIssue({
              code: z.ZodIssueCode.custom,
              path: ['sources'],
              message: `Duplicate GitHub skill sync source id "${source.id}"`,
            });
          }
          seen.add(source.id);
        }
      })
      .optional(),
  })
  .optional();

export type SkillSyncConfig = z.infer<typeof skillSyncConfigSchema>;
export type SkillSyncGitHubSourceConfig = z.infer<typeof skillSyncGitHubSourceSchema>;

// Helper type to extract the shape of the Zod object schema
type SchemaShape<T> = T extends z.ZodObject<infer U> ? U : never;

// Helper type to determine the default value or undefined based on whether the field has a default
type DefaultValue<T> =
  T extends z.ZodDefault<infer Inner>
    ? z.output<Inner>
    : T extends z.ZodPrefault<infer Inner>
      ? z.input<Inner>
      : undefined;

// Extract default values or undefined from the schema shape
type ExtractDefaults<T> = {
  [P in keyof T]: DefaultValue<T[P]>;
};

export type SchemaDefaults<T> = ExtractDefaults<SchemaShape<T>>;

export type TConfigDefaults = SchemaDefaults<typeof configSchema>;

export function getSchemaDefaults<Schema extends z.ZodObject>(
  schema: Schema,
): ExtractDefaults<SchemaShape<Schema>> {
  const shape = schema.shape;
  const entries = Object.entries(shape).map(([key, value]) => {
    if (value instanceof z.ZodDefault || value instanceof z.ZodPrefault) {
      return [key, value.def.defaultValue];
    }
    return [key, undefined];
  });

  // Create the object with the right types
  return Object.fromEntries(entries) as ExtractDefaults<SchemaShape<Schema>>;
}

export const modelConfigSchema = z
  .object({
    deploymentName: z.string().optional(),
    version: z.string().optional(),
    assistants: z.boolean().optional(),
  })
  .or(z.boolean());

export type TAzureModelConfig = z.infer<typeof modelConfigSchema>;

const paramValueSchema: z.ZodType<unknown> = z.lazy(() =>
  z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.null(),
    z.array(paramValueSchema),
    z.record(z.string(), paramValueSchema),
  ]),
);

/** Validates addParams while keeping web_search aligned with current runtime boolean handling. */
const addParamsSchema: z.ZodType<Record<string, unknown>> = z
  .record(z.string(), paramValueSchema)
  .superRefine((params, ctx) => {
    if (params.web_search === undefined || typeof params.web_search === 'boolean') {
      return;
    }

    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['web_search'],
      message: '`web_search` must be a boolean in addParams',
    });
  });

export const azureBaseSchema = z.object({
  apiKey: z.string(),
  serverless: z.boolean().optional(),
  instanceName: z.string().optional(),
  deploymentName: z.string().optional(),
  assistants: z.boolean().optional(),
  addParams: addParamsSchema.optional(),
  dropParams: z.array(z.string()).optional(),
  version: z.string().optional(),
  baseURL: z.string().optional(),
  additionalHeaders: z.record(z.string(), z.string()).optional(),
});

export type TAzureBaseSchema = z.infer<typeof azureBaseSchema>;

export const azureGroupSchema = z
  .object({
    group: z.string(),
    models: z.record(z.string(), modelConfigSchema),
  })
  .required()
  .extend({
    /**
     * Masked preview of the group's `apiKey`, set by the admin config API when it stores the key
     * encrypted. Read-only: writes to it are rejected.
     */
    apiKeyPreview: z.string().optional(),
  })
  .and(azureBaseSchema);

export const azureGroupConfigsSchema = z.array(azureGroupSchema).min(1);
export type TAzureGroup = z.infer<typeof azureGroupSchema>;
export type TAzureGroups = z.infer<typeof azureGroupConfigsSchema>;
export type TAzureModelMapSchema = {
  // deploymentName?: string;
  // version?: string;
  group: string;
};

export type TAzureModelGroupMap = Record<string, TAzureModelMapSchema | undefined>;
export type TAzureGroupMap = Record<
  string,
  (TAzureBaseSchema & { models: Record<string, TAzureModelConfig | undefined> }) | undefined
>;

export type TValidatedAzureConfig = {
  modelNames: string[];
  groupMap: TAzureGroupMap;
  assistantModels?: string[];
  assistantGroups?: string[];
  modelGroupMap: TAzureModelGroupMap;
};

export type TAzureConfigValidationResult = TValidatedAzureConfig & {
  isValid: boolean;
  errors: (ZodError | string)[];
};

export enum Capabilities {
  code_interpreter = 'code_interpreter',
  image_vision = 'image_vision',
  retrieval = 'retrieval',
  actions = 'actions',
  tools = 'tools',
}

export enum AgentCapabilities {
  hide_sequential_outputs = 'hide_sequential_outputs',
  programmatic_tools = 'programmatic_tools',
  end_after_tools = 'end_after_tools',
  deferred_tools = 'deferred_tools',
  execute_code = 'execute_code',
  stateful_code_sessions = 'stateful_code_sessions',
  file_search = 'file_search',
  web_search = 'web_search',
  artifacts = 'artifacts',
  subagents = 'subagents',
  actions = 'actions',
  context = 'context',
  skills = 'skills',
  memory = 'memory',
  ask_user_question = 'ask_user_question',
  tools = 'tools',
  /** @deprecated Retained for legacy configuration. Chain authoring is retired. */
  chain = 'chain',
  ocr = 'ocr',
  run_in_background = 'run_in_background',
  tool_intents = 'tool_intents',
}

export const defaultAssistantsVersion = {
  [EModelEndpoint.assistants]: 2,
  [EModelEndpoint.azureAssistants]: 1,
};

export const baseEndpointSchema = z.object({
  /**
   * Milliseconds between visible streamed chunks. Agents SDK-backed
   * providers (openAI, custom, anthropic, google, bedrock, agents) smooth
   * adaptively at 25ms by default; set to override the cadence, 0 to
   * disable smoothing. Legacy Assistants and Ollama paths instead sleep
   * this long per provider chunk (default 1ms), with no adaptive smoothing.
   */
  streamRate: z.number().min(0).optional(),
  baseURL: z.string().optional(),
  /**
   * Custom request headers forwarded to the provider on every request. Values
   * support the same placeholder resolution as custom endpoints — env vars
   * (`${VAR}`), user fields (`{{LIBRECHAT_USER_*}}`), and request-body fields
   * (`{{LIBRECHAT_BODY_CONVERSATIONID}}`). Primarily for routing built-in
   * providers through an AI gateway / reverse proxy that consumes metadata
   * headers (provider-native request shaping is preserved).
   */
  headers: z.record(z.string(), z.string()).optional(),
  titlePrompt: z.string().optional(),
  titleModel: z.string().optional(),
  titleConvo: z.boolean().optional(),
  titleMethod: z
    .union([z.literal('completion'), z.literal('functions'), z.literal('structured')])
    .optional(),
  titleEndpoint: z.string().optional(),
  titlePromptTemplate: z.string().optional(),
  /**
   * When conversation titles are generated. `immediate` (default) generates the
   * title as soon as the request is made, in parallel with the response, from the
   * user's first message. `final` defers generation until the full response
   * completes (legacy behavior).
   */
  titleTiming: z.union([z.literal('immediate'), z.literal('final')]).optional(),
  /**
   * Agent activity groups: collapse each contiguous block of reasoning and
   * tool calls under a generated one-line header. Mirrors the title options
   * above — `activityLabel` enables it (like `titleConvo`), the rest tune
   * the fast model that writes the label.
   *
   * NOTE: fields added here reach `endpoints.all` automatically (that schema
   * is `baseEndpointSchema.omit({ baseURL })`), but NOT Azure — see the
   * enumerated `.pick()` in `azureEndpointSchema` below.
   */
  activityLabel: z.boolean().optional(),
  /** Model used to write activity labels. Defaults to `titleModel`, then the agent's model. */
  activityModel: z.string().optional(),
  /** Endpoint whose credentials the label model runs on. Defaults to the agent's endpoint. */
  activityEndpoint: z.string().optional(),
  /** Overrides the system prompt used to write activity labels. */
  activityPrompt: z.string().optional(),
  /** Cost cap: maximum labels generated per run. Default 20. */
  activityMaxPerRun: z.number().int().positive().optional(),
  /** Per-entry truncation of tool input/output in the label prompt. Default 600. */
  activityCharLimit: z.number().int().positive().optional(),
  /** Generates one parent summary for each run phase containing 2+ activities. */
  activityPhaseLabel: z.boolean().optional(),
  /** Model used for phase summaries. Defaults to activityModel, titleModel, then the run model. */
  activityPhaseModel: z.string().optional(),
  /** Endpoint whose credentials the phase summary model uses. Defaults to activityEndpoint. */
  activityPhaseEndpoint: z.string().optional(),
  /** Overrides the dedicated phase-summary system prompt. */
  activityPhasePrompt: z.string().optional(),
  /** Cost cap: maximum phase summaries generated per run. Default 5. */
  activityPhaseMaxPerRun: z.number().int().positive().optional(),
  /** Generates a live orientation label for sufficiently long top-level response reasoning. */
  reasoningLabel: z.boolean().optional(),
  /** Model used for reasoning labels. Defaults to activityModel, titleModel, then run model. */
  reasoningLabelModel: z.string().optional(),
  /** Endpoint receiving the bounded visible-reasoning snapshot. Defaults to activityEndpoint. */
  reasoningLabelEndpoint: z.string().optional(),
  /** Overrides the dedicated reasoning-label system prompt. */
  reasoningLabelPrompt: z.string().optional(),
  /** Characters required before the first reasoning label. Default 500. */
  reasoningLabelMinChars: z.number().int().positive().optional(),
  /** New characters required between streaming revisions. Default 400. */
  reasoningLabelUpdateChars: z.number().int().positive().optional(),
  /** Minimum milliseconds between streaming revisions. Default 3000. */
  reasoningLabelUpdateIntervalMs: z.number().int().nonnegative().optional(),
  /** Cost cap: maximum reasoning-label provider calls attempted per run. Default 8. */
  reasoningLabelMaxPerRun: z.number().int().positive().optional(),
  /** Maximum characters allowed in a single tool result before truncation. */
  maxToolResultChars: z.number().positive().optional(),
});

export type TBaseEndpoint = z.infer<typeof baseEndpointSchema>;

export const bedrockGuardrailConfigSchema = z.object({
  guardrailIdentifier: z.string(),
  guardrailVersion: z.string(),
  trace: z.enum(['enabled', 'disabled', 'enabled_full']).optional(),
  streamProcessingMode: z.enum(['sync', 'async']).optional(),
});

export const bedrockEndpointSchema = baseEndpointSchema.merge(
  z.object({
    availableRegions: z.array(z.string()).optional(),
    models: z.array(z.string()).optional(),
    guardrailConfig: bedrockGuardrailConfigSchema.optional(),
    inferenceProfiles: z.record(z.string(), z.string()).optional(),
  }),
);

const modelItemSchema = z.union([
  z.string(),
  z.object({
    name: z.string(),
    description: z.string().optional(),
  }),
]);

export const assistantEndpointSchema = baseEndpointSchema.merge(
  z.object({
    /* assistants specific */
    disableBuilder: z.boolean().optional(),
    pollIntervalMs: z.number().optional(),
    timeoutMs: z.number().optional(),
    version: z.union([z.string(), z.number()]).default(2),
    supportedIds: z.array(z.string()).min(1).optional(),
    excludedIds: z.array(z.string()).min(1).optional(),
    privateAssistants: z.boolean().optional(),
    retrievalModels: z.array(z.string()).min(1).optional().default(defaultRetrievalModels),
    capabilities: z
      .array(z.nativeEnum(Capabilities))
      .optional()
      .default([
        Capabilities.code_interpreter,
        Capabilities.image_vision,
        Capabilities.retrieval,
        Capabilities.actions,
        Capabilities.tools,
      ]),
    /* general */
    apiKey: z.string().optional(),
    /** Masked preview of the API key, stored at write time so admin
     * reads can show which key is configured without returning the secret.
     * Shared by both `endpoints.assistants` and `endpoints.azureAssistants`,
     * which both use this schema. */
    apiKeyPreview: z.string().optional(),
    models: z
      .object({
        default: z.array(modelItemSchema).min(1),
        fetch: z.boolean().optional(),
        userIdQuery: z.boolean().optional(),
      })
      .optional(),
    headers: z.record(z.string(), z.string()).optional(),
  }),
);

export type TAssistantEndpoint = z.infer<typeof assistantEndpointSchema>;

export const defaultAgentCapabilities = [
  // Commented as requires latest Code Interpreter API
  // AgentCapabilities.programmatic_tools,
  AgentCapabilities.deferred_tools,
  AgentCapabilities.execute_code,
  AgentCapabilities.file_search,
  AgentCapabilities.web_search,
  AgentCapabilities.artifacts,
  AgentCapabilities.subagents,
  AgentCapabilities.actions,
  AgentCapabilities.context,
  AgentCapabilities.skills,
  AgentCapabilities.memory,
  AgentCapabilities.ask_user_question,
  AgentCapabilities.tools,
  AgentCapabilities.ocr,
];

const LOCAL_REMOTE_OIDC_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);

export function isRemoteOidcUrlAllowed(value: string): boolean {
  try {
    const url = new URL(value);
    if (url.protocol === 'https:') return true;
    if (url.protocol !== 'http:') return false;

    const hostname = url.hostname.toLowerCase();
    return LOCAL_REMOTE_OIDC_HOSTS.has(hostname) || hostname.endsWith('.localhost');
  } catch {
    return false;
  }
}

const remoteApiOidcUrlSchema = z
  .string()
  .url()
  .refine(isRemoteOidcUrlAllowed, { message: 'must use https:// unless targeting localhost' });

const remoteApiOidcScopeSchema = z.string().refine((scope) => !scope.includes(','), {
  message: 'scopes must be space-separated',
});

const oidcAccessTokenSchema = z.object({
  enabled: z.boolean().default(false),
  issuer: remoteApiOidcUrlSchema.optional(),
  audience: z.string().min(1).optional(),
  jwksUri: remoteApiOidcUrlSchema.optional(),
});

function validateEnabledOidc(
  oidc: z.infer<typeof oidcAccessTokenSchema>,
  ctx: z.RefinementCtx,
): void {
  if (oidc.enabled === true && !oidc.issuer) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['issuer'],
      message: 'issuer is required when OIDC auth is enabled',
    });
  }
  if (oidc.enabled === true && !oidc.audience) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['audience'],
      message: 'audience is required when OIDC auth is enabled',
    });
  }
}

const remoteApiOidcSchema = oidcAccessTokenSchema
  .extend({ scope: remoteApiOidcScopeSchema.optional() })
  .superRefine(validateEnabledOidc);

const remoteApiAuthSchema = z.object({
  apiKey: z
    .object({
      enabled: z.boolean().default(true),
    })
    .optional(),
  oidc: remoteApiOidcSchema.optional(),
});

const remoteApiSchema = z.object({
  auth: remoteApiAuthSchema.optional(),
});

const managementClientBindingSchema = z
  .object({
    clientId: z.string().trim().min(1).max(128),
    subject: z.string().trim().min(1).max(512).optional(),
    userId: z
      .string()
      .trim()
      .regex(/^[a-f\d]{24}$/i, 'must be a MongoDB ObjectId')
      .transform((userId) => userId.toLowerCase()),
    tenantId: z
      .string()
      .trim()
      .min(1)
      .max(128)
      .regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/, 'must be a valid tenant id')
      .refine((tenantId) => tenantId !== '__SYSTEM__', 'system tenant is not allowed'),
    enabled: z.boolean().default(true),
  })
  .strict();

const managementApiOidcSchema = oidcAccessTokenSchema
  .extend({
    tokenUse: z.literal('access').optional(),
    requiredScopes: z
      .array(z.string().trim().min(1).max(256).regex(/^\S+$/, 'must be a single scope token'))
      .min(1)
      .max(20)
      .optional(),
  })
  .strict()
  .superRefine((oidc, ctx) => {
    if (oidc.enabled === true && !oidc.issuer) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['issuer'],
        message: 'issuer is required when OIDC auth is enabled',
      });
    }
    if (
      oidc.enabled === true &&
      !oidc.audience &&
      (oidc.tokenUse !== 'access' || !oidc.requiredScopes?.length)
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['requiredScopes'],
        message:
          'audience or access-token validation with required scopes is required when OIDC auth is enabled',
      });
    }
  });

const managementApiAuthSchema = z
  .object({
    oidc: managementApiOidcSchema,
    clients: z.array(managementClientBindingSchema).max(100).default([]),
  })
  .strict()
  .superRefine((auth, ctx) => {
    if (auth.oidc.enabled === true && auth.clients.length === 0) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['clients'],
        message: 'at least one client binding is required when management auth is enabled',
      });
    }

    const clientIds = new Set<string>();
    for (let index = 0; index < auth.clients.length; index++) {
      const client = auth.clients[index];
      if (clientIds.has(client.clientId)) {
        ctx.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['clients', index, 'clientId'],
          message: 'client IDs must be unique',
        });
      }
      clientIds.add(client.clientId);
    }
  });

const managementApiSchema = z.object({ auth: managementApiAuthSchema.optional() }).strict();

/**
 * Permission mode applied to a tool call. Mirrors `@librechat/agents`'s
 * `ToolPolicyMode` 1:1.
 *
 * - `default`: ask the user about anything not explicitly allowed (default-on).
 * - `dontAsk`: deny anything not explicitly allowed (headless / API-key flows).
 * - `bypass`: auto-approve everything that isn't explicitly denied
 *   (the user-facing "stop asking me" toggle).
 *
 * Subagents inherit the parent's mode; this is enforced by the SDK and not
 * overridable per-subagent.
 */
export const toolApprovalModeSchema = z.enum(['default', 'dontAsk', 'bypass']);

/**
 * Per-endpoint tool-approval policy.
 *
 * Shape mirrors `@librechat/agents`'s `ToolPolicyConfig` so the host can map it
 * directly into `createToolPolicyHook(config)`. The SDK does the evaluation
 * (`deny → ask → allow → bypass → dontAsk → fallthrough(ask)`); this config
 * just describes the surface.
 *
 * Conventions:
 * - All list entries are matched as globs (`*`). Use `mcp:server:*` to scope
 *   a rule to every tool from a single MCP server.
 * - `deny` always wins, including under `bypass`.
 * - `enabled: false` is a LibreChat-only kill switch that disables the entire
 *   HITL machinery for this endpoint (no checkpointer, no hooks, no prompts).
 *   This is admin-level; users toggle prompting via `mode: 'bypass'` instead.
 */
/**
 * A programmatic tool-approval hook loaded from a module at startup.
 *
 * The referenced module's default export must be a builder
 * `(options?) => ToolApprovalHookFactory` (see `@librechat/api`'s `registerToolApprovalHook`).
 * Hooks compose with the static `allow`/`deny`/`ask` policy above and can only TIGHTEN it
 * (the SDK folds decisions `deny → ask → allow`). This is admin-level config — the module is
 * dynamically imported and executed in-process, so only reference trusted code.
 */
export const toolApprovalHookConfigSchema = z.object({
  /**
   * Module specifier to import: a bare package name (e.g. `@acme/approval-hooks`) or a path —
   * absolute, or relative to the app root. Its default export is the hook builder.
   */
  module: z.string().min(1),
  /** Optional regex matched against the tool name; omit to run for every tool. */
  matcher: z.string().optional(),
  /** Static options forwarded to the module's builder; the hook's own per-call config. */
  options: z.record(z.string(), z.unknown()).optional(),
});

export type TToolApprovalHookConfig = z.infer<typeof toolApprovalHookConfigSchema>;

export const toolApprovalPolicySchema = z
  .object({
    enabled: z.boolean().optional(),
    mode: toolApprovalModeSchema.optional(),
    /** Enable after all replicas support agent-scoped approval modes and grants. */
    agentModes: z.boolean().optional(),
    /** Bounded grant lookups fail back to manual review, never automatic approval. */
    grantLookupTimeoutMs: z.number().int().min(100).max(5000).optional(),
    allow: z.array(z.string()).optional(),
    deny: z.array(z.string()).optional(),
    ask: z.array(z.string()).optional(),
    /** Optional reason template surfaced in the prompt; `{tool}` is interpolated. */
    reason: z.string().optional(),
    /**
     * Offer "Always allow" on the approval card. Choosing it auto-approves that exact tool
     * (MCP names include their server) for the rest of the conversation. The server stores
     * and enforces the choice; `deny` and `ask` rules and programmatic hooks still win, and
     * stored choices are ignored under `mode: 'dontAsk'` or once this is turned off.
     * Defaults to `false`: every paused call keeps prompting. Enable it only once every
     * replica runs a version that supports it: older replicas ignore the choice and keep
     * prompting, so during a rolling upgrade it may not stick.
     */
    allowAlways: z.boolean().optional(),
    /**
     * Most tools one conversation may remember with "Always allow". Once reached, the card
     * stops offering the choice for new tools. Defaults to 64.
     */
    allowAlwaysMaxTools: z.number().int().min(1).max(1024).optional(),
    /** Longest tool name that may be remembered. Defaults to 256. */
    allowAlwaysMaxToolNameLength: z.number().int().min(1).max(1024).optional(),
    /**
     * Programmatic policy hooks loaded from modules at startup. They layer on top of the
     * static lists above for dynamic, context-aware decisions the lists can't express
     * (per-args, per-agent, per-user). See {@link toolApprovalHookConfigSchema}.
     *
     * BASE-CONFIG ONLY: hooks are imported + registered once, process-wide, at server
     * startup — they are NOT reloaded from per-role/user/tenant admin overrides. Encode
     * per-user/tenant behavior INSIDE the hook (via its runtime context), not by varying the
     * module list per override. Honored only when `enabled` is true.
     */
    hooks: z.array(toolApprovalHookConfigSchema).optional(),
  })
  .optional();

export type TToolApprovalPolicy = z.infer<typeof toolApprovalPolicySchema>;

export const askUserQuestionRetainedAnswersSchema = z.object({
  /** `false` stops carrying answers forward; they then live only in the messages. */
  enabled: z.boolean().optional(),
  /** Token ceiling for the carried block. Older answers drop first once it is
   *  exceeded; the newest set is always kept. Defaults to
   *  `DEFAULT_RETAINED_ANSWER_TOKENS` (4096). */
  maxTokens: z.number().int().positive().optional(),
});

/**
 * Behavior of the `ask_user_question` tool beyond the admin kill switch
 * (`filteredTools` / `includedTools`).
 *
 * `retainedAnswers`: every answer the user gave to an agent's question is
 * quoted verbatim in the run's user context, so it survives after the
 * messages that carried it were summarized, pruned or dropped from the context
 * window. On by default.
 */
export const askUserQuestionConfigSchema = z
  .object({
    retainedAnswers: askUserQuestionRetainedAnswersSchema.optional(),
  })
  .optional();

export type TAskUserQuestionConfig = z.infer<typeof askUserQuestionConfigSchema>;

/**
 * Durable checkpointer backing human-in-the-loop resume.
 *
 * When `toolApproval.enabled` is true, a run that pauses for review suspends its
 * LangGraph state to a checkpoint; resuming rebuilds that state on a *fresh* `Run`
 * — possibly on a different replica, or the same worker after a restart. That only
 * works if the checkpoint outlives the original request, so HITL needs a durable
 * saver, not the SDK's process-local `MemorySaver` fallback.
 *
 * Defaults are zero-config: with `toolApproval.enabled` on and no `checkpointer`
 * block, LibreChat persists checkpoints to its primary MongoDB, so resume works
 * across replicas out of the box.
 *
 * - `type: 'mongo'` (default) — persist to the app database; survives restarts and
 *   resolves on any replica. A TTL index reclaims runs that are never resolved.
 * - `type: 'memory'` — process-local only. Paused runs do NOT survive a restart and
 *   can only be resolved on the originating worker. Single-process / dev only.
 */
export const checkpointerTypeSchema = z.enum(['mongo', 'memory']);
export type TCheckpointerType = z.infer<typeof checkpointerTypeSchema>;

export const checkpointerSchema = z
  .object({
    type: checkpointerTypeSchema.optional(),
    /**
     * Approval window, in seconds: how long a paused run waits for a decision
     * before it is reclaimed. Drives both the Mongo TTL index on checkpoints and
     * the pending-action expiry, keeping the two layers in lockstep. Defaults to
     * 86400 (24h). Raise it for longer review windows.
     */
    ttl: z.number().int().positive().optional(),
    /** Advanced: override the Mongo collection names used for checkpoints. */
    checkpointCollectionName: z.string().optional(),
    checkpointWritesCollectionName: z.string().optional(),
  })
  .optional();

export type TCheckpointerConfig = z.infer<typeof checkpointerSchema>;

const codeEnvironmentBaseURLSchema = z
  .string()
  .trim()
  .url()
  .refine(
    (value) => {
      try {
        const url = new URL(value);
        return (
          (url.protocol === 'http:' || url.protocol === 'https:') &&
          !value.includes('?') &&
          !value.includes('#') &&
          url.search.length === 0 &&
          url.hash.length === 0
        );
      } catch {
        return false;
      }
    },
    { message: 'Code environment baseURL must be an HTTP(S) base URL without query or fragment' },
  );

export function isSecureCodeEnvironmentControlURL(baseURL: string): boolean {
  try {
    const url = new URL(baseURL.trim());
    if (url.protocol === 'https:') return true;
    if (url.protocol !== 'http:') return false;
    return url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
  } catch {
    return false;
  }
}

export const codeEnvironmentPermissionDecisionSchema = z.enum(['allow', 'ask', 'deny']);
export type CodeEnvironmentPermissionDecision = z.infer<
  typeof codeEnvironmentPermissionDecisionSchema
>;

const codeEnvironmentPermissionFieldSchema = z
  .object({
    allowed: z.array(codeEnvironmentPermissionDecisionSchema).min(1),
    default: codeEnvironmentPermissionDecisionSchema.optional().default('ask'),
  })
  .strict()
  .superRefine((field, context) => {
    if (!field.allowed.includes(field.default)) {
      context.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['default'],
        message: 'Permission default must be included in allowed values',
      });
    }
  });

/** Existing attached commands used a fixed 30-second execution budget. */
export const CODE_ENVIRONMENT_COMMAND_TIMEOUT_DEFAULT_MS = 30_000;
/** Protocol-level ceiling; deployments may only lower this value. */
export const CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS = 5 * 60_000;
/** Historical line window for attached workspace reads. */
export const CODE_ENVIRONMENT_READ_FILE_DEFAULT_LINES = 200;
/** Protocol-v1 read ceiling supported by existing workers. */
export const CODE_ENVIRONMENT_READ_FILE_HARD_MAX_LINES = 500;
/**
 * Client retry horizon across Code API admission windows. Also the hard cap:
 * deployments may only lower it. `0` disables client retries, not the server's
 * initial admission wait or an already-admitted operation's execution budget.
 */
export const CODE_ENVIRONMENT_QUEUE_WAIT_DEFAULT_MS = 5 * 60_000;
/** Code API's per-request admission ceiling, independent of the retry horizon. */
export const CODE_ENVIRONMENT_ADMISSION_MAX_MS = 5 * 60_000;
/** Minimum command admission time reserved inside an opted-in HTTP budget. */
export const CODE_ENVIRONMENT_COMMAND_ADMISSION_DEFAULT_MS = 10_000;
/** Five seconds each for command settlement and transport delivery. */
const CODE_ENVIRONMENT_COMMAND_BUDGET_GRACE_MS = 10_000;
/** Maximum opt-in HTTP budget: five minutes of admission and execution plus settlement and delivery. */
export const CODE_ENVIRONMENT_REQUEST_TIMEOUT_HARD_MAX_MS =
  CODE_ENVIRONMENT_ADMISSION_MAX_MS +
  CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS +
  CODE_ENVIRONMENT_COMMAND_BUDGET_GRACE_MS;

export const codeEnvironmentAdmissionSchema = z
  .object({
    durableRequests: z.boolean().optional(),
    transportTimeoutMs: z.number().int().min(1000).max(30000).optional(),
    pollIntervalMs: z.number().int().min(100).max(5000).optional(),
    /** Optional per-request queue ceiling, bounded by transport and execution reserves. */
    queueWaitMs: z.number().int().min(1).max(CODE_ENVIRONMENT_ADMISSION_MAX_MS).optional(),
    initialDelayMs: z.number().int().min(100).max(30_000).optional().default(1_000),
    maxDelayMs: z.number().int().min(100).max(300_000).optional().default(30_000),
    multiplier: z.number().min(1).max(10).optional().default(1),
    /** Additive jitter never advances a server's Retry-After hint. */
    jitterRatio: z.number().min(0).max(1).optional().default(0),
  })
  .strict()
  .refine((policy) => policy.maxDelayMs >= policy.initialDelayMs, {
    path: ['maxDelayMs'],
    message: 'Maximum retry delay must cover the initial delay',
  });

/**
 * Typed user-tunable surface for one attached code environment. Omitted fields
 * remain fixed at LibreChat's safe baseline. Isolation, networking, mounts,
 * privileged execution, and secrets are deliberately not representable here.
 */
export const codeEnvironmentUserConfigSchema = z
  .object({
    permissions: z
      .object({
        fileWrite: codeEnvironmentPermissionFieldSchema.optional(),
        commandExecution: codeEnvironmentPermissionFieldSchema.optional(),
      })
      .strict()
      .optional(),
    admission: codeEnvironmentAdmissionSchema.optional(),
    limits: z
      .object({
        /** Foreground Bash timeout when the call omits timeoutMs. Omission keeps 30 seconds;
         * the effective command ceiling may lower this value. */
        defaultCommandTimeoutMs: z
          .number()
          .int()
          .min(1)
          .max(CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS)
          .optional(),
        /** Attached read_file line window when max_lines is omitted. Omission keeps 200 lines;
         * the existing byte budget can truncate the result sooner. */
        defaultReadFileLines: z
          .number()
          .int()
          .min(1)
          .max(CODE_ENVIRONMENT_READ_FILE_HARD_MAX_LINES)
          .optional(),
        /** Maximum timeout a Bash invocation may request. Omission preserves
         * the historical 30-second command budget. */
        maxCommandTimeoutMs: z
          .number()
          .int()
          .min(1)
          .max(CODE_ENVIRONMENT_COMMAND_TIMEOUT_HARD_MAX_MS)
          .optional(),
        /** Client retry horizon for capacity expirations, shared by preview/edit.
         * Omission keeps five minutes; `0` makes each required operation try once.
         * An in-flight request retains Code API's admission/execution budgets and
         * can finish after this horizon. This is not a server admission timeout. */
        maxQueueWaitMs: z
          .number()
          .int()
          .min(0)
          .max(CODE_ENVIRONMENT_QUEUE_WAIT_DEFAULT_MS)
          .optional(),
        /** Transport ceiling after verifying the shortest timeout on the Code API path.
         * Also the overall call budget unless maxRunTimeoutMs is set. Omission keeps
         * the legacy per-attempt admission and execution budgets. */
        maxRequestTimeoutMs: z
          .number()
          .int()
          .min(1)
          .max(CODE_ENVIRONMENT_REQUEST_TIMEOUT_HARD_MAX_MS)
          .optional(),
        /** Separate overall call deadline across credentials, backoff, and HTTP attempts.
         * Omission preserves maxRequestTimeoutMs as the total budget. */
        maxRunTimeoutMs: z
          .number()
          .int()
          .min(1)
          .max(CODE_ENVIRONMENT_REQUEST_TIMEOUT_HARD_MAX_MS)
          .optional(),
        /** Admission allowance before local dispatch overhead for a Bash command inside
         * the transport/run budgets. Omission reserves ten seconds. */
        minCommandAdmissionMs: z
          .number()
          .int()
          .min(1_000)
          .max(CODE_ENVIRONMENT_ADMISSION_MAX_MS)
          .optional(),
      })
      .strict()
      .superRefine((limits, context) => {
        const budgetMs = Math.min(
          limits.maxRequestTimeoutMs ?? Infinity,
          limits.maxRunTimeoutMs ?? Infinity,
        );
        if (
          budgetMs >
          (limits.minCommandAdmissionMs ?? CODE_ENVIRONMENT_COMMAND_ADMISSION_DEFAULT_MS) +
            CODE_ENVIRONMENT_COMMAND_BUDGET_GRACE_MS
        ) {
          return;
        }
        const field =
          limits.maxRunTimeoutMs === budgetMs ? 'maxRunTimeoutMs' : 'maxRequestTimeoutMs';
        context.addIssue({
          code: z.ZodIssueCode.custom,
          path: [limits.minCommandAdmissionMs == null ? field : 'minCommandAdmissionMs'],
          message: 'Command admission and settlement reserves must leave time for execution',
        });
      })
      .optional(),
    workspaces: z
      .object({
        /** Run requests aimed at `.worktrees/<name>` in that worktree's own lane when the
         * worker advertises linked-worktree lanes. Omission allows it; `false` keeps every
         * request scoped to its checkout. */
        linkedWorktrees: z.boolean().optional(),
        /** Permit explicit per-conversation checkout choices after every API replica supports
         * them. Omission preserves automatic worker isolation and hides the selector. */
        allowCheckoutSelection: z.boolean().optional().default(false),
      })
      .strict()
      .optional(),
    edits: z
      .object({
        /** Whether a worker that negotiated `tolerant_match` may fall back from exact matching
         * to whitespace-tolerant strategies, as skill and sandbox edits already do. Omission
         * allows it; `false` requires every attached-workspace edit to match exactly. */
        tolerantMatching: z.boolean().optional(),
      })
      .strict()
      .optional(),
  })
  .strict();

export type CodeEnvironmentUserConfigSchema = z.infer<typeof codeEnvironmentUserConfigSchema>;

export const codeEnvironmentUserSettingsSchema = z
  .object({
    permissions: z
      .object({
        fileWrite: codeEnvironmentPermissionDecisionSchema.optional(),
        commandExecution: codeEnvironmentPermissionDecisionSchema.optional(),
      })
      .strict()
      .optional(),
  })
  .strict();

export type CodeEnvironmentUserSettings = z.infer<typeof codeEnvironmentUserSettingsSchema>;

export type CodeWorkerEnrollmentPolicy = NonNullable<
  NonNullable<z.infer<typeof agentsEndpointSchema>['statefulCodeSessions']>['principalWorkers']
>;

/** Agents whose S3 avatar refresh is remembered for one user; see `avatarRefresh`. */
export const DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT = 1000;

export const DEFAULT_MAX_PROVIDER_ERROR_CHARS = 2000;
export const DEFAULT_AGENT_MODEL_RESPONSE_BODY_TIMEOUT_MS = 900_000;
export const DEFAULT_AGENT_MODEL_RESPONSE_HEADERS_TIMEOUT_MS = 300_000;
/** Below the idle cutoff of common proxies (nginx 60 s, Cloudflare 100 s), so a
 * stream that is silent while a tool runs is not closed underneath the client. */
export const DEFAULT_STREAM_KEEPALIVE_INTERVAL_MS = 25_000;
export const DEFAULT_CACHE_CLEAR_TIMEOUT_MS = 1000;

export const HOST_FILE_EDIT_HARD_MAX_COUNT = 100;

/** Host-side skill/sandbox edit budgets. Attached workers retain their own limits. */
export const hostFileEditLimitsSchema = z
  .object({
    maxEdits: z
      .number()
      .int()
      .min(1)
      .max(HOST_FILE_EDIT_HARD_MAX_COUNT)
      .default(HOST_FILE_EDIT_HARD_MAX_COUNT),
    maxWorkBytes: z
      .number()
      .int()
      .min(1024)
      .max(256 * 1024 * 1024)
      .default(64 * 1024 * 1024),
    maxOccurrences: z.number().int().min(1).max(1_000_000).default(100_000),
    timeoutMs: z.number().int().min(100).max(10_000).default(2000),
    maxConcurrent: z.number().int().min(1).max(8).default(2),
  })
  .strict();

export type HostFileEditLimits = z.infer<typeof hostFileEditLimitsSchema>;

/** Server-side resource and recovery policy for ephemeral child activity. */
export const subagentActivityConfigSchema = z.object({
  contentRecoveryEnabled: z.boolean().default(false),
  /** Batch public content writes independently of the lossy live activity projection. */
  contentPageBytes: z.number().int().min(1024).max(4_194_304).default(262_144),
  contentFlushMs: z.number().int().min(10).max(10_000).default(250),
  contentSettlementTimeoutMs: z.number().int().min(100).max(60_000).default(1000),
  contentRecoveryGraceMs: z.number().int().min(0).max(300_000).default(30_000),
  contentBatchBytes: z.number().int().min(1024).max(4_194_304).default(65_536),
  contentPendingBytes: z.number().int().min(65_536).max(1_073_741_824).default(8_388_608),
  replayTtlMs: z.number().int().min(1_000).max(86_400_000).default(300_000),
  publicationTimeoutMs: z.number().int().min(100).max(60_000).default(1_000),
  retryAttempts: z.number().int().min(1).max(10).default(3),
  retryBaseDelayMs: z.number().int().min(1).max(10_000).default(100),
  recoveryDelayMs: z.number().int().min(100).max(60_000).default(1_000),
  memoryMaxStreams: z.number().int().min(1).max(100_000).default(1_000),
  memoryMaxBytes: z.number().int().min(65_536).max(1_073_741_824).default(16_777_216),
});

export type TSubagentActivityConfig = z.infer<typeof subagentActivityConfigSchema>;

export const agentsEndpointSchema = baseEndpointSchema
  .omit({ baseURL: true })
  .merge(
    z.object({
      /* agents specific */
      hostFileEdits: hostFileEditLimitsSchema.optional(),
      /** Maximum provider error characters retained in unprotected terminal failures. */
      maxProviderErrorChars: z
        .number()
        .int()
        .min(0)
        .max(1_000_000)
        .default(DEFAULT_MAX_PROVIDER_ERROR_CHARS),
      /** Maximum inactivity between provider response body chunks; 0 disables the idle timeout. */
      modelResponseBodyTimeoutMs: z
        .number()
        .int()
        .min(0)
        .max(86_400_000)
        .default(DEFAULT_AGENT_MODEL_RESPONSE_BODY_TIMEOUT_MS),
      /** Maximum wait for provider response headers; 0 disables the header timeout. */
      modelResponseHeadersTimeoutMs: z
        .number()
        .int()
        .min(0)
        .max(86_400_000)
        .default(DEFAULT_AGENT_MODEL_RESPONSE_HEADERS_TIMEOUT_MS),
      /** Interval between SSE comment frames on an otherwise silent chat stream, so
       * proxies with an idle timeout keep it open; 0 disables the keepalive. */
      streamKeepaliveIntervalMs: z
        .number()
        .int()
        .min(0)
        .max(3_600_000)
        .refine((ms) => ms === 0 || ms >= 1_000, {
          message: 'Use 0 to disable, or at least 1000 ms',
        })
        .default(DEFAULT_STREAM_KEEPALIVE_INTERVAL_MS),
      /** Graph steps an agent run may take; a run with fewer than 1 cannot take a step. */
      recursionLimit: z.number().int().min(1).optional(),
      disableBuilder: z.boolean().optional().default(false),
      /** Optional workspace guidance acquisition budget, separate from command execution. */
      repositoryInstructions: z
        .object({
          timeoutMs: z.number().int().min(100).max(30_000).optional().default(2000),
        })
        .optional(),
      /** How long a turn on an attached workspace may spend copying chat attachments into it
       * before the model runs; unfinished copies fall back to a note and retry next turn. */
      workspaceAttachments: z
        .object({
          timeoutMs: z.number().int().min(1_000).max(120_000).optional().default(10_000),
          /** Workspace requests in flight for the turn, across every agent it primes. */
          concurrency: z.number().int().min(1).max(16).optional().default(3),
        })
        .optional(),
      /** Budget and cache configuration for resolving an agent's linked prompt-group
       * instructions. Omitting the block applies the defaults below. */
      linkedInstructions: z
        .object({
          timeoutMs: z.number().int().min(100).max(30_000).optional().default(2000),
          native: z
            .object({
              /** Content cache TTL for a resolved native prompt link; `0` disables the cache. */
              cacheTtlMs: z.number().int().min(0).max(3_600_000).optional().default(300_000),
              /** Max wait for the cache clear a prompt write triggers before the write's
               * response continues without it. */
              cacheClearTimeoutMs: z
                .number()
                .int()
                .min(1)
                .max(30_000)
                .optional()
                .default(DEFAULT_CACHE_CLEAR_TIMEOUT_MS),
            })
            .optional()
            .prefault({}),
          /** Rollout switch for linking an agent's instructions to a Langfuse prompt group. */
          langfuse: z
            .object({
              enabled: z.boolean().optional().default(false),
            })
            .optional()
            .prefault({}),
        })
        .optional(),
      /** Cap on any agent's `recursion_limit` and on `recursionLimit`. */
      maxRecursionLimit: z.number().int().min(1).optional(),
      /** Max cumulative bytes a single streamed tool call's arguments may reach before the run
       * aborts. Defaults to 64 KiB in the agents SDK; `0` disables the guard. */
      maxToolCallArgBytes: z.number().optional(),
      /** Max streamed chunk events per model generation before the run aborts. Off by default. */
      maxDeltaEventsPerTurn: z.number().optional(),
      /** Per-tool overrides of `maxToolCallArgBytes`, keyed by model-facing tool name; `0`
       * disables the guard for that tool only. Merged over LibreChat's shipped default of
       * `{ create_file: 131072 }`. */
      maxToolCallArgBytesByTool: z.record(z.string(), z.number()).optional(),
      /** Characters of retained tool output the save path may tokenize exactly for the
       * context gauge when a turn stops at the tool-call limit (see
       * `retainedToolTokens`). Tokenizing costs ~60 ms/MB and runs once per stopped
       * turn; past this ceiling the figure is withdrawn rather than estimated, so the
       * gauge under-reports that turn instead of blocking the save. Raise it for
       * deployments whose tools legitimately return more, lower it on slow hardware. */
      maxRetainedToolCountChars: z
        .number()
        .int()
        .min(0)
        .optional()
        .default(DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS),
      maxCitations: z.number().min(1).max(50).optional().default(30),
      maxCitationsPerFile: z.number().min(1).max(10).optional().default(7),
      minRelevanceScore: z.number().min(0.0).max(1.0).optional().default(0.45),
      /** Maximum explicit subagents per agent (`agent_ids` and `graphs`); raised from
       * the shipped default of 10 for orchestration-heavy deployments, bounded by
       * `MAX_SUBAGENTS_CEILING`. */
      maxSubagents: z
        .number()
        .int()
        .min(1)
        .max(MAX_SUBAGENTS_CEILING)
        .optional()
        .default(MAX_SUBAGENTS),
      /** Live replay retention, publication recovery and process-local cache budgets. */
      subagentActivity: subagentActivityConfigSchema.optional(),
      /** Run-scoped file access for explicitly opted-in subagent delegations. */
      fileSharing: z
        .object({
          enabled: z.boolean().optional().default(false),
          allowSiblingSharing: z.boolean().optional().default(false),
          maxFiles: z.number().int().min(1).max(1_000).optional().default(100),
          /** Aggregate disk budget for private output versions retained during a run. */
          maxPrivateBytes: z
            .number()
            .int()
            .min(1)
            .max(10_737_418_240)
            .optional()
            .default(268_435_456),
          ttlMs: z.number().int().min(1).max(86_400_000).optional().default(3_600_000),
        })
        .optional(),
      /** Maximum concurrent Code API uploads per route and authenticated principal. */
      codeApiUploadConcurrency: z.number().int().min(1).max(100).optional().default(3),
      /** Maximum wall-clock time spent waiting on Code API rate limits per operation. */
      codeApiMaxRetryWaitMs: z.number().int().min(0).max(300_000).optional().default(20_000),
      /** S3 avatar re-signing for agent list responses. */
      avatarRefresh: z
        .object({
          /** Per-agent refresh deadlines remembered for one user across pages. Once this
           *  many are held the oldest are dropped, and a dropped agent is signed and
           *  persisted again when a later page shows it, so deployments whose readers
           *  browse past this many S3-backed avatars should raise it. */
          coverageLimit: z
            .number()
            .int()
            .min(1)
            .max(1_000_000)
            .optional()
            .default(DEFAULT_AVATAR_REFRESH_COVERAGE_LIMIT),
        })
        .optional(),
      allowedProviders: z.array(z.union([z.string(), eModelEndpointSchema])).optional(),
      capabilities: z
        .array(z.nativeEnum(AgentCapabilities))
        .optional()
        .default(defaultAgentCapabilities),
      /** Controls which workspace-sharing scopes users may select for stateful code sessions.
       *  Omit this block to preserve the legacy behavior of allowing every scope. */
      statefulCodeSessions: z
        .object({
          allowedEnvironments: z.array(z.enum(STATEFUL_CODE_ENVIRONMENTS)).min(1),
          /** Let new chats pick a machine from their agent's saved allowlist instead of its default.
           * Omission allows it; `false` keeps every agent on its fixed machine. */
          allowEnvironmentSelection: z.boolean().optional(),
          /** Maximum additional machine choices saved on an agent (wire ceiling: 128). */
          maxEnvironmentChoices: z
            .number()
            .int()
            .min(1)
            .max(MAX_AGENT_CODE_ENVIRONMENT_CHOICES)
            .optional(),
          /** Server-only personal worker enrollment policy. Effective principal
           * policy may tighten, but never raise, the deployment ceiling. */
          principalWorkers: z
            .object({
              enabled: z.boolean().optional(),
              /** Defaults to five. Zero disables enrollment; existing machines remain usable. */
              maxPerUser: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).optional(),
              browserSetup: z
                .object({
                  enabled: z.boolean().optional().default(false),
                  /** Canonical public instance URL, including the deployment prefix. */
                  instance: z.string().url(),
                  maxPending: z.number().int().min(1).max(512).optional().default(128),
                  maxPerIp: z.number().int().min(1).max(512).optional().default(5),
                  requestsPerMinute: z.number().int().min(1).max(20000).optional().default(1200),
                  requestsPerIpMinute: z.number().int().min(1).max(2000).optional().default(120),
                  proofWindowMs: z.number().int().min(10000).max(120000).optional().default(60000),
                  maxProofsPerAttempt: z
                    .number()
                    .int()
                    .min(320)
                    .max(10000)
                    .optional()
                    .default(1024),
                  reconcileIntervalMs: z
                    .number()
                    .int()
                    .min(1000)
                    .max(60000)
                    .optional()
                    .default(10000),
                  retentionMs: z
                    .number()
                    .int()
                    .min(600000)
                    .max(604800000)
                    .optional()
                    .default(86400000),
                })
                .optional(),
            })
            .optional(),
          /** Server-only policy letting a conversation's owner move its sealed attached decision
           * onto the environments its agents now use, or recover a missing workspace. Omit to keep
           * sealed decisions immovable. */
          conversationMoves: z
            .object({
              enabled: z.boolean().optional(),
              /** Opt in after every API replica supports attach/detach. Omitted or false keeps
               * the existing move-only policy, including for already-enabled deployments. */
              allowAttachDetach: z.boolean().optional(),
            })
            .optional(),
          /** Operator-managed execution environments. Attached entries route to a
           * Code API deployment backed by an outbound librechat-code worker. */
          environments: z
            .array(
              z.object({
                id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),
                name: z.string().min(1).max(100),
                type: z.enum(['managed', 'attached']),
                baseURL: codeEnvironmentBaseURLSchema,
                default: z.boolean().optional(),
                /** Server-only outbound worker route. Removed from public config. */
                workerId: z
                  .string()
                  .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/)
                  .optional(),
                /** Distinguishes operator policy from a principal-authorized
                 * environment merged into request-scoped server config. */
                owner: z.enum(['deployment', 'principal']).optional().default('deployment'),
                /** Administrator-controlled user-tunable settings. Only fields
                 * represented here may be changed by a principal. */
                configSchema: codeEnvironmentUserConfigSchema.optional(),
                /** Request-scoped effective settings for a principal-owned environment.
                 * Deployment config should define defaults through configSchema instead. */
                settings: codeEnvironmentUserSettingsSchema.optional(),
                /** Server-only enrollment metadata. `tokenEnv` names an
                 * environment variable and never contains the token itself. */
                pairing: z
                  .object({
                    workerId: z
                      .string()
                      .regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/)
                      .optional(),
                    allowPrincipalWorkers: z.boolean().optional().default(false),
                    tokenEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
                  })
                  .superRefine((pairing, pairingContext) => {
                    if (pairing.workerId != null || pairing.allowPrincipalWorkers === true) {
                      return;
                    }
                    pairingContext.addIssue({
                      code: z.ZodIssueCode.custom,
                      message: 'Pairing requires a workerId or principal workers',
                    });
                  })
                  .optional(),
              }),
            )
            .optional(),
        })
        .superRefine((value, context) => {
          if (!value?.environments) return;
          const ids = new Set<string>();
          let defaults = 0;
          let executableEnvironments = 0;
          for (const environment of value.environments) {
            const pairingOnly =
              environment.pairing?.allowPrincipalWorkers === true &&
              environment.pairing.workerId == null &&
              environment.workerId == null;
            if (environment.pairing != null && environment.type !== 'attached') {
              context.addIssue({
                code: z.ZodIssueCode.custom,
                message: 'Only attached code environments may configure pairing',
                path: ['environments', environment.id, 'pairing'],
              });
            }
            if (environment.pairing != null && environment.owner !== 'deployment') {
              context.addIssue({
                code: z.ZodIssueCode.custom,
                message: 'Only deployment-owned code environments may configure pairing',
                path: ['environments', environment.id, 'pairing'],
              });
            }
            if (
              environment.pairing != null &&
              !isSecureCodeEnvironmentControlURL(environment.baseURL)
            ) {
              context.addIssue({
                code: z.ZodIssueCode.custom,
                message: 'Paired code environments require HTTPS outside loopback development',
                path: ['environments', environment.id, 'baseURL'],
              });
            }
            if (
              environment.workerId != null &&
              environment.pairing?.workerId != null &&
              environment.workerId !== environment.pairing.workerId
            ) {
              context.addIssue({
                code: z.ZodIssueCode.custom,
                message: 'Code environment workerId must match pairing.workerId',
                path: ['environments', environment.id, 'workerId'],
              });
            }
            if (pairingOnly && environment.default === true) {
              context.addIssue({
                code: z.ZodIssueCode.custom,
                message: 'Pairing-only code control planes cannot be execution defaults',
                path: ['environments', environment.id, 'default'],
              });
            }
            if (ids.has(environment.id)) {
              context.addIssue({
                code: z.ZodIssueCode.custom,
                message: `Duplicate code environment id: ${environment.id}`,
                path: ['environments'],
              });
            }
            ids.add(environment.id);
            if (!pairingOnly) {
              executableEnvironments += 1;
              if (environment.default === true) defaults += 1;
            }
          }
          if (executableEnvironments > 0 && defaults !== 1) {
            context.addIssue({
              code: z.ZodIssueCode.custom,
              message: 'Exactly one stateful code environment must be the default',
              path: ['environments'],
            });
          }
        })
        .optional(),
      /** Optional trusted origin for in-process agent event delivery. */
      eventDriven: z
        .object({
          selfUrl: z.string().url().optional(),
          /** Days a dead-lettered trigger delivery stays available for operator review and
           * requeue before it is removed with its event payload. Unset keeps dead letters until
           * an operator acts. */
          deadLetterRetentionDays: z.number().int().min(1).max(3650).optional(),
          /** Every replica keeps polling Mongo as a crash-recovery fallback. Wakes
           * keep local delivery prompt; these caps bound work missed across replicas. */
          idlePolling: z
            .object({
              deliveryMaxIntervalMs: z
                .number()
                .int()
                .min(1_000)
                .max(300_000)
                .optional()
                .default(15_000),
              queuedTurnMaxIntervalMs: z
                .number()
                .int()
                .min(30_000)
                .max(300_000)
                .optional()
                .default(120_000),
              maintenanceMaxIntervalMs: z
                .number()
                .int()
                .min(30_000)
                .max(300_000)
                .optional()
                .default(120_000),
              /** Longest a background or subagent completion re-checks whether its
               * result and parent turn are ready. The events it waits on expedite it,
               * so this bounds missed signals rather than normal delivery latency. */
              completionWaitMaxIntervalMs: z
                .number()
                .int()
                .min(5_000)
                .max(300_000)
                .optional()
                .default(60_000),
            })
            .optional(),
        })
        .optional(),
      /** Header pull request chip: finds the pull request for the branch a conversation's code
       *  workspace reports, using a server-held GitHub token. On by default once a token is found
       *  (`token`, else `GITHUB_PULL_REQUEST_TOKEN`, `GITHUB_TOKEN` or `GH_TOKEN`) and a repository
       *  scope is set; `enabled: false` turns it off. */
      pullRequests: z
        .object({
          enabled: z.boolean().optional(),
          /** Where pull requests live: `github` (the default), `gitlab` for merge requests on
           *  gitlab.com or a self-managed GitLab, or `bitbucket` for Bitbucket Cloud. Read from the
           *  YAML only, as `host` is, so an override cannot send the token to another service. */
          provider: z.enum(PULL_REQUEST_PROVIDERS).optional(),
          /** The host the token belongs to: by default `github.com`, `gitlab.com` or `bitbucket.org`
           *  for the provider; a GitHub Enterprise Server or `*.ghe.com` host, or a self-managed
           *  GitLab host. Bitbucket is Cloud only. Read from the YAML only, never an override. */
          host: pullRequestHostSchema.optional(),
          /** Environment variable reference holding a read-only GitHub token, e.g.
           *  `${GITHUB_PULL_REQUEST_TOKEN}`. Never the token itself. Optional: without it the first
           *  of `GITHUB_PULL_REQUEST_TOKEN`, `GITHUB_TOKEN` and `GH_TOKEN` that is set is used. */
          token: pullRequestTokenReferenceSchema.optional(),
          /** Lets each user connect their own account, so lookups use that user's token, rate
           *  limit and repository access instead of the server's. Read from the YAML only, as
           *  `provider` and `host` are. Register `<DOMAIN_SERVER>/api/pull-requests/oauth/callback`
           *  as the callback URL. On GitHub, a GitHub App with read-only permissions is the
           *  recommended client: its user tokens need no scope. A connection belongs to the app
           *  it was made with: changing `clientId`, `provider` or `host` asks users to connect
           *  again. A grant made with another `clientId`, provider or host is never used and
           *  expires with `retentionDays`. A changed `scope` applies to new connections only.
           *  Disconnecting removes every grant of the user. */
          oauth: z
            .object({
              /** Environment variable references, never the values. */
              clientId: pullRequestTokenReferenceSchema,
              clientSecret: pullRequestTokenReferenceSchema,
              /** Space separated scopes to request. Defaults: none on GitHub, `read_api` on
               *  GitLab, and the consumer's own on Bitbucket. */
              scope: z
                .string()
                .trim()
                .max(256)
                .regex(/^[A-Za-z0-9_:.\- ]*$/)
                .optional(),
              /** Minutes a user may take to approve the connection at the provider. Default 10. */
              flowTimeoutMinutes: z.number().int().min(1).max(60).optional(),
              /** Seconds a code exchange or token refresh may take. Default 10. */
              requestTimeoutSeconds: z.number().int().min(1).max(60).optional(),
              /** Days a connection is kept without being used; every use extends it. Default 180. */
              retentionDays: z.number().int().min(1).max(3650).optional(),
            })
            .optional(),
          /** Repositories the token may be used for, as `owner/name` or `owner/*`. A worker reports
           *  its own repository, so without this list a user could point the server's token at any
           *  repository it can read. */
          allowedRepositories: z.array(pullRequestRepositorySchema).max(256).optional(),
          /** Look up every repository a worker reports, limited only by what the token can read.
           *  Off by default: a worker names its own repository, so with this on any user can point
           *  the server's token at any repository it can see. Use a read-only token scoped to the
           *  repositories you are willing to show. */
          allowAllRepositories: z.boolean().optional(),
          /** Seconds a looked-up pull request is reused before GitHub is asked again. */
          cacheTtlSeconds: z.number().int().min(5).max(3600).optional().default(30),
          /** Pull requests cached per credential before the oldest is evicted. Size it to the
           *  distinct repository and branch combinations seen within one cache lifetime, or fresh
           *  results are evicted and GitHub is asked again. */
          cacheMaxEntries: z.number().int().min(10).max(100_000).optional().default(500),
          /** Credentials whose results are cached at once; past it the one idle longest is dropped.
           *  Deployment-wide: when principals configure different values, the largest applies.
           *  Raise it when many tenants each configure their own token. */
          cacheMaxCredentials: z.number().int().min(1).max(10_000).optional().default(256),
          /** Pull request lookups a single sidebar request runs at once. Each lookup is a few
           *  GitHub requests, so this bounds how hard one request leans on the token. */
          maxConcurrentLookups: z.number().int().min(1).max(16).optional().default(4),
          /** Seconds one sidebar request may stay open in total, whatever its lookups are doing. */
          batchTimeoutSeconds: z
            .number()
            .int()
            .min(1)
            .max(PULL_REQUEST_BATCH_TIMEOUT_MAX_SECONDS)
            .optional()
            .default(20),
          /** Longest one GitHub request may take. Raise it behind a slow proxy. */
          requestTimeoutSeconds: z.number().int().min(1).max(60).optional().default(10),
          /** Longest a whole lookup, every request together, may hold the header request. */
          lookupTimeoutSeconds: z.number().int().min(1).max(120).optional().default(30),
          /** Pages of 100 check runs read before the rollup is reported as still running. */
          maxCheckRunPages: z.number().int().min(1).max(50).optional().default(10),
          /** Pull requests listed per state when matching a branch's history to the commit a chat
           *  last ran at. Raise it for branch names that are reused many times. */
          maxCandidatePullRequests: z.number().int().min(1).max(100).optional().default(10),
          /** Pages of those candidates read per state, so a branch name reused more often than one
           *  page holds can still reach an older match. Each page is one request. */
          maxCandidatePages: z.number().int().min(1).max(10).optional().default(1),
          /** Candidates compared with that commit before the search gives up. Each is one request. */
          maxHeadComparisons: z.number().int().min(0).max(20).optional().default(3),
          /** Share looked-up pull requests and GitHub rate limit cooldowns between replicas
           *  through Redis, so each replica does not spend the token on the same answer. Takes
           *  effect only when the deployment runs with Redis (`USE_REDIS`); each replica keeps its
           *  own in-memory cache either way. Only found pull requests and rate limits are shared;
           *  a failed lookup stays with the replica that saw it. */
          sharedCache: z.boolean().optional().default(false),
          /** Longest one shared cache read or write may take, in milliseconds, before a lookup
           *  carries on without it, so a slow Redis cannot hold the header request. A command
           *  still queued at that point, as during a disconnect, is dropped rather than sent later. */
          sharedCacheTimeoutMs: z.number().int().min(10).max(5000).optional().default(250),
          /** Redis keys the shared cache uses at most, for results and again for rate limits:
           *  each goes in a slot picked from its key, replacing what was there. Read from the
           *  YAML only, so every replica and principal addresses the same slot for a lookup. */
          sharedCacheSlots: z.number().int().min(64).max(1_000_000).optional().default(65_536),
        })
        .optional(),
      /** Conversational background-task delivery policy. Automatic completion wakeups are
       * enabled unless an administrator explicitly restores poll-only behavior. */
      backgroundTasks: z
        .object({
          completionWakeups: z.boolean().optional().default(true),
          /** Maximum terminal output copied into the private completion receipt.
           * Generated files remain governed by their separate attachment policy. */
          completionResultMaxChars: z
            .number()
            .int()
            .min(1)
            .max(AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_HARD_MAX)
            .optional()
            .default(AGENT_BACKGROUND_COMPLETION_RESULT_MAX_CHARS_DEFAULT),
          /** Set `false` while replicas older than receipt batching still serve
           * traffic; those replicas cannot read batched (v3) receipts. */
          completionReceiptBatching: z
            .boolean()
            .optional()
            .default(AGENT_BACKGROUND_COMPLETION_RECEIPT_BATCHING_DEFAULT),
          /** Maximum compatible sibling results in one continuation. */
          completionResultBatchSize: z.number().int().min(1).max(16).optional().default(8),
          /** Cooperative cancellation for process-local ordinary tools. Off
           * by default so existing deployments opt into the new control. */
          ordinaryToolCancellation: z.boolean().optional().default(false),
          /** During graceful shutdown, how long an interrupted background tool gets to
           * settle on its own before its result is recorded as interrupted. */
          shutdownInterruptGraceMs: z
            .number()
            .int()
            .min(0)
            .max(60_000)
            .optional()
            .default(AGENT_BACKGROUND_SHUTDOWN_INTERRUPT_GRACE_MS_DEFAULT),
        })
        .optional(),
      skills: z
        .object({
          maxCatalogSkills: z.number().int().min(1).max(100).optional(),
        })
        .optional(),
      managementApi: managementApiSchema.optional(),
      remoteApi: remoteApiSchema.optional(),
      /** Human-in-the-loop tool approval policy. Off by default. */
      toolApproval: toolApprovalPolicySchema,
      /** Ask User question behavior; see {@link askUserQuestionConfigSchema}. */
      askUserQuestion: askUserQuestionConfigSchema,
      /** Durable checkpointer backing tool-approval and Ask User resume.
       *  Defaults to the app's MongoDB when either flow needs it. */
      checkpointer: checkpointerSchema,
    }),
  )
  .prefault({
    disableBuilder: false,
    capabilities: defaultAgentCapabilities,
    maxCitations: 30,
    maxCitationsPerFile: 7,
    minRelevanceScore: 0.45,
    maxSubagents: MAX_SUBAGENTS,
  });

export type TAgentsEndpoint = z.infer<typeof agentsEndpointSchema>;

export const paramDefinitionSchema = z.object({
  key: z.string(),
  description: z.string().optional(),
  type: z.nativeEnum(SettingTypes).optional(),
  default: z.union([z.number(), z.boolean(), z.string(), z.array(z.string())]).optional(),
  showLabel: z.boolean().optional(),
  showDefault: z.boolean().optional(),
  options: z.array(z.string()).optional(),
  range: z
    .object({
      min: z.number(),
      max: z.number(),
      step: z.number().optional(),
      positiveMin: z.number().optional(),
    })
    /** A floor above the ceiling admits nothing but the sentinel, while the
     *  clamp maps every non-negative input onto a maximum the generated schema
     *  then rejects. */
    .refine((value) => value.positiveMin == null || value.positiveMin <= value.max, {
      message: 'range.positiveMin cannot exceed range.max',
      path: ['positiveMin'],
    })
    .optional(),
  enumMappings: z.record(z.string(), z.union([z.number(), z.boolean(), z.string()])).optional(),
  component: z.nativeEnum(ComponentTypes).optional(),
  optionType: z.nativeEnum(OptionTypes).optional(),
  columnSpan: z.number().int().nonnegative().optional(),
  columns: z.number().int().min(1).max(4).optional(),
  label: z.string().optional(),
  placeholder: z.string().optional(),
  labelCode: z.boolean().optional(),
  placeholderCode: z.boolean().optional(),
  descriptionCode: z.boolean().optional(),
  minText: z.number().optional(),
  maxText: z.number().optional(),
  minTags: z.number().min(0).optional(),
  maxTags: z.number().min(0).optional(),
  includeInput: z.boolean().optional(),
  descriptionSide: z.enum(['top', 'right', 'bottom', 'left']).optional(),
  searchPlaceholder: z.string().optional(),
  selectPlaceholder: z.string().optional(),
  searchPlaceholderCode: z.boolean().optional(),
  selectPlaceholderCode: z.boolean().optional(),
});

export const endpointSchema = baseEndpointSchema.merge(
  z.object({
    name: z.string().refine((value) => !eModelEndpointSchema.safeParse(value).success, {
      message: `Value cannot be one of the default endpoint (EModelEndpoint) values: ${Object.values(
        EModelEndpoint,
      ).join(', ')}`,
    }),
    /** Limit this YAML custom endpoint to one tenant. Omit for deployment-wide endpoints. */
    tenantId: z
      .string()
      .min(1)
      .max(128)
      .regex(/^[-a-zA-Z0-9_.]+$/, 'must be a valid tenant id without whitespace')
      .refine((tenantId) => tenantId !== '__SYSTEM__', 'system tenant is not allowed')
      .optional(),
    apiKey: z.string(),
    /** Masked preview of the API key, stored at write time so admin
     * reads can show which key is configured without returning the secret. */
    apiKeyPreview: z.string().optional(),
    baseURL: z.string(),
    models: z.object({
      default: z.array(modelItemSchema).min(1),
      fetch: z.boolean().optional(),
      userIdQuery: z.boolean().optional(),
    }),
    iconURL: z.string().optional(),
    modelDisplayLabel: z.string().optional(),
    /**
     * Forces the endpoint to use a provider's native client / request format
     * instead of the default OpenAI-compatible client. Currently supports
     * `anthropic`, for endpoints that speak the Anthropic `/v1/messages` API
     * (Anthropic itself or Anthropic-compatible gateways). Omit for
     * OpenAI-compatible endpoints.
     */
    provider: z.literal(EModelEndpoint.anthropic).optional(),
    headers: z.record(z.string(), z.string()).optional(),
    addParams: addParamsSchema.optional(),
    dropParams: z.array(z.string()).optional(),
    customParams: z
      .object({
        defaultParamsEndpoint: z.string().default('custom'),
        reasoningFormat: eReasoningParameterFormatSchema.optional(),
        reasoningKey: eReasoningResponseKeySchema.optional(),
        /** Replays `reasoning_content` within a run's tool-call turns (e.g. Xiaomi MiMo, Kimi). */
        includeReasoningContent: z.boolean().optional(),
        /** Also reconstructs `reasoning_content` from persisted history across turns (implies `includeReasoningContent`). */
        includeReasoningHistory: z.boolean().optional(),
        paramDefinitions: z.array(paramDefinitionSchema).optional(),
        /**
         * Milliseconds to wait for each request when reading an OpenRouter endpoint's
         * per-model reasoning efforts. Omission keeps 5000.
         */
        reasoningCatalogTimeoutMs: z.number().int().min(500).max(30000).optional(),
        /**
         * Most pages of an OpenRouter endpoint's model catalog to read before treating it as
         * unavailable. Omission keeps 20.
         */
        reasoningCatalogMaxPages: z.number().int().min(1).max(200).optional(),
        /**
         * Milliseconds a failed or unreadable OpenRouter catalog is remembered before it is
         * requested again; 0 retries on every request. Omission keeps 30000.
         */
        reasoningCatalogFailureTtlMs: z.number().int().min(0).max(600000).optional(),
        /**
         * Milliseconds a successfully read OpenRouter catalog is kept before it is read again.
         * Omission keeps 3600000 (one hour).
         */
        reasoningCatalogTtlMs: z.number().int().min(60000).max(86400000).optional(),
      })
      .strict()
      .optional(),
    directEndpoint: z.boolean().optional(),
    titleMessageRole: z.enum(['system', 'user', 'assistant']).optional(),
    /** Static per-model token config: context window and per-million-token rates */
    tokenConfig: z
      .record(
        z.string(),
        z.object({
          prompt: z.number(),
          completion: z.number(),
          context: z.number(),
          cacheRead: z.number().optional(),
          cacheWrite: z.number().optional(),
          /** 1-hour prompt cache writes; defaults to twice `prompt` */
          cacheWrite1h: z.number().optional(),
        }),
      )
      .optional(),
  }),
);

export type TEndpoint = z.infer<typeof endpointSchema>;

export const azureEndpointSchema = z
  .object({
    groups: azureGroupConfigsSchema,
    assistants: z.boolean().optional(),
  })
  .and(
    /**
     * Azure carries only the base-endpoint fields enumerated here. This is a
     * `.pick()`, NOT an omit, so a field added to `baseEndpointSchema` is
     * silently unavailable on Azure endpoints until it is listed below —
     * unlike `endpoints.all`, which omits and therefore inherits new fields
     * automatically. Keep this list in sync when adding endpoint options.
     */
    endpointSchema
      .pick({
        streamRate: true,
        titleConvo: true,
        titleMethod: true,
        titleModel: true,
        titlePrompt: true,
        titleTiming: true,
        titlePromptTemplate: true,
        activityLabel: true,
        activityModel: true,
        activityEndpoint: true,
        activityPrompt: true,
        activityMaxPerRun: true,
        activityCharLimit: true,
        activityPhaseLabel: true,
        activityPhaseModel: true,
        activityPhaseEndpoint: true,
        activityPhasePrompt: true,
        activityPhaseMaxPerRun: true,
        reasoningLabel: true,
        reasoningLabelModel: true,
        reasoningLabelEndpoint: true,
        reasoningLabelPrompt: true,
        reasoningLabelMinChars: true,
        reasoningLabelUpdateChars: true,
        reasoningLabelUpdateIntervalMs: true,
        reasoningLabelMaxPerRun: true,
      })
      .partial(),
  );

export type TAzureConfig = Omit<z.infer<typeof azureEndpointSchema>, 'groups'> &
  TAzureConfigValidationResult;

/**
 * A Vertex AI location as it appears in the API host (`<region>-aiplatform.googleapis.com`):
 * letters, digits and hyphens only, so no value can name another host.
 */
export const VERTEX_REGION_PATTERN = /^[A-Za-z0-9-]+$/;

/**
 * A Vertex AI project ID or deployment (model) name, each one segment of the request path:
 * letters, digits, `.`, `_`, `:` (domain-scoped projects), `@` (model versions) and `-`, and not
 * only dots, so no value can leave its segment.
 */
export const VERTEX_PATH_SEGMENT_PATTERN = /^(?!\.+$)[A-Za-z0-9._:@-]+$/;

/**
 * A whole `${VAR}` reference to one environment variable: a name of letters, digits and
 * underscores, with nothing around it. Text that only starts with `${` and ends with `}`
 * (`${A}/x#${A}`) is not one.
 */
export const ENV_VAR_REFERENCE_PATTERN = /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/;

/** A Vertex AI setting: a value matching `pattern`, or a whole `${VAR}` reference resolved at load. */
function vertexSettingSchema(pattern: RegExp, label: string) {
  return z
    .string()
    .refine((value) => ENV_VAR_REFERENCE_PATTERN.test(value) || pattern.test(value), {
      message: `Must be a valid Vertex AI ${label} or a \${ENV_VAR} reference`,
    });
}

/**
 * Vertex AI model configuration - similar to Azure model config
 * Allows specifying deployment name for each model
 */
export const vertexModelConfigSchema = z
  .object({
    /** The actual model ID/deployment name used by Vertex AI API */
    deploymentName: vertexSettingSchema(VERTEX_PATH_SEGMENT_PATTERN, 'deployment name').optional(),
  })
  .or(z.boolean());

export type TVertexModelConfig = z.infer<typeof vertexModelConfigSchema>;

/**
 * Vertex AI configuration schema for Anthropic models served via Google Cloud Vertex AI.
 * Similar to Azure configuration, this allows running Anthropic models through Google Cloud.
 */
export const vertexAISchema = z.object({
  /** Enable Vertex AI mode for Anthropic (defaults to true when vertex config is present) */
  enabled: z.boolean().optional(),
  /** Google Cloud Project ID (optional - auto-detected from service key file if not provided) */
  projectId: vertexSettingSchema(VERTEX_PATH_SEGMENT_PATTERN, 'project ID').optional(),
  /** Vertex AI region (e.g., 'us-east5', 'europe-west1') */
  region: vertexSettingSchema(VERTEX_REGION_PATTERN, 'region').default('us-east5'),
  /** Optional: Path to service account key file */
  serviceKeyFile: z.string().optional(),
  /** Optional: Default deployment name for all models (can be overridden per model) */
  deploymentName: vertexSettingSchema(VERTEX_PATH_SEGMENT_PATTERN, 'deployment name').optional(),
  /** Optional: Available models - can be string array or object with deploymentName mapping */
  models: z.union([z.array(z.string()), z.record(z.string(), vertexModelConfigSchema)]).optional(),
});

export type TVertexAISchema = z.infer<typeof vertexAISchema>;

/**
 * The deployment name a Vertex AI request for `modelName` sends, which the client puts in the
 * request path as written: a `models` record entry's own `deploymentName`, else the default
 * `deploymentName` for an entry that is `true` or has none, else (a `models` array, an entry set
 * to `false`, a model not listed) the model name itself.
 */
export function getVertexDeploymentName(
  modelName: string,
  vertexConfig?: Pick<TVertexAISchema, 'models' | 'deploymentName'>,
): string {
  const models = vertexConfig?.models;
  if (models == null || Array.isArray(models)) {
    return modelName;
  }
  const modelConfig = models[modelName];
  if (!modelConfig) {
    return modelName;
  }
  if (typeof modelConfig === 'boolean') {
    return vertexConfig?.deploymentName || modelName;
  }
  return modelConfig.deploymentName || vertexConfig?.deploymentName || modelName;
}

export type TVertexModelMap = Record<string, string>;

/**
 * Validated Vertex AI configuration result
 */
export type TVertexAIConfig = TVertexAISchema & {
  isValid: boolean;
  errors: string[];
  modelNames?: string[];
  modelDeploymentMap?: TVertexModelMap;
};

/**
 * Anthropic endpoint schema with optional Vertex AI configuration.
 * Extends baseEndpointSchema with Vertex AI support.
 */
/**
 * A built-in endpoint whose configured `models` list replaces its `*_MODELS`
 * environment list. Read from the per-request config, so principal overrides
 * can narrow it.
 */
export const modelListEndpointSchema = baseEndpointSchema.merge(
  z.object({
    models: z.array(z.string()).optional(),
  }),
);

export const anthropicEndpointSchema = baseEndpointSchema.merge(
  z.object({
    /** Vertex AI configuration for running Anthropic models on Google Cloud */
    vertex: vertexAISchema.optional(),
    /** Optional: List of available models */
    models: z.array(z.string()).optional(),
  }),
);

export type TAnthropicEndpoint = z.infer<typeof anthropicEndpointSchema>;

/** Masked preview of the API key, stored at write time so admin
 * reads can show which key is configured without returning the secret. */
const apiKeyPreviewSchema = z.string().optional();

const ttsOpenaiSchema = z.object({
  url: z.string().optional(),
  apiKey: z.string(),
  apiKeyPreview: apiKeyPreviewSchema,
  model: z.string(),
  voices: z.array(z.string()),
});

const ttsAzureOpenAISchema = z.object({
  instanceName: z.string(),
  apiKey: z.string(),
  apiKeyPreview: apiKeyPreviewSchema,
  deploymentName: z.string(),
  apiVersion: z.string(),
  model: z.string(),
  voices: z.array(z.string()),
});

const ttsElevenLabsSchema = z.object({
  url: z.string().optional(),
  websocketUrl: z.string().optional(),
  apiKey: z.string(),
  apiKeyPreview: apiKeyPreviewSchema,
  model: z.string(),
  voices: z.array(z.string()),
  voice_settings: z
    .object({
      similarity_boost: z.number().optional(),
      stability: z.number().optional(),
      style: z.number().optional(),
      use_speaker_boost: z.boolean().optional(),
    })
    .optional(),
  pronunciation_dictionary_locators: z.array(z.string()).optional(),
});

const ttsLocalaiSchema = z.object({
  url: z.string(),
  apiKey: z.string().optional(),
  apiKeyPreview: apiKeyPreviewSchema,
  voices: z.array(z.string()),
  backend: z.string(),
});

const ttsSchema = z.object({
  allowedAddresses: allowedAddressesSchema,
  /** Longest text one request may synthesize; each 1,000 characters is a separate paid call. */
  maxInputChars: z.number().int().positive().optional(),
  openai: ttsOpenaiSchema.optional(),
  azureOpenAI: ttsAzureOpenAISchema.optional(),
  elevenlabs: ttsElevenLabsSchema.optional(),
  localai: ttsLocalaiSchema.optional(),
});

const sttOpenaiSchema = z.object({
  url: z.string().optional(),
  apiKey: z.string(),
  apiKeyPreview: apiKeyPreviewSchema,
  model: z.string(),
});

const sttAzureOpenAISchema = z.object({
  instanceName: z.string(),
  apiKey: z.string(),
  apiKeyPreview: apiKeyPreviewSchema,
  deploymentName: z.string(),
  apiVersion: z.string(),
});

const sttSchema = z.object({
  allowedAddresses: allowedAddressesSchema,
  openai: sttOpenaiSchema.optional(),
  azureOpenAI: sttAzureOpenAISchema.optional(),
});

/**
 * The speech providers a schema actually configures. `allowedAddresses` is transport
 * policy rather than a provider, and a provider key present but empty configures
 * nothing. The speech services accept a schema only when exactly one survives here, so
 * the upload router reads availability from the same list and never routes audio to a
 * transcription that cannot run.
 */
export function listConfiguredSpeechProviders(
  schema?: Record<string, unknown> | null,
): Array<[string, Record<string, unknown>]> {
  if (schema == null) {
    return [];
  }
  return Object.entries(schema).filter(
    ([key, value]) =>
      key !== 'allowedAddresses' &&
      value != null &&
      typeof value === 'object' &&
      Object.keys(value).length > 0,
  ) as Array<[string, Record<string, unknown>]>;
}

/** Whether a speech schema names exactly one usable provider. */
export function isSpeechProviderConfigured(schema?: Record<string, unknown> | null): boolean {
  return listConfiguredSpeechProviders(schema).length === 1;
}

const speechTab = z
  .object({
    conversationMode: z.boolean().optional(),
    advancedMode: z.boolean().optional(),
    speechToText: z
      .boolean()
      .optional()
      .or(
        z.object({
          /** Provider names remain valid for backward compatibility and are normalized for clients. */
          engineSTT: z.enum(['browser', 'external', 'openai', 'azureOpenAI']).optional(),
          languageSTT: z.string().optional(),
          autoTranscribeAudio: z.boolean().optional(),
          decibelValue: z.number().optional(),
          autoSendText: z.number().optional(),
        }),
      )
      .optional(),
    textToSpeech: z
      .boolean()
      .optional()
      .or(
        z.object({
          /** Provider names remain valid for backward compatibility and are normalized for clients. */
          engineTTS: z
            .enum(['browser', 'external', 'openai', 'azureOpenAI', 'elevenlabs', 'localai'])
            .optional(),
          voice: z.string().optional(),
          languageTTS: z.string().optional(),
          automaticPlayback: z.boolean().optional(),
          playbackRate: z.number().min(0.25).max(4).optional(),
          cacheTTS: z.boolean().optional(),
        }),
      )
      .optional(),
  })
  .optional();

export enum RateLimitPrefix {
  FILE_UPLOAD = 'FILE_UPLOAD',
  IMPORT = 'IMPORT',
  TTS = 'TTS',
  STT = 'STT',
  EMAIL_CHANGE = 'EMAIL_CHANGE',
  EMAIL_CHANGE_CONFIRM = 'EMAIL_CHANGE_CONFIRM',
}

export const mcpAppRateLimitSchema = z
  .object({
    resourcesPerMinute: z.number().int().positive().default(120),
    toolCallsPerMinute: z.number().int().positive().default(60),
  })
  .prefault({});

export type TMCPAppRateLimits = z.infer<typeof mcpAppRateLimitSchema>;

/** Per-integration budgets, in milliseconds, for outbound calls that run inside a request.
 *  Omitted keys use the server defaults (`DEFAULT_OUTBOUND_TIMEOUTS_MS` in `@librechat/api`). */
/** Node clamps a timer delay above 2^31 - 1 ms to 1 ms, so larger budgets would fail at once. */
const outboundTimeoutMs = z.number().int().positive().max(2_147_483_647).optional();

export const outboundTimeoutsSchema = z.object({
  /** RAG API queries for file search and message context. */
  ragMs: outboundTimeoutMs,
  /** Each OCR provider call (upload, signed URL, OCR, delete). */
  ocrMs: outboundTimeoutMs,
  /** Each action (OpenAPI tool) HTTP call. */
  actionsMs: outboundTimeoutMs,
  /** The OpenAI moderation check that runs before a chat turn. */
  moderationMs: outboundTimeoutMs,
  /** Fetching a stored image by URL to encode it for a provider. */
  imageFetchMs: outboundTimeoutMs,
  /** Each call a built-in tool makes to its API (weather, Wolfram, web search). */
  toolsMs: outboundTimeoutMs,
  /** Each text-to-speech or speech-to-text provider request. */
  speechMs: outboundTimeoutMs,
  /** Each Stable Diffusion image generation request. */
  imageGenerationMs: outboundTimeoutMs,
});

/** Retention for the write-only GENERAL violation log kept per user. */
export const violationLogSchema = z.object({
  /** Newest entries kept per user; older ones are dropped on the next append. */
  maxEntries: z.number().int().positive().optional(),
});

export type TOutboundTimeouts = z.infer<typeof outboundTimeoutsSchema>;

const lookupConcurrency = z.number().int().min(1).max(32).optional();

/** Upper bounds on independent lookups a request runs at once. Omitted keys use the server
 *  defaults (`DEFAULT_LOOKUP_CONCURRENCY` in `@librechat/api`); `1` restores serial lookups. */
export const lookupConcurrencySchema = z.object({
  /** Connected agents initialized together per level while discovering a handoff graph. */
  connectedAgentLoads: lookupConcurrency,
  /** MCP tool catalog reads when assembling an ephemeral or added agent. */
  mcpCatalogLookups: lookupConcurrency,
  /** Model spec skill name resolutions. */
  skillNameLookups: lookupConcurrency,
  /** Bundled skill file inspections before a skill is primed. */
  skillFileInspections: lookupConcurrency,
  /** Agent reads while building the resume snapshot of a paused run. */
  resumeAgentLoads: lookupConcurrency,
});

export type TLookupConcurrency = z.infer<typeof lookupConcurrencySchema>;

export const rateLimitSchema = z.object({
  twoFactorManagement: z
    .object({
      /** Shared budget; setup needs enable, verify, and confirm within five minutes. */
      requestsPerFiveMinutes: z.number().int().min(3).optional().default(7),
    })
    .optional(),
  agentEvents: z
    .object({
      userMax: z.number().int().positive().optional(),
      userWindowInMinutes: z.number().positive().optional(),
    })
    .optional(),
  /** Limits GET /prompts/groups/:groupId/resolve; keyed by the authenticated user. */
  promptResolve: z
    .object({
      userMax: z.number().int().positive().optional(),
      userWindowInMinutes: z.number().positive().optional(),
    })
    .optional(),
  fileUploads: z
    .object({
      ipMax: z.number().optional(),
      ipWindowInMinutes: z.number().optional(),
      userMax: z.number().optional(),
      userWindowInMinutes: z.number().optional(),
    })
    .optional(),
  conversationsImport: z
    .object({
      ipMax: z.number().optional(),
      ipWindowInMinutes: z.number().optional(),
      userMax: z.number().optional(),
      userWindowInMinutes: z.number().optional(),
    })
    .optional(),
  tts: z
    .object({
      ipMax: z.number().optional(),
      ipWindowInMinutes: z.number().optional(),
      userMax: z.number().optional(),
      userWindowInMinutes: z.number().optional(),
    })
    .optional(),
  stt: z
    .object({
      ipMax: z.number().optional(),
      ipWindowInMinutes: z.number().optional(),
      userMax: z.number().optional(),
      userWindowInMinutes: z.number().optional(),
    })
    .optional(),
  mcpApps: mcpAppRateLimitSchema.unwrap().optional(),
  /** Requesting a change of the registered email; keyed by the authenticated user. */
  emailChange: z
    .object({
      userMax: z.number().optional(),
      userWindowInMinutes: z.number().optional(),
    })
    .optional(),
  /** Confirming one; the endpoint is unauthenticated, so the source address is bounded too. */
  emailChangeConfirm: z
    .object({
      ipMax: z.number().optional(),
      ipWindowInMinutes: z.number().optional(),
      userMax: z.number().optional(),
      userWindowInMinutes: z.number().optional(),
    })
    .optional(),
});

export function resolveMCPAppRateLimits(
  rateLimits?: z.input<typeof rateLimitSchema>,
): TMCPAppRateLimits {
  return mcpAppRateLimitSchema.parse(rateLimits?.mcpApps);
}

export enum EImageOutputType {
  PNG = 'png',
  WEBP = 'webp',
  JPEG = 'jpeg',
}

/** Schemes a configured link may use: web pages, and the mail and phone links that run no script. */
const LINK_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
/**
 * A link's scheme as a reader finds it. It skips what either reader strips from the front: the
 * WHATWG URL parser strips C0 controls and spaces, and `String.prototype.trim()` (which clients
 * apply first) strips Unicode white space such as U+00A0, U+FEFF, U+2028 and U+3000; skipping
 * both at once covers either reader, and either order. Inside the scheme it allows the tabs and
 * newlines the URL parser removes. Only the front of a link decides its scheme, so the match is
 * anchored there and ends with the scheme: the skipped characters cannot start a scheme, so a
 * failed match gives each one back once, and nothing after the scheme is read at all.
 */
// eslint-disable-next-line no-control-regex
const URL_SCHEME = /^[\u0000-\u0020\s]*([a-z][a-z\d+.\t\n\r-]*):/i;
const URL_TAB_OR_NEWLINE = /[\t\n\r]/g;

/**
 * Whether a configured link, such as a privacy policy or terms of service `externalUrl`, may be
 * rendered as an `href` on the app's pages, the signed-out sign-in page included: an http(s),
 * `mailto:` or `tel:` URL, a URL relative to the app (which keeps the page's http(s) scheme),
 * or a blank value, which publishes no link. The scheme is read the way the URL parser browsers
 * use reads it, after the trimming clients apply, so letter case, white space (Unicode white
 * space included) and control characters cannot disguise one that runs script, such as
 * `javascript:` or `data:`. Only the scheme is judged: a malformed http(s) URL is not opened by
 * a browser at all, so it stays accepted as it always was.
 */
export function isSafeLinkUrl(url: string): boolean {
  const scheme = URL_SCHEME.exec(url)?.[1];
  return scheme == null || LINK_SCHEMES.has(scheme.replace(URL_TAB_OR_NEWLINE, '').toLowerCase());
}

const linkUrlSchema = z
  .string()
  .refine(isSafeLinkUrl, { message: 'must be an http(s), mailto: or tel: URL, or a relative URL' });

const termsOfServiceSchema = z.object({
  externalUrl: linkUrlSchema.optional(),
  openNewTab: z.boolean().optional(),
  modalAcceptance: z.boolean().optional(),
  modalTitle: z.string().optional(),
  modalContent: z.string().or(z.array(z.string())).optional(),
});

export type TTermsOfService = z.infer<typeof termsOfServiceSchema>;

// Schema for localized string (either simple string or language-keyed object)
const localizedStringSchema = z.union([z.string(), z.record(z.string(), z.string())]);

export const mcpRefreshDefaults = {
  toolsRefreshInterval: 5 * 60 * 1000,
  statusRefreshInterval: 30 * 1000,
};

/** Default confirmation window for a client-side steer escalation arm. */
export const DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS = 10_000;
export const DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS = 60_000;
/** Last-resort expiry of the client's per-pane queued-send lock. */
export const DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS = 60_000;
/** How many recently touched files the composer palette offers to reuse. */
export const DEFAULT_COMPOSER_RECENT_FILES = 5;
/** Milliseconds a left conversation's message history stays cached in the browser. */
export const DEFAULT_HISTORY_CACHE_TTL_MS = 60_000;
/** Most recently left conversations whose message history keeps that grace. */
export const DEFAULT_HISTORY_CACHE_RECENT = 1;
/** Estimated payload bytes retained across inactive conversation histories. */
export const DEFAULT_HISTORY_CACHE_MAX_BYTES = 8 * 1024 * 1024;

const mcpServersSchema = z
  .object({
    /** Foreground polling intervals in milliseconds; 0 disables polling. */
    toolsRefreshInterval: z.number().int().nonnegative().max(2_147_483_647).optional(),
    statusRefreshInterval: z.number().int().nonnegative().max(2_147_483_647).optional(),
    placeholder: z.string().optional(),
    use: z.boolean().optional(),
    create: z.boolean().optional(),
    share: z.boolean().optional(),
    public: z.boolean().optional(),
    configureObo: z.boolean().optional(),
    trustCheckbox: z
      .object({
        label: localizedStringSchema.optional(),
        subLabel: localizedStringSchema.optional(),
      })
      .optional(),
  })
  .optional();

/** Values the trace viewer uses for any `interface.traceViewer` field left unset. */
export const traceViewerDefaults = {
  enabled: false,
  showInputOutput: false,
  showToolNames: false,
  maxRecords: 1000,
  maxContentLength: 50_000,
  requestsPerMinute: 30,
  requestTimeoutMs: 10_000,
} as const;

type TraceViewerLimitField =
  | 'maxRecords'
  | 'maxContentLength'
  | 'requestsPerMinute'
  | 'requestTimeoutMs';

/** Inclusive bounds for the numeric `interface.traceViewer` fields. */
export const traceViewerLimits: Readonly<
  Record<TraceViewerLimitField, { readonly min: number; readonly max: number }>
> = {
  maxRecords: { min: 1, max: 10_000 },
  maxContentLength: { min: 1, max: 1_000_000 },
  requestsPerMinute: { min: 1, max: 1000 },
  requestTimeoutMs: { min: 1000, max: 300_000 },
};

const boundedIntegerSchema = (field: TraceViewerLimitField) =>
  z.number().int().min(traceViewerLimits[field].min).max(traceViewerLimits[field].max).optional();

const traceViewerSchema = z.object({
  /** Shows the conversation trace control for traces this deployment exported. */
  enabled: z.boolean().optional(),
  /** Returns observation input, output and metadata in the record inspector. */
  showInputOutput: z.boolean().optional(),
  /**
   * Names the tools of each tool round from the tracing backend's own record of the round, at the
   * cost of further backend reads per listed page, which carry each round's input and output.
   * Off, a round is named only when the chat's messages can be matched to the trace.
   */
  showToolNames: z.boolean().optional(),
  /** Observations read from the tracing backend per request. */
  maxRecords: boundedIntegerSchema('maxRecords'),
  /** Characters kept from each input, output and metadata value before truncation. */
  maxContentLength: boundedIntegerSchema('maxContentLength'),
  /** Trace reads one user may start per minute. */
  requestsPerMinute: boundedIntegerSchema('requestsPerMinute'),
  /** Budget for each round trip to the tracing backend, in milliseconds. */
  requestTimeoutMs: boundedIntegerSchema('requestTimeoutMs'),
});

export type TTraceViewerConfig = z.infer<typeof traceViewerSchema>;
export type TResolvedTraceViewerConfig = {
  enabled: boolean;
  showInputOutput: boolean;
  showToolNames: boolean;
} & Record<TraceViewerLimitField, number>;

function boundedInteger(value: unknown, field: TraceViewerLimitField): number {
  const { min, max } = traceViewerLimits[field];
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= min
    ? Math.min(value, max)
    : traceViewerDefaults[field];
}

/**
 * Fills unset or invalid `interface.traceViewer` fields from
 * {@link traceViewerDefaults}. Admin config overrides reach runtime without
 * schema validation, so every consumer reads the section through this.
 */
export function resolveTraceViewerConfig(
  config?: Partial<Record<keyof TTraceViewerConfig, unknown>> | null,
): TResolvedTraceViewerConfig {
  return {
    enabled: config?.enabled === true,
    showInputOutput: config?.showInputOutput === true,
    showToolNames: config?.showToolNames === true,
    maxRecords: boundedInteger(config?.maxRecords, 'maxRecords'),
    maxContentLength: boundedInteger(config?.maxContentLength, 'maxContentLength'),
    requestsPerMinute: boundedInteger(config?.requestsPerMinute, 'requestsPerMinute'),
    requestTimeoutMs: boundedInteger(config?.requestTimeoutMs, 'requestTimeoutMs'),
  };
}

export enum RetentionMode {
  ALL = 'all',
  TEMPORARY = 'temporary',
  EPHEMERAL = 'ephemeral',
}

const themeModeSchema = z
  .object({
    colors: z.record(
      z.string().regex(/^[a-z][a-z0-9-]*$/),
      z.string().regex(/^\d{1,3} \d{1,3} \d{1,3}$/),
    ),
    appearance: z.record(z.string(), z.string()),
    brands: z.record(z.string(), z.string()),
  })
  .partial()
  .strict();

/**
 * Shape of an inline deployment theme. Token names and value ranges are checked
 * by `collectThemeIssues` in `theme.ts`, which owns the token list.
 */
export const themeDefinitionSchema = z
  .object({
    version: z.literal(1),
    name: z.string().trim().min(1),
    modes: z.object({ light: themeModeSchema, dark: themeModeSchema }).partial().strict(),
    brands: z.record(z.string(), z.string()).optional(),
  })
  .strict();

export type TThemeDefinitionConfig = z.infer<typeof themeDefinitionSchema>;

/** A bundled theme name or an inline theme definition applied to every user. */
export const deploymentThemeSchema = z.union([z.string().trim().min(1), themeDefinitionSchema]);
/** Single source for the quiet period between syntax highlights while a code block streams, and
 *  its bounds; the schema default and the client's normalizer both read them. */
export const DEFAULT_CODE_HIGHLIGHT_THROTTLE_MS = 300;
export const MAX_CODE_HIGHLIGHT_THROTTLE_MS = 60_000;

/** A configured highlight cadence the schema would accept, or the default. */
export function normalizeCodeHighlightThrottleMs(value: unknown): number {
  return typeof value === 'number' &&
    Number.isInteger(value) &&
    value >= 0 &&
    value <= MAX_CODE_HIGHLIGHT_THROTTLE_MS
    ? value
    : DEFAULT_CODE_HIGHLIGHT_THROTTLE_MS;
}

/** One resolved theme mode as plain data: what the shell's boot script replays on the root. */
export type ThemeBootStyle = {
  properties: Array<[string, string]>;
  attributes: Record<string, string>;
};

export type ThemeBootModes = { light: ThemeBootStyle; dark: ThemeBootStyle };

/** Each bundled theme resolved at build time, in `THEME_BOOT_FILE` beside the shell. */
export type BundledThemeBoot = Record<string, ThemeBootModes>;

/** The build output the server reads to hand a bundled theme to the shell's boot script. */
export const THEME_BOOT_FILE = 'theme-boot.json';

/**
 * The id of the JSON block the server embeds in the HTML shell with the deployment's base
 * `interface.theme`, so a first-ever visit paints it before `/api/config` answers. `modes`
 * is present only for a bundled name; an inline definition is resolved by the bundle.
 */
export const DEPLOYMENT_THEME_BOOT_ID = 'deployment-theme-boot';

export type DeploymentThemeBoot = {
  source: z.infer<typeof deploymentThemeSchema>;
  modes?: ThemeBootModes;
};

/** Single source for the agents panel selector's unsearched list cap; the
 * schema default and the client fallback both read it. */
export const DEFAULT_AGENT_SELECTOR_LIMIT = 10;
export const AGENT_SELECTOR_LIMIT_MIN = 1;
export const AGENT_SELECTOR_LIMIT_MAX = 100;

/** Runtime guard for values that bypass `interfaceSchema`: raw librechat.yaml
 * reads and principal-scoped admin overrides reach the client unparsed, so an
 * out-of-bounds value falls back to the default instead of emptying the list. */
export function normalizeAgentSelectorLimit(value: unknown): number {
  return typeof value === 'number' &&
    Number.isInteger(value) &&
    value >= AGENT_SELECTOR_LIMIT_MIN &&
    value <= AGENT_SELECTOR_LIMIT_MAX
    ? value
    : DEFAULT_AGENT_SELECTOR_LIMIT;
}

/** Retention modes that apply expiration deadlines to all data, not just user-marked temporary chats. */
export const isAllDataRetention = (mode?: RetentionMode | null): boolean =>
  mode === RetentionMode.ALL || mode === RetentionMode.EPHEMERAL;

/** Whether the retention mode forces every conversation to be temporary, overriding the per-chat toggle. */
export const isForcedTemporaryRetention = (mode?: RetentionMode | null): boolean =>
  mode === RetentionMode.EPHEMERAL;

export const interfaceSchema = z
  .object({
    theme: deploymentThemeSchema.optional(),
    privacyPolicy: z
      .object({
        externalUrl: linkUrlSchema.optional(),
        openNewTab: z.boolean().optional(),
      })
      .optional(),
    termsOfService: termsOfServiceSchema.optional(),
    customWelcome: z.string().optional(),
    /** What heads the welcome screen when an agent, assistant or branded spec is
     *  selected: its name (`entity`), or the time-of-day greeting with the user's
     *  name (`greeting`) for deployments whose header selector already names it. */
    landingHeading: z.enum(['entity', 'greeting']).optional(),
    /** Shows the generic disclaimer and policy links beneath the welcome screen's
     *  composer. A configured `customFooter` still renders when this is false. */
    landingFooter: z.boolean().optional(),
    mcpServers: mcpServersSchema.optional(),
    modelSelect: z.boolean().optional(),
    /** Set to false during a rolling upgrade, until every API replica supports title ownership and old title jobs drain. */
    runningChatRename: z.boolean().default(true),
    /** Milliseconds between syntax highlights while a code block streams. */
    codeHighlightThrottleMs: z
      .number()
      .int()
      .min(0)
      .max(MAX_CODE_HIGHLIGHT_THROTTLE_MS)
      .default(DEFAULT_CODE_HIGHLIGHT_THROTTLE_MS),
    /** Most agents the agents panel selector lists before a search term is
     * typed; typing lifts the cap so search reaches every agent. */
    agentSelectorLimit: z
      .number()
      .int()
      .min(AGENT_SELECTOR_LIMIT_MIN)
      .max(AGENT_SELECTOR_LIMIT_MAX)
      .default(DEFAULT_AGENT_SELECTOR_LIMIT),
    parameters: z.boolean().optional(),
    multiConvo: z.boolean().optional(),
    bookmarks: z.boolean().optional(),
    memories: z.boolean().optional(),
    presets: z.boolean().optional(),
    prompts: z
      .union([
        z.boolean(),
        z.object({
          use: z.boolean().optional(),
          create: z.boolean().optional(),
          share: z.boolean().optional(),
          public: z.boolean().optional(),
        }),
      ])
      .optional(),
    agents: z
      .union([
        z.boolean(),
        z.object({
          use: z.boolean().optional(),
          create: z.boolean().optional(),
          share: z.boolean().optional(),
          public: z.boolean().optional(),
        }),
      ])
      .optional(),
    temporaryChat: z.boolean().optional(),
    temporaryChatRetention: z.number().min(1).max(8760).optional(),
    generalChatRetention: z.number().min(1).max(8760).optional(),
    autoSubmitFromUrl: z.boolean().optional(),
    /** Accept `?theme=dark|light|system` on an entry link as the user's colour mode, so another app can hand its mode over. */
    colorModeFromUrl: z.boolean().optional(),
    retentionMode: z.nativeEnum(RetentionMode).default(RetentionMode.TEMPORARY),
    retainAgentFiles: z.boolean().optional(),
    runCode: z.boolean().optional(),
    webSearch: z.boolean().optional(),
    contextUsage: z.boolean().optional(),
    contextCost: z.boolean().optional(),
    /** Opening the artifacts pane in its own browser window. Enabled by
     *  default; a deployment that cannot use popups can turn it off and keep
     *  the docked pane. */
    artifactUndocking: z.boolean().optional(),
    /** Asks each viewer for consent before Google Tag Manager (`ANALYTICS_GTM_ID`)
     *  loads. A deployment that settles consent itself, such as an internal one
     *  covered by its own policy, can set false to load the container without the
     *  banner or the Settings toggle. */
    analyticsConsent: z.boolean().optional(),
    feedback: z.boolean().optional(),
    currency: z
      .object({
        code: z.string(),
        rate: z.number().positive(),
      })
      .optional(),
    peoplePicker: z
      .object({
        users: z.boolean().optional(),
        groups: z.boolean().optional(),
        roles: z.boolean().optional(),
      })
      .optional(),
    marketplace: z
      .object({
        use: z.boolean().optional(),
        /** Backoff steps, in milliseconds, before each automatic retry of a failed
         *  marketplace request; the count is also how many automatic attempts there are.
         *  An empty array leaves only the manual Retry. Omit for LibreChat's sequence. */
        retryDelaysMs: z.array(z.number().int().min(0).max(600_000)).max(20).optional(),
      })
      .optional(),
    fileSearch: z.boolean().optional(),
    fileCitations: z.boolean().optional(),
    traceViewer: traceViewerSchema.optional(),
    /** Tool keys (and `'mcp'` or an MCP server name) pinned to the prompt bar by default */
    defaultPinnedTools: z.array(z.string()).optional(),
    buildInfo: z.boolean().optional(),
    /** Allows Lia, the welcome screen mascot. Users still opt in from Settings. */
    mascot: z.boolean().optional(),
    remoteAgents: z
      .object({
        use: z.boolean().optional(),
        create: z.boolean().optional(),
        share: z.boolean().optional(),
        public: z.boolean().optional(),
      })
      .optional(),
    skills: z
      .union([
        z.boolean(),
        z.object({
          use: z.boolean().optional(),
          create: z.boolean().optional(),
          share: z.boolean().optional(),
          public: z.boolean().optional(),
          defaultActiveOnShare: z.boolean().optional(),
        }),
      ])
      .optional(),
    sharedLinks: z
      .union([
        z.boolean(),
        z.object({
          create: z.boolean().optional(),
          share: z.boolean().optional(),
          public: z.boolean().optional(),
          snapshotFiles: z.boolean().optional(),
        }),
      ])
      .optional(),
    /**
     * What the reply-alert capabilities may do on this deployment. Each field gates a
     * capability rather than setting it: the preferences themselves stay per device, because
     * notification permission and audio output belong to the machine the reader sits at.
     */
    replyNotifications: z
      .object({
        /** Whether an unseen count may reach the tab title and favicon. */
        tabBadge: z.boolean().optional(),
        /** Whether readers may turn on desktop notifications for replies. */
        desktop: z.boolean().optional(),
        /** Whether readers may turn on the reply chime. */
        sound: z.boolean().optional(),
        /**
         * How many conversations one away poll looks at. A reply lifts its conversation, so the
         * newest activity is what the first page holds.
         *
         * Bounded by the conversation list's own maximum page, which the server clamps every
         * request to: advertising a wider range here would accept a number the read silently
         * truncates. Covering a deployment whose replies outpace a single page wants the
         * server-side unseen query rather than a larger page.
         */
        pollLimit: z.number().int().min(1).max(100).optional(),
        /** Milliseconds between list checks while the tab is unfocused and an away alert is on. */
        pollIntervalMs: z.number().int().min(10_000).max(600_000).optional(),
        /**
         * Milliseconds between list refreshes while the tab is focused, so a reply produced
         * elsewhere eventually shows its dot. Deliberately far slower than the away poll.
         *
         * Capped at five minutes because this refresh is what renews the unfiltered discovery
         * snapshot, and the client holds an unobserved snapshot authoritative for five minutes:
         * a slower refresh would let it lapse, dropping its unseen rows from the count until the
         * next one.
         */
        focusedRefreshMs: z.number().int().min(60_000).max(300_000).optional(),
      })
      .default({
        tabBadge: true,
        desktop: true,
        sound: true,
        pollLimit: 100,
        pollIntervalMs: 30_000,
        focusedRefreshMs: 300_000,
      }),
    schedules: z
      .union([
        z.boolean(),
        z.object({
          use: z.boolean().optional(),
          create: z.boolean().optional(),
          maxPerUser: z.number().int().min(0).optional(),
          minIntervalMinutes: z.number().int().min(1).optional(),
          autoDisableAfterFailures: z.number().int().min(1).optional(),
          admissionConcurrency: z.number().int().min(1).max(100).optional(),
          fireConcurrency: z.number().int().min(1).optional(),
          mcpConsent: z
            .object({
              enabled: z.boolean().optional(),
              maxLifetimeHours: z.number().int().min(1).max(8760).optional(),
              resources: z.record(z.string(), scheduledMCPResourceBindingSchema).optional(),
              /** Trusted service declarations, keyed by raw server and upstream tool name. */
              readOnlyPolicy: z.record(z.string(), scheduledMCPReadOnlyPolicySchema).optional(),
            })
            .optional(),
          /** Bounded exponential receipt retry interval; equal jitter prevents outage waves. */
          mcpReceiptRetry: z
            .object({
              baseMs: z.number().int().min(100).max(60_000).optional(),
              maxMs: z.number().int().min(100).max(600_000).optional(),
            })
            .refine(
              (value) => (value.maxMs ?? 30_000) >= (value.baseMs ?? 250),
              'Receipt retry maxMs must be at least baseMs',
            )
            .optional(),
          mcpPreflightConcurrency: z.number().int().min(1).max(10).optional(),
          mcpPreflightTimeoutMs: z.number().int().min(1000).max(600000).optional(),
          /** Refuse schedules that are not filed under a chat project. Enforced on
           *  create/update AND at every fire, so raising it later stops schedules
           *  that predate the policy instead of grandfathering them. */
          requireProject: z.boolean().optional(),
          /** Pins every scheduled run to ONE chat project, ignoring any client
           *  choice. Implies `requireProject`. The project must belong to the
           *  schedule's owner, so a deployment-wide value only makes sense with
           *  a per-user/per-role config override. */
          projectId: z.string().trim().min(1).optional(),
        }),
      ])
      .optional(),
    /** Client confirmation window for a steer escalation arm, in milliseconds. */
    steerArmConfirmationTimeoutMs: z
      .number()
      .int()
      .positive()
      .max(2_147_483_647)
      .default(DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS),
    /** How long the client keeps reconciling a transport-ambiguous queued turn
     *  before it stops polling, in milliseconds. A slow proxy or a delayed
     *  read replica needs a longer window than the default. */
    queuedTurnReconciliationTimeoutMs: z
      .number()
      .int()
      .positive()
      .max(2_147_483_647)
      .default(DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS),
    /** How long a queued send may hold its pane before the claim is treated as
     *  broken and released, in milliseconds. A healthy start releases it at once;
     *  this only bounds a start that failed without ever reporting progress. */
    queuedSendLockTimeoutMs: z
      .number()
      .int()
      .positive()
      .max(2_147_483_647)
      .default(DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS),
    /** How many recently touched files the composer palette requests and shows
     *  while idle; 0 turns that idle list off. Searching the palette still
     *  finds any of the user's files, since it is the composer's only way to
     *  reuse one. Capped at the file list endpoint's
     *  own default maximum (`fileListLimit`) so the palette can never ask for
     *  more than a typical deployment will return. */
    composerRecentFiles: z.number().int().min(0).max(100).default(DEFAULT_COMPOSER_RECENT_FILES),
    /** Milliseconds a conversation's message history stays cached in the browser after the
     *  user leaves it, so returning soon renders without refetching. Long agent transcripts
     *  run to tens of megabytes each, so mobile browsers need this short. */
    historyCacheTtlMs: z
      .number()
      .int()
      .min(0)
      .max(60 * 60_000)
      .default(DEFAULT_HISTORY_CACHE_TTL_MS),
    /** How many of the most recently left conversations keep that grace; older ones are
     *  released at the next conversation switch. */
    historyCacheRecent: z.number().int().min(0).max(20).default(DEFAULT_HISTORY_CACHE_RECENT),
    /** Aggregate estimated payload budget for histories kept during the grace period.
     *  Oversized histories reload on return; observed, running and Assistants histories stay.
     *  Zero disables the inactive-history grace. This is not a browser heap limit. */
    historyCacheMaxBytes: z
      .number()
      .int()
      .min(0)
      .max(Number.MAX_SAFE_INTEGER)
      .default(DEFAULT_HISTORY_CACHE_MAX_BYTES),
  })
  .prefault({
    modelSelect: true,
    runningChatRename: true,
    codeHighlightThrottleMs: DEFAULT_CODE_HIGHLIGHT_THROTTLE_MS,
    agentSelectorLimit: DEFAULT_AGENT_SELECTOR_LIMIT,
    parameters: true,
    presets: true,
    multiConvo: true,
    bookmarks: true,
    memories: true,
    prompts: {
      use: true,
      create: true,
      share: false,
      public: false,
    },
    agents: {
      use: true,
      create: true,
      share: false,
      public: false,
    },
    temporaryChat: true,
    autoSubmitFromUrl: true,
    colorModeFromUrl: false,
    runCode: true,
    webSearch: true,
    contextUsage: true,
    contextCost: false,
    artifactUndocking: true,
    feedback: true,
    peoplePicker: {
      users: true,
      groups: true,
      roles: true,
    },
    marketplace: {
      use: false,
    },
    mcpServers: {
      use: true,
      create: true,
      share: false,
      public: false,
    },
    fileSearch: true,
    fileCitations: true,
    buildInfo: true,
    mascot: true,
    landingHeading: 'entity',
    landingFooter: true,
    remoteAgents: {
      use: false,
      create: false,
      share: false,
      public: false,
    },
    skills: {
      use: true,
      create: true,
      share: false,
      public: false,
      defaultActiveOnShare: false,
    },
    sharedLinks: {
      create: true,
      share: true,
      public: true,
      snapshotFiles: true,
    },
    replyNotifications: {
      tabBadge: true,
      desktop: true,
      sound: true,
      pollLimit: 100,
      pollIntervalMs: 30_000,
      focusedRefreshMs: 300_000,
    },
    // `schedules` is deliberately ABSENT from this default. It is experimental and
    // default-off in v1, and zod applies this whole object when `interface` is omitted
    // from librechat.yaml — including it would silently enable the feature (and permit
    // billable scheduled runs) on every deployment that never opted in. The PERMISSION
    // defaults live in updateInterfacePermissions, which is a separate concern.
    steerArmConfirmationTimeoutMs: DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS,
    queuedTurnReconciliationTimeoutMs: DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS,
    queuedSendLockTimeoutMs: DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS,
    composerRecentFiles: DEFAULT_COMPOSER_RECENT_FILES,
    historyCacheTtlMs: DEFAULT_HISTORY_CACHE_TTL_MS,
    historyCacheRecent: DEFAULT_HISTORY_CACHE_RECENT,
    historyCacheMaxBytes: DEFAULT_HISTORY_CACHE_MAX_BYTES,
  });

export type TInterfaceConfig = z.infer<typeof interfaceSchema>;
export type TReplyNotificationsConfig = TInterfaceConfig['replyNotifications'];
export type TBalanceConfig = z.infer<typeof balanceSchema>;
export type TTransactionsConfig = z.infer<typeof transactionsSchema>;

export const turnstileOptionsSchema = z
  .object({
    language: z.string().default('auto'),
    size: z.enum(['normal', 'compact', 'flexible', 'invisible']).default('normal'),
  })
  .default({
    language: 'auto',
    size: 'normal',
  });

export const turnstileSchema = z.object({
  siteKey: z.string(),
  options: turnstileOptionsSchema.unwrap().optional(),
});

export type TTurnstileConfig = z.infer<typeof turnstileSchema>;

/** Distinguishes collector acceptance from the proxy's silent 204 authentication drop. */
export const RUM_COLLECTOR_ACK_HEADER = 'x-librechat-rum-accepted';

export const telemetrySchema = z
  .object({
    /**
     * Frames V8 records per error stack (`Error.stackTraceLimit`), applied when librechat.yaml
     * loads. Unset keeps the process default: 10, or `--stack-trace-limit` from NODE_OPTIONS.
     * Deeper stacks cost more on every thrown error.
     */
    stackTraceLimit: z.number().int().min(1).max(1000).optional(),
    rum: z
      .object({
        enabled: z.boolean().optional(),
        sessionReplay: z
          .object({ enabled: z.boolean().default(false) })
          .strict()
          .optional(),
      })
      .strict()
      .optional(),
  })
  .strict();

export type TTelemetryConfig = DeepPartial<z.infer<typeof telemetrySchema>>;

export type TRumConfig = {
  provider: 'hyperdx';
  enabled: boolean;
  url: string;
  serviceName: string;
  authMode: 'publicToken' | 'proxy';
  publicToken?: string;
  tracePropagationTargets?: string[];
  consoleCapture?: boolean;
  disableReplay?: boolean;
  /** Positive replay policy; disableReplay is retained for older browser bundles. */
  sessionReplay?: { enabled: boolean };
  advancedNetworkCapture?: boolean;
  sampleRate?: number;
  environment?: string;
  /** Opt-in, proxy mode only: export client logger warnings/errors as OTLP logs via the RUM proxy. */
  clientLogs?: boolean;
};

export type StartupConfigContext = 'share';

/**
 * Per-endpoint dropParams for the startup config. Most endpoints (e.g. `custom`) map a
 * provider name directly to its dropParams. `azureOpenAI` instead maps a provider name to
 * a per-model dropParams lookup, since each Azure group can drop different parameters.
 */
export type EndpointsDropParamsMap = Record<string, string[] | Record<string, string[]>>;

export type TMCPAppOperationLimits = {
  maxBytes: number;
  timeoutMs: number;
  maxActive: number;
};

export const DEFAULT_MCP_APP_OPERATION_LIMITS: TMCPAppOperationLimits = {
  maxBytes: 4 * 1024 * 1024,
  timeoutMs: 30_000,
  maxActive: 16,
};

export function resolveMCPAppOperationLimits(
  limits?: Partial<TMCPAppOperationLimits>,
): TMCPAppOperationLimits {
  return { ...DEFAULT_MCP_APP_OPERATION_LIMITS, ...limits };
}

export type TMCPAppsPolicy = {
  enabled: boolean;
  legacyHtmlEnabled: boolean;
  cspLimits?: MCPAppCspLimits;
  /** Server-enforced UTF-8 JSON byte cap for one persisted MCP App artifact. */
  maxPersistedAppBytes?: number;
  /** Shared per-user ceiling applied before principal-scoped MCP App admission. */
  maxAdmissionRequestsPerMinute?: number;
  /** Maximum simultaneously opened App views per authenticated host. */
  maxActiveViews?: number;
  /** Maximum UTF-16 characters displayed for an App-requested action before denying it. */
  maxActionPreviewChars?: number;
  /** Server-side bounds for App operations; never derived from App-provided content. */
  operationLimits?: TMCPAppOperationLimits;
  /** Deployment-owned dedicated Sandbox Proxy URL published to authenticated clients. */
  sandboxUrl?: string;
};

/** Aggregate App-bearing message target; cannot exceed the safe storage ceiling. */
export const DEFAULT_MCP_APP_MESSAGE_BYTES: number = 12 * 1024 * 1024;
export const MAX_MCP_APP_MESSAGE_BYTES: number = 12 * 1024 * 1024;
export const DEFAULT_MCP_APP_PERSISTED_BYTES = 1024 * 1024;
export const MAX_MCP_APP_PERSISTED_BYTES = 4 * 1024 * 1024;
export const DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE = 240;
export const DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS = 3;
export const MAX_MCP_APP_ACTIVE_VIEWS = 32;
export const DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS = 16_384;
export const MAX_MCP_APP_ACTION_PREVIEW_CHARS = 131_072;

export const DEFAULT_MCP_APPS_POLICY: TMCPAppsPolicy = {
  enabled: false,
  legacyHtmlEnabled: false,
  maxPersistedAppBytes: DEFAULT_MCP_APP_PERSISTED_BYTES,
  maxAdmissionRequestsPerMinute: DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
  maxActiveViews: DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
  maxActionPreviewChars: DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
};

export function resolveMCPAppsPolicy(
  value?: boolean,
  cspLimits?: Partial<MCPAppCspLimits>,
  maxPersistedAppBytes = DEFAULT_MCP_APP_PERSISTED_BYTES,
  maxAdmissionRequestsPerMinute = DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE,
  sandboxUrl?: string,
  maxActiveViews = DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS,
  maxActionPreviewChars = DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS,
  operationLimits?: Partial<TMCPAppOperationLimits>,
): TMCPAppsPolicy {
  return {
    enabled: value === true,
    legacyHtmlEnabled: value !== false,
    ...(cspLimits != null ? { cspLimits: resolveMCPAppCspLimits(cspLimits) } : {}),
    maxPersistedAppBytes,
    maxAdmissionRequestsPerMinute,
    maxActiveViews,
    maxActionPreviewChars,
    ...(operationLimits != null
      ? { operationLimits: resolveMCPAppOperationLimits(operationLimits) }
      : {}),
    ...(sandboxUrl !== undefined ? { sandboxUrl } : {}),
  };
}

export const CONVERSATION_TITLE_OWNERSHIP_VERSION = 1 as const;

/** Missing capability means an older replica, even when its YAML has the new option. */
export function supportsConversationTitleOwnership(config?: {
  conversationTitleOwnershipVersion?: typeof CONVERSATION_TITLE_OWNERSHIP_VERSION;
  interface?: Pick<TInterfaceConfig, 'runningChatRename'>;
}): boolean {
  return (
    config?.conversationTitleOwnershipVersion === CONVERSATION_TITLE_OWNERSHIP_VERSION &&
    config.interface?.runningChatRename === true
  );
}

export type TStartupConfig = {
  conversationTitleOwnershipVersion?: typeof CONVERSATION_TITLE_OWNERSHIP_VERSION;
  appTitle: string;
  socialLogins?: string[];
  langfuseFanoutEnabled?: boolean;
  langfuseConnectionAccess?: boolean;
  langfusePromptSyncAccess?: boolean;
  /** Whether this admin also holds `manage:prompts`, the capability the server's
   *  `POST /prompts/sync` route requires in addition to Langfuse settings access. Gates the
   *  "Sync prompts" action in the connection tab; absent (falsy) for an older server. */
  langfusePromptManageAccess?: boolean;
  insightsEnabled?: boolean;
  /** Whether pull requests are active (on unless turned off, with a token and a repository scope);
   *  the header does not ask for a pull request without it. */
  pullRequestsEnabled?: boolean;
  /** Present with `pullRequestsEnabled` once this server has the batch route the sidebar uses. */
  pullRequestsBatchVersion?: typeof PULL_REQUEST_BATCH_VERSION;
  /** `endpoints.agents.pullRequests.maxConcurrentLookups`, so the single-route fallback of an
   *  upgrade in progress keeps to the limit the operator configured. */
  pullRequestsMaxConcurrentLookups?: number;
  /** The provider users can connect their own account to, from `pullRequests.oauth`. */
  pullRequestsConnect?: PullRequestProvider;
  /** Manual context compaction, gated by the same `summarization.enabled`
   *  switch that governs the automatic detour. */
  compactionEnabled?: boolean;
  /** Conversation-owned code-environment decision protocol supported by the API.
   * Clients must not emit selection-less decisions unless this is advertised. */
  codeEnvironmentDecisionVersion?: typeof CODE_ENVIRONMENT_DECISION_VERSION;
  /** Owner moves of a sealed code-environment decision supported by the API. Clients must not
   * offer to move a conversation unless this is advertised. */
  codeEnvironmentMoveVersion?: typeof CODE_ENVIRONMENT_MOVE_VERSION;
  /** Owner attach and detach of a sealed code-environment decision supported by the API. Clients
   * must not offer either unless this is advertised, independently of the move version. */
  codeEnvironmentTransitionVersion?: typeof CODE_ENVIRONMENT_TRANSITION_VERSION;
  /** Additive recovery support. Clients require this and the move capability before replacing
   * a missing workspace. Keeping it separate preserves exact-version checks in older clients. */
  codeWorkspaceRecoveryVersion?: typeof CODE_WORKSPACE_RECOVERY_VERSION;
  /** Subagents follow their parent's attached machine. Clients mirror that routing only when this
   * is advertised. */
  codeWorkspaceInheritanceVersion?: typeof CODE_WORKSPACE_INHERITANCE_VERSION;
  interface?: TInterfaceConfig;
  turnstile?: TTurnstileConfig;
  balance?: TBalanceConfig;
  transactions?: TTransactionsConfig;
  discordLoginEnabled: boolean;
  facebookLoginEnabled: boolean;
  githubLoginEnabled: boolean;
  googleLoginEnabled: boolean;
  openidLoginEnabled: boolean;
  appleLoginEnabled: boolean;
  samlLoginEnabled: boolean;
  passkeyLoginEnabled: boolean;
  /** Per-account passkey enrollment cap, from `passkeys.perUserMax`; post-login only. */
  maxPasskeysPerUser?: number;
  /** What one chat list filter request may name (`conversationList`), resolved from the
   *  deployment's base config as the list route resolves it; post-login only. */
  conversationListLimits?: TConversationListConfig;
  openidLabel: string;
  openidImageUrl: string;
  openidAutoRedirect: boolean;
  samlLabel: string;
  samlImageUrl: string;
  /** LDAP Auth Configuration */
  ldap?: {
    /** LDAP enabled */
    enabled: boolean;
    /** Whether LDAP uses username vs. email */
    username?: boolean;
  };
  serverDomain: string;
  emailLoginEnabled: boolean;
  registrationEnabled: boolean;
  socialLoginEnabled: boolean;
  passwordResetEnabled: boolean;
  twoFactorAuthenticationRequired?: boolean;
  emailEnabled: boolean;
  allowEmailChange: boolean;
  showBirthdayIcon: boolean;
  helpAndFaqURL: string;
  /** Admin panel link, only present for users with admin access */
  adminPanelURL?: string;
  customFooter?: string;
  modelSpecs?: TSpecsConfig;
  projects?: TChatProjectsConfig;
  modelDescriptions?: Record<string, Record<string, string>>;
  sharedLinksEnabled: boolean;
  publicSharedLinksEnabled: boolean;
  /** Whether shared links snapshot conversation files (gates the per-link "share files" checkbox). */
  sharedLinksSnapshotFilesEnabled?: boolean;
  /** Effective default timing for when conversation titles become fetchable.
   * `immediate` = fetch in parallel with the active stream (default);
   * `final` = fetch only after the stream completes (legacy). */
  titleGenerationTiming?: 'immediate' | 'final';
  analyticsGtmId?: string;
  rum?: TRumConfig;
  clientLimits?: TClientLimits;
  bundlerURL?: string;
  staticBundlerURL?: string;
  /** Whether the deployment has a configured RAG service. */
  ragEnabled?: boolean;
  sharePointFilePickerEnabled?: boolean;
  sharePointBaseUrl?: string;
  sharePointPickerGraphScope?: string;
  sharePointPickerSharePointScope?: string;
  openidReuseTokens?: boolean;
  allowAccountDeletion: boolean;
  minPasswordLength?: number;
  webSearch?: {
    searchProvider?: SearchProviders;
    scraperProvider?: ScraperProviders;
    rerankerType?: RerankerTypes;
  };
  cloudFront?: {
    cookieRefresh?: {
      endpoint: string;
      domain: string;
    };
  };
  mcpServers?: Record<
    string,
    {
      customUserVars: Record<
        string,
        {
          title: string;
          description: string;
        }
      >;
      chatMenu?: boolean;
      isOAuth?: boolean;
      startup?: boolean;
      iconPath?: string;
    }
  >;
  mcpPlaceholder?: string;
  mcpApps?: TMCPAppsPolicy;
  conversationImportMaxFileSize?: number;
  buildInfo?: {
    commit?: string | null;
    commitShort?: string | null;
    branch?: string | null;
    buildDate?: string | null;
  };
  fileUploadSseEnabled?: boolean;
  endpointsDropParamsMap?: EndpointsDropParamsMap;
};

export type TSharedLinkStartupInterface = Pick<
  Partial<TInterfaceConfig>,
  | 'privacyPolicy'
  | 'termsOfService'
  | 'codeHighlightThrottleMs'
  | 'theme'
  | 'artifactUndocking'
  | 'analyticsConsent'
>;

export type TSharedLinkStartupConfig = Pick<TStartupConfig, 'appTitle'> &
  Pick<
    Partial<TStartupConfig>,
    'analyticsGtmId' | 'bundlerURL' | 'customFooter' | 'staticBundlerURL'
  > & {
    interface?: TSharedLinkStartupInterface;
  };

export enum OCRStrategy {
  MISTRAL_OCR = 'mistral_ocr',
  CUSTOM_OCR = 'custom_ocr',
  AZURE_MISTRAL_OCR = 'azure_mistral_ocr',
  VERTEXAI_MISTRAL_OCR = 'vertexai_mistral_ocr',
  DOCUMENT_PARSER = 'document_parser',
}

export enum SearchCategories {
  PROVIDERS = 'providers',
  SCRAPERS = 'scrapers',
  RERANKERS = 'rerankers',
}

export enum SearchProviders {
  SERPER = 'serper',
  SEARXNG = 'searxng',
  TAVILY = 'tavily',
  KEENABLE = 'keenable',
}

export enum ScraperProviders {
  FIRECRAWL = 'firecrawl',
  SERPER = 'serper',
  TAVILY = 'tavily',
  KEENABLE = 'keenable',
}

export enum RerankerTypes {
  JINA = 'jina',
  COHERE = 'cohere',
  NONE = 'none',
}

export enum SafeSearchTypes {
  OFF = 0,
  MODERATE = 1,
  STRICT = 2,
}

/**
 * Normalizes a SearXNG engine list into the comma-separated form the API expects.
 * Accepts the YAML list or comma-separated string an operator may write, and is
 * applied both at the schema boundary and when loading the runtime config, since
 * `loadCustomConfig` returns the raw YAML object rather than the parsed result.
 */
export function normalizeSearxngEngines(engines?: string | string[]): string | undefined {
  if (engines == null) {
    return undefined;
  }
  const normalized = (Array.isArray(engines) ? engines : engines.split(','))
    .map((engine) => engine.trim())
    .filter(Boolean);
  return normalized.length ? normalized.join(',') : undefined;
}

export const webSearchSchema = z.object({
  allowedAddresses: allowedAddressesSchema,
  serperApiKey: z.string().optional().default('${SERPER_API_KEY}'),
  serperApiKeyPreview: apiKeyPreviewSchema,
  searxngInstanceUrl: z.string().optional().default('${SEARXNG_INSTANCE_URL}'),
  searxngApiKey: z.string().optional().default('${SEARXNG_API_KEY}'),
  searxngApiKeyPreview: apiKeyPreviewSchema,
  firecrawlApiKey: z.string().optional().default('${FIRECRAWL_API_KEY}'),
  firecrawlApiKeyPreview: apiKeyPreviewSchema,
  firecrawlApiUrl: z.string().optional().default('${FIRECRAWL_API_URL}'),
  firecrawlVersion: z.string().optional().default('${FIRECRAWL_VERSION}'),
  tavilyApiKey: z.string().optional().default('${TAVILY_API_KEY}'),
  tavilyApiKeyPreview: apiKeyPreviewSchema,
  tavilySearchUrl: z.string().optional().default('${TAVILY_SEARCH_URL}'),
  tavilyExtractUrl: z.string().optional().default('${TAVILY_EXTRACT_URL}'),
  keenableApiKey: z.string().optional().default('${KEENABLE_API_KEY}'),
  keenableApiKeyPreview: apiKeyPreviewSchema,
  keenableApiUrl: z.string().optional().default('${KEENABLE_API_URL}'),
  jinaApiKey: z.string().optional().default('${JINA_API_KEY}'),
  jinaApiKeyPreview: apiKeyPreviewSchema,
  jinaApiUrl: z.string().optional().default('${JINA_API_URL}'),
  cohereApiKey: z.string().optional().default('${COHERE_API_KEY}'),
  cohereApiKeyPreview: apiKeyPreviewSchema,
  searchProvider: z.nativeEnum(SearchProviders).optional(),
  scraperProvider: z.nativeEnum(ScraperProviders).optional(),
  rerankerType: z.nativeEnum(RerankerTypes).optional(),
  scraperTimeout: z.number().int().nonnegative().optional(),
  safeSearch: z.nativeEnum(SafeSearchTypes).default(SafeSearchTypes.MODERATE),
  firecrawlOptions: z
    .object({
      formats: z.array(z.string()).optional(),
      includeTags: z.array(z.string()).optional(),
      excludeTags: z.array(z.string()).optional(),
      headers: z.record(z.string(), z.string()).optional(),
      waitFor: z.number().optional(),
      timeout: z.number().int().nonnegative().optional(),
      maxAge: z.number().optional(),
      mobile: z.boolean().optional(),
      skipTlsVerification: z.boolean().optional(),
      blockAds: z.boolean().optional(),
      removeBase64Images: z.boolean().optional(),
      parsePDF: z.boolean().optional(),
      storeInCache: z.boolean().optional(),
      zeroDataRetention: z.boolean().optional(),
      location: z
        .object({
          country: z.string().optional(),
          languages: z.array(z.string()).optional(),
        })
        .optional(),
      onlyMainContent: z.boolean().optional(),
      changeTrackingOptions: z
        .object({
          modes: z.array(z.string()).optional(),
          schema: z.record(z.string(), z.unknown()).optional(),
          prompt: z.string().optional(),
          tag: z.string().nullable().optional(),
        })
        .optional(),
    })
    .optional(),
  searxngSearchOptions: z
    .object({
      engines: z
        .union([z.string(), z.array(z.string())])
        .transform(normalizeSearxngEngines)
        .optional(),
      language: z.string().optional(),
      timeRange: z.enum(['day', 'month', 'year']).optional(),
      timeout: z.number().int().positive().max(120000).optional(),
    })
    .optional(),
  tavilySearchOptions: z
    .object({
      searchDepth: z.enum(['basic', 'advanced', 'fast', 'ultra-fast']).optional(),
      maxResults: z.number().int().min(1).max(20).optional(),
      includeImages: z.boolean().optional(),
      includeAnswer: z.union([z.boolean(), z.enum(['basic', 'advanced'])]).optional(),
      includeRawContent: z.union([z.boolean(), z.enum(['markdown', 'text'])]).optional(),
      includeDomains: z.array(z.string()).optional(),
      excludeDomains: z.array(z.string()).optional(),
      topic: z.enum(['general', 'news', 'finance']).optional(),
      timeRange: z.enum(['day', 'week', 'month', 'year', 'd', 'w', 'm', 'y']).optional(),
      includeImageDescriptions: z.boolean().optional(),
      includeFavicon: z.boolean().optional(),
      chunksPerSource: z.number().int().min(1).max(3).optional(),
      safeSearch: z.boolean().optional(),
      timeout: z.number().int().nonnegative().max(120000).optional(),
    })
    .optional(),
  tavilyScraperOptions: z
    .object({
      extractDepth: z.enum(['basic', 'advanced']).optional(),
      includeImages: z.boolean().optional(),
      includeFavicon: z.boolean().optional(),
      format: z.enum(['markdown', 'text']).optional(),
      timeout: z.number().int().nonnegative().max(120000).optional(),
    })
    .optional(),
  keenableSearchOptions: z
    .object({
      maxResults: z.number().int().min(1).max(20).optional(),
      site: z.string().optional(),
      attributionTitle: z.string().optional(),
      timeout: z.number().int().nonnegative().max(120000).optional(),
    })
    .optional(),
  keenableScraperOptions: z
    .object({
      attributionTitle: z.string().optional(),
      timeout: z.number().int().nonnegative().max(120000).optional(),
    })
    .optional(),
});

export type TWebSearchConfig = DeepPartial<z.infer<typeof webSearchSchema>>;

export const ocrSchema = z.object({
  allowedAddresses: allowedAddressesSchema,
  mistralModel: z.string().optional(),
  apiKey: z.string().optional().default('${OCR_API_KEY}'),
  apiKeyPreview: apiKeyPreviewSchema,
  baseURL: z.string().optional().default('${OCR_BASEURL}'),
  strategy: z.nativeEnum(OCRStrategy).default(OCRStrategy.MISTRAL_OCR),
});

export const balanceSchema = z
  .object({
    enabled: z.boolean().optional().default(false),
    startBalance: z.number().optional().default(20000),
    autoRefillEnabled: z.boolean().optional().default(false),
    refillIntervalValue: z.number().optional().default(30),
    refillIntervalUnit: z.enum(REFILL_INTERVAL_UNITS).optional().default('days'),
    refillAmount: z.number().optional().default(10000),
    /** Add credits on exhaustion, or replace the allowance on the next read/request once due. */
    refillMode: z.enum(BALANCE_REFILL_MODES).optional().default('add'),
    reservationTtlMs: z
      .number()
      .int()
      .min(MIN_BALANCE_RESERVATION_TTL_MS)
      .optional()
      .default(DEFAULT_BALANCE_RESERVATION_TTL_MS),
    /** How the UI presents the balance; `credits` keeps the raw figure. */
    display: z.enum(BALANCE_DISPLAY_MODES).optional().default('credits'),
  })
  .superRefine((balance, ctx) => {
    if (
      balance.refillMode === 'reset' &&
      !(Number.isInteger(balance.refillIntervalValue) && balance.refillIntervalValue > 0)
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['refillIntervalValue'],
        message: 'Reset intervals must be positive integers',
      });
    }
  });

export const transactionsSchema = z.object({
  enabled: z.boolean().optional().default(true),
});

export const DEFAULT_MEMORY_MAX_INPUT_TOKENS = 12000;

export const memorySchema = z.object({
  disabled: z.boolean().optional(),
  validKeys: z.array(z.string()).optional(),
  tokenLimit: z.number().optional(),
  charLimit: z.number().optional().default(10000),
  maxInputTokens: z.number().int().positive().optional().default(DEFAULT_MEMORY_MAX_INPUT_TOKENS),
  personalize: z.boolean().default(true),
  messageWindowSize: z.number().optional().default(5),
  agent: z
    .union([
      z.object({
        enabled: z.boolean().optional(),
        id: z.string(),
      }),
      z.object({
        enabled: z.boolean().optional(),
        provider: z.string(),
        model: z.string(),
        instructions: z.string().optional(),
        model_parameters: z
          .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
          .optional(),
      }),
    ])
    .optional(),
});

export type TMemoryConfig = DeepPartial<z.infer<typeof memorySchema>>;

export const summarizationTriggerSchema = z.discriminatedUnion('type', [
  z.object({
    type: z.literal('token_ratio'),
    value: z.number().finite().min(0).max(1),
  }),
  z.object({
    type: z.literal('remaining_tokens'),
    value: z.number().finite().int().positive(),
  }),
  z.object({
    type: z.literal('messages_to_refine'),
    value: z.number().finite().int().positive(),
  }),
]);

export const contextPruningSchema = z.object({
  enabled: z.boolean().optional(),
  keepLastAssistants: z.number().min(0).max(10).optional(),
  softTrimRatio: z.number().min(0).max(1).optional(),
  hardClearRatio: z.number().min(0).max(1).optional(),
  minPrunableToolChars: z.number().min(0).optional(),
});

export const retainRecentConfigSchema = z.object({
  turns: z.number().min(0).max(20).optional(),
  tokens: z.number().positive().optional(),
});

export const summarizationConfigSchema = z.object({
  enabled: z.boolean().optional(),
  provider: z.string().optional(),
  model: z.string().optional(),
  parameters: z
    .record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]))
    .optional(),
  trigger: summarizationTriggerSchema.optional(),
  prompt: z.string().optional(),
  updatePrompt: z.string().optional(),
  reserveRatio: z.number().min(0).max(1).optional(),
  maxSummaryTokens: z.number().positive().optional(),
  contextPruning: contextPruningSchema.optional(),
  retainRecent: retainRecentConfigSchema.optional(),
});

export type SummarizationConfig = z.infer<typeof summarizationConfigSchema>;

const customEndpointsSchema = z.array(endpointSchema.partial()).optional();

/**
 * Validates a messageFilter PII regex at config load. Defaults to native RegExp so browser
 * builds add no extra engine; the server injects a check backed by the linear-time runtime
 * engine (RE2) via setMessageFilterRegexValidator, so a pattern the runtime cannot compile
 * (backreferences, lookaround, control escapes, and so on) is rejected at load rather than
 * silently dropped at request time.
 */
interface MessageFilterRegexValidation {
  readonly supported: boolean;
  readonly programSize?: number;
}

type MessageFilterRegexValidationResult = boolean | MessageFilterRegexValidation;

let messageFilterRegexValidator: (pattern: string) => MessageFilterRegexValidationResult = (
  value,
) => {
  try {
    new RegExp(value, 'g');
    return true;
  } catch {
    return false;
  }
};

export const setMessageFilterRegexValidator = (
  validate: (pattern: string) => MessageFilterRegexValidationResult,
): void => {
  messageFilterRegexValidator = validate;
};

const messageFilterPiiCustomPatternSchema = z.object({
  id: z.string().min(1).max(MAX_PII_PATTERN_ID_LENGTH),
  label: z.string().min(1).max(MAX_PII_PATTERN_LABEL_LENGTH),
  regex: z.string().min(1).max(MAX_PII_PATTERN_LENGTH),
});

export const messageFilterPiiSchema = z
  .object({
    starterPatterns: z
      .array(z.string().max(MAX_PII_PATTERN_ID_LENGTH))
      .max(MAX_PII_PATTERNS_PER_SOURCE)
      .optional(),
    customPatterns: z
      .array(messageFilterPiiCustomPatternSchema)
      .max(MAX_PII_PATTERNS_PER_SOURCE)
      .optional(),
  })
  .superRefine((pii, context) => {
    let regexCharacters = 0;
    let regexInstructions = 0;
    for (let index = 0; index < (pii.customPatterns?.length ?? 0); index++) {
      const pattern = pii.customPatterns?.[index];
      if (pattern == null) {
        continue;
      }
      regexCharacters += pattern.regex.length;
      const result = messageFilterRegexValidator(pattern.regex);
      const supported = typeof result === 'boolean' ? result : result.supported;
      if (!supported) {
        context.addIssue({
          code: z.ZodIssueCode.custom,
          path: ['customPatterns', index, 'regex'],
          message:
            'Unsupported regex: not compatible with the RE2 engine (no backreferences, lookaround, or control escapes)',
        });
        continue;
      }
      if (typeof result !== 'boolean' && result.programSize != null) {
        regexInstructions += result.programSize;
      }
    }
    if (regexCharacters > MAX_PII_CUSTOM_REGEX_CHARACTERS) {
      context.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['customPatterns'],
        message: `Custom PII regexes may contain at most ${MAX_PII_CUSTOM_REGEX_CHARACTERS} characters in total`,
      });
    }
    if (regexInstructions > MAX_PII_CUSTOM_REGEX_INSTRUCTIONS) {
      context.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['customPatterns'],
        message: `Custom PII regexes may compile to at most ${MAX_PII_CUSTOM_REGEX_INSTRUCTIONS} instructions in total`,
      });
    }
  });

export type MessageFilterPiiConfig = z.infer<typeof messageFilterPiiSchema>;

export const messageFilterSchema = z.object({
  pii: messageFilterPiiSchema.optional(),
});

export type MessageFilterConfig = z.infer<typeof messageFilterSchema>;

/** User fields a deployment may select as the Langfuse trace `userId`. */
export const LANGFUSE_TRACE_USER_ID_FIELDS = [
  'id',
  'email',
  'username',
  'name',
  'openidId',
  'samlId',
  'ldapId',
  'googleId',
  'githubId',
  'discordId',
  'appleId',
  'facebookId',
] as const;
export type LangfuseTraceUserIdField = (typeof LANGFUSE_TRACE_USER_ID_FIELDS)[number];

/** User fields a deployment may copy into Langfuse trace metadata. */
export const LANGFUSE_TRACE_USER_METADATA_FIELDS = [
  ...LANGFUSE_TRACE_USER_ID_FIELDS,
  'role',
  'provider',
] as const;
export type LangfuseTraceUserMetadataField = (typeof LANGFUSE_TRACE_USER_METADATA_FIELDS)[number];

/** Request fields a deployment may copy into Langfuse trace metadata. */
export const LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS = [
  'conversationId',
  'endpoint',
  'endpointType',
  'provider',
  'model',
  'modelLabel',
  'spec',
] as const;
export type LangfuseTraceConversationMetadataField =
  (typeof LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS)[number];

/**
 * What a deployment attaches to every Langfuse trace beyond the defaults.
 * Nothing here is exported unless explicitly listed, so the default trace
 * carries only the internal user id and no user or request metadata.
 */
export const langfuseTraceConfigSchema = z.object({
  /**
   * Which user field becomes the trace `userId`. Defaults to the internal user
   * id; a user with no value for the chosen field keeps the internal id.
   */
  userIdField: z.enum(LANGFUSE_TRACE_USER_ID_FIELDS).optional(),
  /** User fields exported as `librechat.user.<field>` trace metadata. */
  userMetadataFields: z.array(z.enum(LANGFUSE_TRACE_USER_METADATA_FIELDS)).optional(),
  /**
   * Request fields exported as trace metadata: `librechat.conversation.id`,
   * `librechat.endpoint`, `librechat.endpoint.type`, `librechat.provider`,
   * `librechat.model`, `librechat.model.label`, and `librechat.spec`.
   */
  conversationMetadataFields: z
    .array(z.enum(LANGFUSE_TRACE_CONVERSATION_METADATA_FIELDS))
    .optional(),
  /**
   * Whether temporary chats, including chats forced temporary by
   * `interface.retentionMode: "ephemeral"`, are traced and receive feedback
   * scores. Defaults to false: a temporary chat reaches no Langfuse destination.
   */
  temporaryChats: z.boolean().optional(),
});

export type LangfuseTraceConfig = z.infer<typeof langfuseTraceConfigSchema>;

/**
 * Format new stored user credentials (tool, web search and MCP custom user variable values)
 * are written in. Both formats are always readable; `legacy` keeps writes readable by
 * replicas on releases that predate `v3` during a rolling upgrade.
 */
export const credentialsConfigSchema = z
  .object({
    writeFormat: z.enum(['v3', 'legacy']).default('v3'),
  })
  .strict();

export type TCredentialsConfig = z.infer<typeof credentialsConfigSchema>;

export const langfuseConfigSchema = z.object({
  enabled: z.boolean().optional(),
  publicKey: z.string().optional(),
  secretKey: z.string().optional(),
  /** Stable Langfuse project identity returned when credentials are verified. */
  projectId: z.string().optional(),
  /** Masked preview of the secret key, stored at write time so
   * admin reads can show which secret key is configured without returning the secret. */
  secretKeyPreview: z.string().optional(),
  /** Routing key for one of the deployment-configured tenant Langfuse destinations. */
  destination: z.string().optional(),
  /**
   * Custom request headers sent on every outbound Langfuse request — trace and
   * media export, feedback scores, and credential verification — for
   * self-hosted instances behind an authenticating proxy or gateway. Values
   * support `${ENV_VAR}` interpolation.
   *
   * Deployment-level only. Trace export batches spans from every user through
   * one exporter, so unlike endpoint headers these cannot carry per-user
   * placeholders. Headers referencing an unset variable, naming an
   * infrastructure secret, or carrying an invalid HTTP field name are dropped
   * with a warning rather than sent.
   *
   * Sent only when the deployment configures exactly one Langfuse origin, and
   * only to that origin. The map cannot say which endpoint it authenticates
   * to, so with several configured origins any choice of recipient would risk
   * disclosing a gateway credential to the others; a warning is logged instead.
   * Multi-destination deployments need per-destination headers, which this
   * schema does not yet express — and note the fanout collector forwards only
   * `Authorization` upstream regardless.
   */
  headers: z.record(z.string(), z.string()).optional(),
  /** Trace user identity and allowlisted user/request metadata. */
  trace: langfuseTraceConfigSchema.optional(),
  /** Tenant admin switch for Langfuse prompt sync. Effective only when the
   *  deployment sets LANGFUSE_PROMPT_SYNC_AVAILABLE.
   *  - enabled: the tenant admin switch itself.
   *  - lockLeaseMs: the per-tenant sync lock lease, in milliseconds (default
   *    300000, clamped to 60000-3600000).
   *  - maxPages: the page cap for one sync request, in pages of up to 100
   *    Langfuse prompts each (default 50, clamped to 1-1000). */
  promptSync: z
    .object({
      enabled: z.boolean().optional(),
      lockLeaseMs: z.number().int().min(60000).max(3600000).optional(),
      maxPages: z.number().int().min(1).max(1000).optional(),
    })
    .optional(),
});

export type LangfuseConfig = z.infer<typeof langfuseConfigSchema>;

export const openIdDiscoverySchema = z.object({
  /** Discovery attempts made before startup continues; `0` retries only in the background. */
  startupAttempts: z.number().int().min(0).max(100).default(1),
  /** Milliseconds between startup and background discovery attempts. */
  retryDelayMs: z.number().int().min(100).max(3_600_000).default(5000),
});

export type TOpenIdDiscoveryConfig = z.infer<typeof openIdDiscoverySchema>;
export const chatProjectsConfigSchema = z
  .object({
    /** Maximum number of reference files attached to one Chat Project. Defaults to 50. */
    maxFiles: z
      .number()
      .int()
      .positive()
      .max(MAX_CHAT_PROJECT_FILES_CEILING)
      .optional()
      .default(MAX_CHAT_PROJECT_FILES),
    /** Maximum instruction characters stored for one Chat Project. Defaults to 16000. */
    maxInstructionsLength: z
      .number()
      .int()
      .positive()
      .max(MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH_CEILING)
      .optional()
      .default(MAX_CHAT_PROJECT_INSTRUCTIONS_LENGTH),
    /** Maximum description characters stored for one Chat Project. Defaults to 1000. */
    maxDescriptionLength: z
      .number()
      .int()
      .positive()
      .max(MAX_CHAT_PROJECT_DESCRIPTION_LENGTH_CEILING)
      .optional()
      .default(MAX_CHAT_PROJECT_DESCRIPTION_LENGTH),
  })
  .strict()
  .prefault({});

export type TChatProjectsConfig = z.infer<typeof chatProjectsConfigSchema>;

/** Maximum CAS attempts per ACL document, including the initial attempt. */
export const permissionWriteAttemptsSchema = z.number().int().min(1).max(100).default(3);

/** How long a holder keeps the per-resource permission lease without renewing it. */
export const permissionLeaseTtlSchema = z.number().int().min(1000).max(600000).default(30000);

/** How long a permission update waits for a contended per-resource lease before answering 409. */
export const permissionLeaseWaitSchema = z.number().int().min(0).max(60000).default(3000);

/**
 * Validation limits for the conversation list's filter facets. The field defaults are the
 * only definition of these values: `getConfigDefaults()` resolves them for AppService, and
 * the parser takes what AppService resolved.
 */
export const conversationListConfigSchema = z.object({
  /** How many endpoint names one filter request may name. The list is a fixed menu of the
   * endpoints a deployment serves, so a request naming more than this is not a user
   * choosing filters: it is an unbounded `$in` arriving from somewhere else. */
  maxEndpointFilters: z.number().int().min(1).max(1_000).default(50),
  /** One endpoint name. Long enough for a custom endpoint, short enough to bound the query. */
  maxEndpointNameLength: z.number().int().min(1).max(1_024).default(128),
});

export type TConversationListConfig = z.infer<typeof conversationListConfigSchema>;

/**
 * Bounded previews of settled tool calls on conversation loads. A client that asks for them
 * receives the start and end of each long output and argument string, without subagent
 * transcripts, and fetches a part in full only when the reader opens it. `enabled: false` sends
 * every load in full, as before previews existed.
 */
export const toolCallPreviewsConfigSchema = z.object({
  enabled: z.boolean().default(true),
  /** Characters of `output` kept per tool call, half from the start and half from the end.
   *  JSON output stays valid JSON, and an exit-status trailer is always kept whole. */
  outputChars: z.number().int().min(256).max(1_000_000).default(512),
  /** Characters of serialized `args` kept per tool call. JSON arguments stay valid JSON with
   *  every field present; only the longest strings are shortened. */
  argsChars: z.number().int().min(256).max(1_000_000).default(512),
  /** Transcript nodes and unique scope lookups per message; exhausted calls keep their transcript. */
  attachmentWorkLimit: z.number().int().min(1).max(1_000_000).default(100_000),
});

export type TToolCallPreviewsConfig = z.infer<typeof toolCallPreviewsConfigSchema>;

export const configSchema = z.object({
  version: z.string(),
  telemetry: telemetrySchema.optional(),
  clientLimits: clientLimitsSchema.optional(),
  permissions: z
    .object({
      maxWriteAttempts: permissionWriteAttemptsSchema,
      leaseTtlMs: permissionLeaseTtlSchema,
      leaseWaitMs: permissionLeaseWaitSchema,
    })
    .optional(),
  cache: z.boolean().default(true),
  projects: chatProjectsConfigSchema,
  ocr: ocrSchema.optional(),
  webSearch: webSearchSchema.optional(),
  githubCompare: z
    .object({
      enabled: z.boolean().default(false),
      timeoutMs: z.number().int().min(1).max(30000).default(10000),
    })
    .strict()
    .optional(),
  langfuse: langfuseConfigSchema.optional(),
  credentials: credentialsConfigSchema.optional(),
  memory: memorySchema.optional(),
  summarization: summarizationConfigSchema.optional(),
  skillSync: skillSyncConfigSchema,
  skillDeletion: z
    .object({
      /** Enable only after every server that can write Skill files uses upload intents. */
      finalizationEnabled: z.boolean().default(false),
      sweepIntervalMs: z.number().int().min(1_000).default(60_000),
      claimLeaseMs: z.number().int().min(1_000).default(120_000),
      /** Bounds both sweep candidates and per-Skill manifest batches. */
      batchSize: z.number().int().min(1).max(1_000).default(DEFAULT_SKILL_DELETION_BATCH_SIZE),
      recheckIntervalMs: z.number().int().min(60_000).default(3_600_000),
    })
    .strict()
    .default(() => ({
      finalizationEnabled: false,
      sweepIntervalMs: 60_000,
      claimLeaseMs: 120_000,
      batchSize: DEFAULT_SKILL_DELETION_BATCH_SIZE,
      recheckIntervalMs: 3_600_000,
    })),
  secureImageLinks: z.boolean().optional(),
  imageOutputType: z.nativeEnum(EImageOutputType).default(EImageOutputType.PNG),
  conversationList: conversationListConfigSchema.default(() =>
    conversationListConfigSchema.parse({}),
  ),
  toolCallPreviews: toolCallPreviewsConfigSchema.default(() =>
    toolCallPreviewsConfigSchema.parse({}),
  ),
  includedTools: z.array(z.string()).optional(),
  filteredTools: z.array(z.string()).optional(),
  mcpServers: MCPServersSchema.optional(),
  mcpAppSandbox: z
    .object({
      url: z
        .string()
        .trim()
        .url()
        .refine(
          (value) => {
            try {
              return ['http:', 'https:'].includes(new URL(value).protocol);
            } catch {
              return false;
            }
          },
          { message: 'MCP App sandbox URL must use http:// or https://' },
        )
        .optional(),
      maxSourcesPerDirective: z
        .number()
        .int()
        .positive()
        .max(Number.MAX_SAFE_INTEGER)
        .default(DEFAULT_MCP_APP_CSP_LIMITS.maxSourcesPerDirective),
      maxSerializedLength: z
        .number()
        .int()
        .positive()
        .max(Number.MAX_SAFE_INTEGER)
        .default(DEFAULT_MCP_APP_CSP_LIMITS.maxSerializedLength),
      maxPersistedAppBytes: z
        .number()
        .int()
        .positive()
        .max(MAX_MCP_APP_PERSISTED_BYTES)
        .default(DEFAULT_MCP_APP_PERSISTED_BYTES),
      maxPersistedMessageBytes: z
        .number()
        .int()
        .positive()
        .max(MAX_MCP_APP_MESSAGE_BYTES)
        .default(DEFAULT_MCP_APP_MESSAGE_BYTES),
      maxAdmissionRequestsPerMinute: z
        .number()
        .int()
        .positive()
        .max(Number.MAX_SAFE_INTEGER)
        .default(DEFAULT_MCP_APP_ADMISSION_REQUESTS_PER_MINUTE),
      maxActiveViews: z
        .number()
        .int()
        .positive()
        .max(MAX_MCP_APP_ACTIVE_VIEWS)
        .default(DEFAULT_MCP_APP_MAX_ACTIVE_VIEWS),
      maxActionPreviewChars: z
        .number()
        .int()
        .positive()
        .max(MAX_MCP_APP_ACTION_PREVIEW_CHARS)
        .default(DEFAULT_MCP_APP_ACTION_PREVIEW_CHARS),
      operationLimits: z
        .object({
          maxBytes: z
            .number()
            .int()
            .positive()
            .max(16 * 1024 * 1024)
            .default(DEFAULT_MCP_APP_OPERATION_LIMITS.maxBytes),
          timeoutMs: z
            .number()
            .int()
            .positive()
            .max(10 * 60_000)
            .default(DEFAULT_MCP_APP_OPERATION_LIMITS.timeoutMs),
          maxActive: z
            .number()
            .int()
            .positive()
            .max(256)
            .default(DEFAULT_MCP_APP_OPERATION_LIMITS.maxActive),
        })
        .prefault({}),
    })
    .prefault({}),
  mcpSettings: z
    .object({
      allowedDomains: z.array(z.string()).optional(),
      allowedAddresses: allowedAddressesSchema,
      /** How long a failed OAuth reconnection is remembered before its attempt count resets.
       * Defaults to 24 hours. */
      oauthFailureRetentionMs: z
        .number()
        .int()
        .positive()
        .max(30 * 24 * 60 * 60_000)
        .optional(),
      catalogRecovery: z
        .object({
          discoveryBackoffMs: z
            .array(
              z
                .number()
                .int()
                .positive()
                .max(24 * 60 * 60_000),
            )
            .min(1)
            .max(8)
            .default([5 * 60_000, 10 * 60_000, 20 * 60_000, 30 * 60_000]),
          discoveryTimeoutMs: z
            .number()
            .int()
            .positive()
            .max(5 * 60_000)
            .default(3_000),
          /** How long past `discoveryTimeoutMs` a stalled discovery may hold its catalog slot and
           * coalesced requests. It is never cancelled, so OAuth tokens it redeemed still persist,
           * and no other discovery for the same server state starts until it settles. */
          discoverySettleGraceMs: z
            .number()
            .int()
            .nonnegative()
            .max(5 * 60_000)
            .default(10_000),
          reauthRetryMs: z
            .number()
            .int()
            .positive()
            .max(24 * 60 * 60_000)
            .default(30 * 60_000),
          maxStateEntries: z.number().int().positive().max(1_000_000).default(10_000),
          /** Process-wide: how many discoveries released past `discoverySettleGraceMs` may still be
           * running before recovery starts no new discovery until one settles. The default matches
           * the three catalog slots a stalled dependency could hold before discoveries were released. */
          maxDetachedDiscoveries: z.number().int().positive().max(1_000).default(3),
          generationReadTimeoutMs: z.number().int().positive().max(10_000).default(500),
          authorizationFenceRetryMs: z
            .array(z.number().int().nonnegative().max(60_000))
            .min(1)
            .max(8)
            .default([0, 50, 200]),
          authorizationFenceTimeoutMs: z.number().int().positive().max(30_000).default(1_000),
          authorizationFenceRetryIntervalMs: z
            .number()
            .int()
            .positive()
            .max(60 * 60_000)
            .default(30_000),
          authorizationFenceRetryBatchSize: z.number().int().positive().max(10_000).default(100),
        })
        .prefault({}),
      apps: z.boolean().optional(),
    })
    .optional(),
  interface: interfaceSchema,
  turnstile: turnstileSchema.optional(),
  /** Maximum rows an explicitly limited GET /files request may return. */
  fileListLimit: z.number().int().positive().default(100),
  fileStrategy: fileStorageSchema.default(FileSources.local),
  fileStrategies: fileStrategiesSchema,
  cloudfront: cloudfrontConfigSchema,
  actions: z
    .object({
      allowedDomains: z.array(z.string()).optional(),
      allowedAddresses: allowedAddressesSchema,
    })
    .optional(),
  registration: z
    .object({
      socialLogins: z.array(z.string()).optional(),
      allowedDomains: z.array(z.string()).optional(),
      /** Milliseconds a started social login may take to reach its callback; defaults to `DEFAULT_OAUTH_STATE_TTL_MS`. */
      oauthStateTtlMs: z.number().int().min(60_000).max(3_600_000).optional(),
      /** OpenID discovery retries; an unset field falls back to its `OPENID_DISCOVERY_RETRY_*` env var, then the schema default. */
      openidDiscovery: partialWithoutDefaults(openIdDiscoverySchema).optional(),
    })
    .default({ socialLogins: defaultSocialLogins }),
  /** Changing the registered email address. An unset field falls back to its env var, then the
   *  documented default, so an existing deployment keeps the behavior it has today. */
  emailChange: z
    .object({
      /** `ALLOW_EMAIL_CHANGE` when unset; enabled when neither is given. */
      enabled: z.boolean().optional(),
      /** Lifetime of a verification link. */
      tokenTTLSeconds: z.number().int().min(60).max(86_400).optional(),
    })
    .optional(),
  /** WebAuthn passkey enrollment. An unset field falls back to its env var, then the
   *  documented default, so an existing deployment keeps the behavior it has today. */
  passkeys: z
    .object({
      /** `MAX_PASSKEYS_PER_USER` when unset; the documented default when neither is given. */
      perUserMax: z.number().int().min(1).max(100).optional(),
    })
    .default({}),
  balance: balanceSchema.optional(),
  transactions: transactionsSchema.optional(),
  speech: z
    .object({
      tts: ttsSchema.optional(),
      stt: sttSchema.optional(),
      speechTab: speechTab.optional(),
    })
    .optional(),
  rateLimits: rateLimitSchema.optional(),
  /** Worker threads that hash and verify passwords and auth tokens off the event loop. */
  passwordHashing: z
    .object({
      /** Defaults to one less than the CPU count, at most 4. */
      maxWorkers: z.number().int().min(1).max(32).optional(),
    })
    .optional(),
  timeouts: outboundTimeoutsSchema.optional(),
  violationLog: violationLogSchema.optional(),
  messages: z
    .object({
      /** Largest `pageSize` accepted by `GET /api/messages`. Defaults to 1000. */
      maxPageSize: z.number().int().min(1).max(10000).optional(),
    })
    .optional(),
  concurrency: lookupConcurrencySchema.optional(),
  fileConfig: fileConfigSchema.optional(),
  modelSpecs: specsConfigSchema.optional(),
  filters: filtersConfigSchema.optional(),
  messageFilter: messageFilterSchema.optional(),
  endpoints: z
    .object({
      allowedAddresses: allowedAddressesSchema,
      /**
       * Milliseconds the admin config catalog (`GET /api/admin/config/catalog`) reuses a scope's
       * model lists while its endpoint config is unchanged, up to one hour; `0` resolves them on
       * every read, where a fetched list may still come from the two-minute model-list cache.
       * Only librechat.yaml sets it. Omission keeps `DEFAULT_CATALOG_MODELS_TTL_MS` (two minutes).
       */
      catalogModelsTtlMs: z.number().int().min(0).max(3_600_000).optional(),
      /**
       * Defaults applied to every endpoint. Omit-based, so options added to
       * `baseEndpointSchema` are inherited here automatically — no list to
       * maintain (contrast `azureEndpointSchema`, which enumerates via
       * `.pick()`). Resolution order at read sites is `all` > the named
       * endpoint > a custom endpoint's own config.
       */
      all: baseEndpointSchema.omit({ baseURL: true }).optional(),
      [EModelEndpoint.openAI]: modelListEndpointSchema.optional(),
      [EModelEndpoint.google]: modelListEndpointSchema.optional(),
      [EModelEndpoint.anthropic]: anthropicEndpointSchema.optional(),
      [EModelEndpoint.azureOpenAI]: azureEndpointSchema.optional(),
      [EModelEndpoint.azureAssistants]: assistantEndpointSchema.optional(),
      [EModelEndpoint.assistants]: assistantEndpointSchema.optional(),
      [EModelEndpoint.agents]: agentsEndpointSchema.unwrap().optional(),
      [EModelEndpoint.custom]: customEndpointsSchema.optional(),
      [EModelEndpoint.bedrock]: bedrockEndpointSchema.optional(),
    })
    .strict()
    .refine((data) => Object.keys(data).length > 0, {
      message: 'At least one `endpoints` field must be provided.',
    })
    .optional(),
  /** Serve the OpenAPI spec and docs for the public Agents API. Off by default. */
  openapi: z
    .object({
      enabled: z.boolean().optional(),
    })
    .optional(),
});

/**
 * Recursively makes all properties of T optional, including nested objects.
 * Handles arrays, primitives, functions, and Date objects correctly.
 */
export type DeepPartial<T> = T extends (infer U)[]
  ? DeepPartial<U>[]
  : T extends ReadonlyArray<infer U>
    ? ReadonlyArray<DeepPartial<U>>
    : // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
      T extends Function
      ? T
      : T extends Date
        ? T
        : T extends object
          ? {
              [P in keyof T]?: DeepPartial<T[P]>;
            }
          : T;

export const getConfigDefaults = () => getSchemaDefaults(configSchema);
export type TCustomConfig = DeepPartial<z.infer<typeof configSchema>>;

/**
 * Shape of the `webSearch` block as written in `librechat.yaml`, where
 * `searxngSearchOptions.engines` may still be the YAML list or untrimmed string an
 * operator wrote. `loadCustomConfig` returns the raw YAML object rather than the
 * parsed result, so the runtime loader receives this shape, not the parsed one.
 */
export type TWebSearchConfigInput = Omit<
  NonNullable<TCustomConfig['webSearch']>,
  'searxngSearchOptions'
> & {
  searxngSearchOptions?: z.input<typeof webSearchSchema>['searxngSearchOptions'];
};
export type TCustomEndpoints = z.infer<typeof customEndpointsSchema>;

export type TProviderSchema =
  | z.infer<typeof ttsOpenaiSchema>
  | z.infer<typeof ttsElevenLabsSchema>
  | z.infer<typeof ttsLocalaiSchema>
  | undefined;

export enum KnownEndpoints {
  anyscale = 'anyscale',
  apipie = 'apipie',
  cohere = 'cohere',
  fireworks = 'fireworks',
  deepseek = 'deepseek',
  moonshot = 'moonshot',
  groq = 'groq',
  helicone = 'helicone',
  huggingface = 'huggingface',
  lemonade = 'lemonade',
  mistral = 'mistral',
  mlx = 'mlx',
  ollama = 'ollama',
  openrouter = 'openrouter',
  perplexity = 'perplexity',
  shuttleai = 'shuttleai',
  'together.ai' = 'together.ai',
  unify = 'unify',
  vercel = 'vercel',
  xai = 'xai',
}

export enum FetchTokenConfig {
  openrouter = KnownEndpoints.openrouter,
  helicone = KnownEndpoints.helicone,
}

export const defaultEndpoints: EModelEndpoint[] = [
  EModelEndpoint.openAI,
  EModelEndpoint.assistants,
  EModelEndpoint.azureAssistants,
  EModelEndpoint.azureOpenAI,
  EModelEndpoint.agents,
  EModelEndpoint.google,
  EModelEndpoint.anthropic,
  EModelEndpoint.custom,
  EModelEndpoint.bedrock,
];

export const alternateName = {
  [EModelEndpoint.openAI]: 'OpenAI',
  [EModelEndpoint.assistants]: 'Assistants',
  [EModelEndpoint.agents]: 'My Agents',
  [EModelEndpoint.azureAssistants]: 'Azure Assistants',
  [EModelEndpoint.azureOpenAI]: 'Azure OpenAI',
  [EModelEndpoint.google]: 'Google',
  [EModelEndpoint.anthropic]: 'Anthropic',
  [EModelEndpoint.custom]: 'Custom',
  [EModelEndpoint.bedrock]: 'AWS Bedrock',
  [KnownEndpoints.lemonade]: 'AMD Lemonade',
  [KnownEndpoints.ollama]: 'Ollama',
  [KnownEndpoints.deepseek]: 'DeepSeek',
  [KnownEndpoints.moonshot]: 'Moonshot',
  [KnownEndpoints.xai]: 'xAI',
  [KnownEndpoints.vercel]: 'Vercel',
  [KnownEndpoints.helicone]: 'Helicone',
};

/**
 * Models the Assistants endpoints cannot run. GPT-6 Astra serves tool calls only
 * from the Responses API, and the Assistants surface does not route through
 * `getOpenAILLMConfig`, so listing it there would offer a configuration the
 * provider rejects. Kept out of `sharedOpenAIModels`, which both Assistants
 * catalogs consume.
 */
const responsesOnlyOpenAIModels = ['gpt-6-astra'];
/** Tool calls with Sol/Luna's default reasoning require Responses. Do not offer
 * these on Assistants, which cannot use the native request-routing path. */
const responsesReasoningOpenAIModels = ['gpt-6.1-sol', 'gpt-6-sol', 'gpt-6-luna'];
/** Catalog models whose native execution defaults to the Responses API. */
export const responsesPreferredOpenAIModels: readonly string[] = [
  ...responsesOnlyOpenAIModels,
  ...responsesReasoningOpenAIModels,
];

const sharedOpenAIModels = [
  'gpt-5.6',
  'gpt-5.6-terra',
  'gpt-5.6-luna',
  'gpt-5.5',
  'gpt-5.5-pro',
  'chat-latest',
  'gpt-5.4',
  'gpt-5.4-pro',
  'gpt-5.4-mini',
  'gpt-5.4-nano',
  'gpt-5.3-codex',
  'gpt-5.2',
  'gpt-5.1',
  'gpt-5.1-codex',
  'gpt-5.1-codex-max',
  'gpt-5.1-codex-mini',
  'gpt-5',
  'gpt-5-mini',
  'gpt-5-nano',
  'gpt-4.1',
  'gpt-4.1-mini',
  'gpt-4.1-nano',
  'gpt-4o-mini',
  'gpt-4o',
];

const sharedAnthropicModels = [
  'claude-fable-5-1',
  'claude-fable-5',
  'claude-opus-5-5',
  'claude-opus-5',
  'claude-sonnet-5-5',
  'claude-opus-4-8',
  'claude-opus-4-7',
  'claude-sonnet-5',
  'claude-sonnet-4-6',
  'claude-opus-4-6',
  'claude-sonnet-4-5',
  'claude-sonnet-4-5-20250929',
  'claude-haiku-5-5',
  'claude-haiku-4-5',
  'claude-haiku-4-5-20251001',
  'claude-opus-4-1',
  'claude-opus-4-1-20250805',
  'claude-opus-4-5',
  'claude-sonnet-4-20250514',
  'claude-sonnet-4-0',
  'claude-opus-4-20250514',
  'claude-opus-4-0',
  'claude-3-7-sonnet-latest',
  'claude-3-7-sonnet-20250219',
  'claude-3-5-haiku-20241022',
  'claude-3-5-sonnet-20241022',
  'claude-3-5-sonnet-20240620',
  'claude-3-5-sonnet-latest',
];

/**
 * Claude 4+ models are not invocable on-demand by their bare foundation-model
 * ID on the Converse path — Bedrock rejects those with "Invocation of model ID
 * ... with on-demand throughput isn't supported. Retry your request with the ID
 * or ARN of an inference profile that contains this model." Default to the
 * `global.` cross-region profile (no regional pricing premium, widest
 * availability); Opus 4.1 has no global profile, so it uses `us.`.
 */
export const bedrockModels = [
  'global.anthropic.claude-fable-5-1',
  'global.anthropic.claude-fable-5',
  'global.anthropic.claude-opus-5-5',
  'global.anthropic.claude-opus-5',
  'global.anthropic.claude-sonnet-5-5',
  'global.anthropic.claude-opus-4-8',
  'global.anthropic.claude-opus-4-7',
  'global.anthropic.claude-sonnet-5',
  'global.anthropic.claude-sonnet-4-6',
  'global.anthropic.claude-opus-4-6-v1',
  'global.anthropic.claude-sonnet-4-5-20250929-v1:0',
  'global.anthropic.claude-haiku-5-5',
  'global.anthropic.claude-haiku-4-5-20251001-v1:0',
  'us.anthropic.claude-opus-4-1-20250805-v1:0',
  // 'cohere.command-text-v14', // no conversation history
  // 'cohere.command-light-text-v14', // no conversation history
  'cohere.command-r-v1:0',
  'cohere.command-r-plus-v1:0',
  'meta.llama2-13b-chat-v1',
  'meta.llama2-70b-chat-v1',
  'meta.llama3-8b-instruct-v1:0',
  'meta.llama3-70b-instruct-v1:0',
  'meta.llama3-1-8b-instruct-v1:0',
  'meta.llama3-1-70b-instruct-v1:0',
  'meta.llama3-1-405b-instruct-v1:0',
  'mistral.mistral-7b-instruct-v0:2',
  'mistral.mixtral-8x7b-instruct-v0:1',
  'mistral.mistral-large-2402-v1:0',
  'mistral.mistral-large-2407-v1:0',
  'mistral.mistral-small-2402-v1:0',
  'ai21.jamba-instruct-v1:0',
  // 'ai21.j2-mid-v1', // no streaming
  // 'ai21.j2-ultra-v1', no conversation history
  'amazon.titan-text-lite-v1',
  'amazon.titan-text-express-v1',
  'amazon.titan-text-premier-v1:0',
];

export const defaultModels = {
  [EModelEndpoint.azureAssistants]: sharedOpenAIModels,
  [EModelEndpoint.assistants]: [...sharedOpenAIModels, 'chatgpt-4o-latest'],
  // TODO: Add agent models (agentsModels)
  [EModelEndpoint.agents]: [
    ...responsesOnlyOpenAIModels,
    ...responsesReasoningOpenAIModels,
    ...sharedOpenAIModels,
  ],
  [EModelEndpoint.google]: [
    // Gemini 4 Models
    'gemini-4-argon',
    // Gemini 3.8 Models
    'gemini-3.8-flash',
    // Gemini 3.7 Models
    'gemini-3.7-flash',
    // Gemini 3.6 Models
    'gemini-3.6-flash',
    // Gemini 3.5 Models
    'gemini-3.5-flash',
    'gemini-3.5-flash-lite',
    // Gemini 3.1 Models
    'gemini-3.1-pro-preview',
    'gemini-3.1-pro-preview-customtools',
    'gemini-3.1-flash-lite-preview',
    // Gemini 3 Models
    'gemini-3-pro-preview',
    'gemini-3-flash-preview',
    // Gemini 2.5 Models
    'gemini-2.5-pro',
    'gemini-2.5-flash',
    'gemini-2.5-flash-lite',
  ],
  [EModelEndpoint.anthropic]: sharedAnthropicModels,
  [EModelEndpoint.openAI]: [
    ...responsesOnlyOpenAIModels,
    ...responsesReasoningOpenAIModels,
    ...sharedOpenAIModels,
    'chatgpt-4o-latest',
    'gpt-4-vision-preview',
    'gpt-3.5-turbo-instruct-0914',
    'gpt-3.5-turbo-instruct',
  ],
  [EModelEndpoint.bedrock]: bedrockModels,
};

const fitlerAssistantModels = (str: string) => {
  return /gpt-4|gpt-3\\.5/i.test(str) && !/vision|instruct/i.test(str);
};

const openAIModels = defaultModels[EModelEndpoint.openAI];

/**
 * Preserve Azure's fallback default selection when the OpenAI catalog gains
 * Responses-preferred models. Configured Azure deployments supply their own
 * model list, including Astra when deployed.
 */
const nonResponsesOnlyOpenAIModels = openAIModels.filter(
  (model) =>
    !responsesOnlyOpenAIModels.includes(model) && !responsesReasoningOpenAIModels.includes(model),
);

export const initialModelsConfig: TModelsConfig = {
  initial: [],
  [EModelEndpoint.openAI]: openAIModels,
  [EModelEndpoint.assistants]: openAIModels.filter(fitlerAssistantModels),
  [EModelEndpoint.agents]: openAIModels, // TODO: Add agent models (agentsModels)
  [EModelEndpoint.azureOpenAI]: nonResponsesOnlyOpenAIModels,
  [EModelEndpoint.google]: defaultModels[EModelEndpoint.google],
  [EModelEndpoint.anthropic]: defaultModels[EModelEndpoint.anthropic],
  [EModelEndpoint.bedrock]: defaultModels[EModelEndpoint.bedrock],
};

export const EndpointURLs = {
  [EModelEndpoint.assistants]: `${apiBaseUrl()}/api/assistants/v2/chat`,
  [EModelEndpoint.azureAssistants]: `${apiBaseUrl()}/api/assistants/v1/chat`,
  [EModelEndpoint.agents]: `${apiBaseUrl()}/api/${EModelEndpoint.agents}/chat`,
} as const;

export const modularEndpoints = new Set<EModelEndpoint | string>([
  EModelEndpoint.anthropic,
  EModelEndpoint.google,
  EModelEndpoint.openAI,
  EModelEndpoint.azureOpenAI,
  EModelEndpoint.custom,
  EModelEndpoint.agents,
  EModelEndpoint.bedrock,
]);

export const supportsBalanceCheck = {
  [EModelEndpoint.custom]: true,
  [EModelEndpoint.openAI]: true,
  [EModelEndpoint.anthropic]: true,
  [EModelEndpoint.assistants]: true,
  [EModelEndpoint.agents]: true,
  [EModelEndpoint.azureAssistants]: true,
  [EModelEndpoint.azureOpenAI]: true,
  [EModelEndpoint.bedrock]: true,
  [EModelEndpoint.google]: true,
};

export enum VisionModes {
  generative = 'generative',
  agents = 'agents',
}

export const imageGenTools = new Set([
  'dalle',
  'dall-e',
  'stable-diffusion',
  'flux',
  'gemini_image_gen',
]);

/**
 * Enum for collections using infinite queries
 */
export enum InfiniteCollections {
  /**
   * Collection for Prompt Groups
   */
  PROMPT_GROUPS = 'promptGroups',
  /**
   * Collection for Shared Links
   */
  SHARED_LINKS = 'sharedLinks',
}

/**
 * Enum for time intervals
 */
export enum Time {
  ONE_DAY = 86400000,
  TWELVE_HOURS = 43200000,
  ONE_HOUR = 3600000,
  THIRTY_MINUTES = 1800000,
  TEN_MINUTES = 600000,
  FIVE_MINUTES = 300000,
  THREE_MINUTES = 180000,
  TWO_MINUTES = 120000,
  ONE_MINUTE = 60000,
  THIRTY_SECONDS = 30000,
}

/**
 * Enum for cache keys.
 */
export enum CacheKeys {
  /**
   * Key for the config store namespace.
   */
  CONFIG_STORE = 'CONFIG_STORE',
  /**
   * Key for the tool cache namespace (plugins, MCP tools, tool definitions).
   */
  TOOL_CACHE = 'TOOL_CACHE',
  /**
   * Key for the roles cache.
   */
  ROLES = 'ROLES',
  /**
   * Key for cached group memberships used to resolve ACL user principals.
   */
  USER_PRINCIPALS = 'USER_PRINCIPALS',
  /**
   * Key for cached prompt group access ID sets (accessible, public, owned).
   */
  PROMPT_GROUPS_ACCESS = 'PROMPT_GROUPS_ACCESS',
  /**
   * Key for cached resolved content of an agent's linked native prompt-group instructions.
   */
  AGENT_LINKED_INSTRUCTIONS = 'AGENT_LINKED_INSTRUCTIONS',
  /**
   * Key for per-conversation stateful code sandbox prewarm/warm state.
   */
  SANDBOX_PREWARM = 'SANDBOX_PREWARM',
  /**
   * Key for the title generation cache.
   */
  GEN_TITLE = 'GEN_TITLE',
  /**
   * Key for the tools cache.
   */
  TOOLS = 'TOOLS',
  /**
   * Key for the model config cache.
   */
  MODELS_CONFIG = 'MODELS_CONFIG',
  /**
   * Key for the model queries cache.
   */
  MODEL_QUERIES = 'MODEL_QUERIES',
  /**
   * Key for the default startup config cache.
   */
  STARTUP_CONFIG = 'STARTUP_CONFIG',
  /**
   * Key for the default endpoint config cache.
   */
  ENDPOINT_CONFIG = 'ENDPOINT_CONFIG',
  /**
   * Key for accessing the model token config cache.
   */
  TOKEN_CONFIG = 'TOKEN_CONFIG',
  /**
   * Key for the per-model reasoning effort cache of OpenRouter endpoints.
   */
  REASONING_CAPABILITIES = 'REASONING_CAPABILITIES',
  /**
   * Key for pull request lookups and GitHub rate limit cooldowns shared across replicas.
   */
  PULL_REQUESTS = 'PULL_REQUESTS',
  /**
   * Key for the app config namespace.
   */
  APP_CONFIG = 'APP_CONFIG',
  /**
   * Key for accessing Abort Keys
   */
  ABORT_KEYS = 'ABORT_KEYS',
  /**
   * Key for the bans cache.
   */
  BANS = 'BANS',
  /**
   * Key for the encoded domains cache.
   * Used by Azure OpenAI Assistants.
   */
  ENCODED_DOMAINS = 'ENCODED_DOMAINS',
  /**
   * Key for the cached audio run Ids.
   */
  AUDIO_RUNS = 'AUDIO_RUNS',
  /**
   * Key for in-progress messages.
   */
  MESSAGES = 'MESSAGES',
  /**
   * Key for in-progress flow states.
   */
  FLOWS = 'FLOWS',
  /**
   * Key for pending chat requests (concurrency check)
   */
  PENDING_REQ = 'PENDING_REQ',
  /**
   * Key for s3 check intervals per user
   */
  S3_EXPIRY_INTERVAL = 'S3_EXPIRY_INTERVAL',
  /**
   * key for open id exchanged tokens
   */
  OPENID_EXCHANGED_TOKENS = 'OPENID_EXCHANGED_TOKENS',
  /**
   * Key for cached authenticated user documents.
   */
  AUTH_USER_DOC = 'AUTH_USER_DOC',
  /**
   * Key for OpenID session.
   */
  OPENID_SESSION = 'OPENID_SESSION',
  /**
   * Key for SAML session.
   */
  SAML_SESSION = 'SAML_SESSION',
  /**
   * Key for admin panel OAuth exchange codes (one-time-use, short TTL).
   */
  ADMIN_OAUTH_EXCHANGE = 'ADMIN_OAUTH_EXCHANGE',
  /**
   * Key for pending WebAuthn (passkey) ceremony challenges (one-time-use, short TTL).
   */
  PASSKEY_CHALLENGE = 'PASSKEY_CHALLENGE',
}

export const AUTH_USER_DOC_BY_ID_PREFIX = 'auth-user-doc-byid';

/** Lifetime of a cached auth user document, and so the longest a stale one can be served. */
export const AUTH_USER_DOC_CACHE_TTL_MS = 5000;

/**
 * Longest a cached auth user document can live after its lookup began: the lookup may take one
 * cache TTL before the write, and the document lives at most one more.
 */
export const AUTH_USER_DOC_MAX_AGE_MS = AUTH_USER_DOC_CACHE_TTL_MS * 2;

/** Per-user marker an eviction leaves so a lookup that began before it cannot be cached or served. */
export const AUTH_USER_DOC_EVICTED_PREFIX = 'auth-user-doc-evicted';

/**
 * Lifetime of that marker. A document is only cached when its lookup took at most one cache TTL
 * and then lives one more, so any document read before an eviction expires within two TTLs of it.
 */
export const AUTH_USER_DOC_EVICTION_FENCE_TTL_MS = AUTH_USER_DOC_CACHE_TTL_MS * 3;

/**
 * Enum for violation types, used to identify, log, and cache violations.
 */
export enum ViolationTypes {
  /**
   * File Upload Violations (exceeding limit).
   */
  FILE_UPLOAD_LIMIT = 'file_upload_limit',
  /**
   * Illegal Model Request (not available).
   */
  ILLEGAL_MODEL_REQUEST = 'illegal_model_request',
  /**
   * Token Limit Violation.
   */
  TOKEN_BALANCE = 'token_balance',
  /**
   * An issued ban.
   */
  BAN = 'ban',
  /**
   * TTS Request Limit Violation.
   */
  TTS_LIMIT = 'tts_limit',
  /**
   * STT Request Limit Violation.
   */
  STT_LIMIT = 'stt_limit',
  /**
   * Reset Password Limit Violation.
   */
  RESET_PASSWORD_LIMIT = 'reset_password_limit',
  /**
   * Verify Email Limit Violation.
   */
  VERIFY_EMAIL_LIMIT = 'verify_email_limit',
  /**
   * Verify Conversation Access violation.
   */
  CONVO_ACCESS = 'convo_access',
  /**
   * Tool Call Limit Violation.
   */
  TOOL_CALL_LIMIT = 'tool_call_limit',
  /**
   * General violation (catch-all).
   */
  GENERAL = 'general',
  /**
   * Login attempt violations.
   */
  LOGINS = 'logins',
  /**
   * Concurrent request violations.
   */
  CONCURRENT = 'concurrent',
  /**
   * Non-browser access violations.
   */
  NON_BROWSER = 'non_browser',
  /**
   * Message limit violations.
   */
  MESSAGE_LIMIT = 'message_limit',
  /**
   * Registration violations.
   */
  REGISTRATIONS = 'registrations',
  /**
   * Shared link retrieval limit violations.
   */
  SHARE_LIMIT = 'share_limit',
}

/**
 * Enum for error message types that are not "violations" as above, used to identify client-facing errors.
 */
export enum ErrorTypes {
  /**
   * No User-provided Key.
   */
  NO_USER_KEY = 'no_user_key',
  /**
   * Expired User-provided Key.
   */
  EXPIRED_USER_KEY = 'expired_user_key',
  /**
   * Invalid User-provided Key.
   */
  INVALID_USER_KEY = 'invalid_user_key',
  /**
   * No Base URL Provided.
   */
  NO_BASE_URL = 'no_base_url',
  /**
   * Base URL targets a restricted or invalid address (SSRF protection).
   */
  INVALID_BASE_URL = 'invalid_base_url',
  /**
   * Moderation error
   */
  MODERATION = 'moderation',
  /**
   * Prompt exceeds max length
   */
  INPUT_LENGTH = 'INPUT_LENGTH',
  /**
   * Invalid request error, API rejected request
   */
  INVALID_REQUEST = 'invalid_request_error',
  /**
   * Invalid action request error, likely not on list of allowed domains
   */
  INVALID_ACTION = 'invalid_action_error',
  /**
   * Invalid request error, API rejected request
   */
  NO_SYSTEM_MESSAGES = 'no_system_messages',
  /**
   * Google provider returned an error
   */
  GOOGLE_ERROR = 'google_error',
  /**
   * Google provider does not allow custom tools with built-in tools
   */
  GOOGLE_TOOL_CONFLICT = 'google_tool_conflict',
  /**
   * Google provider could not process a linked video (most often longer than the model accepts)
   */
  GOOGLE_VIDEO_UNPROCESSABLE = 'google_video_unprocessable',
  /**
   * Required CodeAPI resources could not be restored before model invocation.
   */
  RESOURCE_RECOVERY_REQUIRED = 'resource_recovery_required',
  /**
   * Agent selected a stateful Code API workspace scope disabled by the deployment.
   */
  STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED = 'stateful_code_environment_not_allowed',
  /**
   * A conversation's selected attached workspace cannot be used as requested.
   */
  CODE_WORKSPACE_UNAVAILABLE = 'code_workspace_unavailable',
  /**
   * Invalid Agent Provider (excluded by Admin)
   */
  INVALID_AGENT_PROVIDER = 'invalid_agent_provider',
  /**
   * Missing model selection
   */
  MISSING_MODEL = 'missing_model',
  /**
   * Models configuration not loaded
   */
  MODELS_NOT_LOADED = 'models_not_loaded',
  /**
   * Endpoint models not loaded
   */
  ENDPOINT_MODELS_NOT_LOADED = 'endpoint_models_not_loaded',
  /**
   * Generic Authentication failure
   */
  AUTH_FAILED = 'auth_failed',
  /**
   * Authentication rejected by a rate limiter
   */
  AUTH_RATE_LIMITED = 'auth_rate_limited',
  /**
   * Authentication rejected because the account or IP is banned
   */
  AUTH_BANNED = 'auth_banned',
  /**
   * Authentication request was not sent from this application's origin
   */
  AUTH_CROSS_ORIGIN = 'auth_cross_origin',
  /**
   * Model refused to respond (content policy violation)
   */
  REFUSAL = 'refusal',
  /**
   * SSE stream 404 — job completed, expired, or was deleted before the subscriber connected
   */
  STREAM_EXPIRED = 'stream_expired',
  /**
   * Provider does not serve the requested model
   */
  MODEL_NOT_FOUND = 'model_not_found',
  /**
   * Provider throttled or refused the request for exceeding a rate/spend allowance
   */
  MODEL_RATE_LIMIT = 'model_rate_limit',
  /**
   * Provider accepted the request, then closed the connection before the response finished
   */
  MODEL_STREAM_CLOSED = 'model_stream_closed',
  /**
   * Provider accepted the request, then sent nothing for longer than the model response timeout
   */
  MODEL_STREAM_STALLED = 'model_stream_stalled',
  /**
   * An agent model provider failed and the run could not recover.
   */
  UPSTREAM_MODEL_ERROR = 'upstream_model_error',
  /**
   * Context pruning removed every message; nothing fits the configured context window
   */
  EMPTY_MESSAGES = 'empty_messages',
  /**
   * Formatted provider payload exceeded the context budget before invocation
   */
  FINAL_CONTEXT_OVERFLOW = 'final_context_overflow',
  /**
   * A manual compaction the graph could not attempt; `reason` says why
   */
  COMPACTION_SKIPPED = 'compaction_skipped',
  /**
   * A manual compaction whose summarizer produced nothing; history is untouched
   */
  COMPACTION_FAILED = 'compaction_failed',
}

/**
 * Enum for authentication keys.
 */
export enum AuthKeys {
  /**
   * Key for the Service Account to use Vertex AI.
   */
  GOOGLE_SERVICE_KEY = 'GOOGLE_SERVICE_KEY',
  /**
   * API key to use Google Generative AI.
   *
   * Note: this is not for Environment Variables, but to access encrypted object values.
   */
  GOOGLE_API_KEY = 'GOOGLE_API_KEY',
  /**
   * API key to use Anthropic.
   *
   * Note: this is not for Environment Variables, but to access encrypted object values.
   */
  ANTHROPIC_API_KEY = 'ANTHROPIC_API_KEY',
}

/**
 * Tab values for Settings Dialog
 */
export enum SettingsTabValues {
  /**
   * Tab for General Settings
   */
  GENERAL = 'general',
  /**
   * Tab for Chat Settings
   */
  CHAT = 'chat',
  /**
   * Tab for Speech Settings
   */
  SPEECH = 'speech',
  /**
   * Tab for Langfuse Settings
   */
  LANGFUSE = 'langfuse',
  /**
   * Tab for Beta Features
   */
  BETA = 'beta',
  /**
   * Tab for Data Controls
   */
  DATA = 'data',
  /**
   * Tab for Balance Settings
   */
  BALANCE = 'balance',
  /**
   * Tab for Account Settings
   */
  ACCOUNT = 'account',
  /**
   * Chat input commands
   */
  COMMANDS = 'commands',
  /**
   * Tab for Personalization Settings
   */
  PERSONALIZATION = 'personalization',
  /**
   * Tab for About / Build Info
   */
  ABOUT = 'about',
}

export enum STTProviders {
  /**
   * Provider for OpenAI STT
   */
  OPENAI = 'openai',
  /**
   * Provider for Microsoft Azure STT
   */
  AZURE_OPENAI = 'azureOpenAI',
}

export enum TTSProviders {
  /**
   * Provider for OpenAI TTS
   */
  OPENAI = 'openai',
  /**
   * Provider for Microsoft Azure OpenAI TTS
   */
  AZURE_OPENAI = 'azureOpenAI',
  /**
   * Provider for ElevenLabs TTS
   */
  ELEVENLABS = 'elevenlabs',
  /**
   * Provider for LocalAI TTS
   */
  LOCALAI = 'localai',
}

/** Enum for app-wide constants */
export enum Constants {
  /**
   * Key for the app's version. The placeholder `__LIBRECHAT_VERSION__` is
   * swapped in by `@rollup/plugin-replace` during `npm run build:data-provider`
   * using the value of the root `package.json`'s `version` field. Consumers
   * always import this via the built dist bundle (see `main` field in
   * `packages/data-provider/package.json`), so production and UI code get the
   * substituted value. Only tests that import the TypeScript source directly
   * would observe the raw placeholder.
   */
  VERSION = '__LIBRECHAT_VERSION__',
  /** Key for the Custom Config's version (librechat.yaml). */
  CONFIG_VERSION = '1.3.18',
  /** Standard value for the first message's `parentMessageId` value, to indicate no parent exists. */
  NO_PARENT = '00000000-0000-0000-0000-000000000000',
  /** Standard value to use whatever the submission prelim. `responseMessageId` is */
  USE_PRELIM_RESPONSE_MESSAGE_ID = 'USE_PRELIM_RESPONSE_MESSAGE_ID',
  /** Standard value for the initial conversationId before a request is sent */
  NEW_CONVO = 'new',
  /** Standard value for the temporary conversationId after a request is sent and before the server responds */
  PENDING_CONVO = 'PENDING',
  /** Standard value for the conversationId used for search queries */
  SEARCH = 'search',
  /** Fixed, encoded domain length for Azure OpenAI Assistants Function name parsing. */
  ENCODED_DOMAIN_LENGTH = 10,
  /** Identifier for using current_model in multi-model requests. */
  CURRENT_MODEL = 'current_model',
  /** Protocol bound for UUIDs, nanoids, and derived user identities. */
  MAX_MESSAGE_ID_LENGTH = 256,
  /** A preliminary response reserves one trailing underscore. */
  MAX_RESPONSE_MESSAGE_ID_LENGTH = MAX_MESSAGE_ID_LENGTH + 1,
  /** Common divider for text values */
  COMMON_DIVIDER = '__',
  /** Max length for commands */
  COMMANDS_MAX_LENGTH = 56,
  /** Default Stream Rate (ms) */
  DEFAULT_STREAM_RATE = 1,
  /** Saved Tag */
  SAVED_TAG = 'Saved',
  /** Max number of Conversation starters for Agents/Assistants */
  MAX_CONVO_STARTERS = 4,
  /** Delimiter for MCP tools */
  mcp_delimiter = '_mcp_',
  /** Prefix for MCP plugins */
  mcp_prefix = 'mcp_',
  /** Unique value to indicate all MCP servers. For backend use only. */
  mcp_all = 'sys__all__sys',
  /** Unique value to indicate clearing MCP servers from UI state. For frontend use only. */
  mcp_clear = 'sys__clear__sys',
  /** Key suffix for non-spec user default tool storage */
  spec_defaults_key = '__defaults__',
  /**
   * Unique value to indicate the MCP tool was added to an agent.
   * This helps inform the UI if the mcp server was previously added.
   * */
  mcp_server = 'sys__server__sys',
  /**
   * Handoff Tool Name Prefix
   */
  LC_TRANSFER_TO_ = 'lc_transfer_to_',
  /** Placeholder Agent ID for Ephemeral Agents */
  EPHEMERAL_AGENT_ID = 'ephemeral',
  /** Programmatic Tool Calling tool name */
  PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',
  /** Bash Programmatic Tool Calling tool name */
  BASH_PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_bash',
  /** Subagent spawn tool name (must match `@librechat/agents` `Constants.SUBAGENT`). */
  SUBAGENT = 'subagent',
  /** Poll tool for retrieving the status/result of a backgrounded tool call. */
  CHECK_BACKGROUND_TASK = 'check_background_task',
  /**
   * `finish_reason` stamped on an assistant message whose turn ended because the
   * agent exhausted its per-turn graph step budget (`recursionLimit`) rather than
   * because the model chose to stop. Distinct from a user abort: nothing failed and
   * nothing was cancelled, the turn simply ran out of room. The UI keys its
   * "tool call limit reached" notice off this value. The hover Continue control
   * is withheld for this reason because the notice already offers the way forward.
   */
  TOOL_CALL_LIMIT_FINISH_REASON = 'tool_call_limit',
}

/**
 * This package's own version, swapped in from `packages/data-provider/package.json` at build
 * time like `Constants.VERSION`, so a server can report which schema package it validates with.
 */
export const DATA_PROVIDER_VERSION: string = '__DATA_PROVIDER_VERSION__';

/**
 * Normalizes a server name into the character set tool keys are built from.
 * Tool keys embed this output, so any candidate list matched against a key must
 * be normalized the same way.
 */
export function normalizeServerName(serverName: string): string {
  if (/^[a-zA-Z0-9_.-]+$/.test(serverName)) {
    return serverName;
  }

  const normalized = serverName.replace(/[^a-zA-Z0-9_.-]/g, '_').replace(/^_+|_+$/g, '');
  if (normalized) {
    return normalized;
  }

  /** All characters were stripped; hash the original so the name stays unique. */
  let hash = 0;
  for (let i = 0; i < serverName.length; i++) {
    hash = (hash << 5) - hash + serverName.charCodeAt(i);
    hash |= 0;
  }
  return `server_${Math.abs(hash)}`;
}

/**
 * Splits a combined MCP tool key (`${rawToolName}${mcp_delimiter}${serverName}`)
 * back into its two parts.
 *
 * Both halves can legitimately contain the delimiter, so position alone cannot
 * identify the boundary. Raw tool names come from the upstream server and are
 * untrusted (`get_mcp_server_version`, or a gateway-prefixed
 * `gitlab-get_mcp_server_version`), and `normalizeServerName` preserves
 * underscores, so a configured server may be named `Google_mcp_Workspace`.
 *
 * When `knownServerNames` is supplied the boundary is resolved against it: the
 * longest configured name the key actually ends with wins. Otherwise this falls
 * back to the last delimiter, which is correct whenever only the tool half
 * contains one and matches `.split()` when neither does.
 *
 * One case stays undecidable from the key alone: if both `bar` and `foo_mcp_bar`
 * are configured, `tool_mcp_foo_mcp_bar` is a valid key for either. Longest match
 * is the deterministic tiebreak; resolving it properly needs the tool/server
 * mapping carried alongside the key rather than re-derived from the string.
 */
/**
 * Maps each configured server name's normalized form back to the raw config
 * name. Model-facing tool keys embed `normalizeServerName(server)`, while the
 * registry, config maps, tool cache, and plugin-auth rows are keyed by the raw
 * name — any consumer that parses a server out of a tool key must resolve it
 * through this map before those lookups. Identity entries are included so
 * `aliases.get(name) ?? name` works uniformly.
 *
 * When two configured names normalize to the same value their tool keys are
 * inherently ambiguous; the FIRST configured name wins deterministically here,
 * and `resolveMCPServerContext` warns about the collision so the operator can
 * rename one server.
 */
export function buildServerNameAliases(rawServerNames: readonly string[]): Map<string, string> {
  const aliases = new Map<string, string>();
  /** Identity entries claim their slot FIRST regardless of configuration
   *  order: a server literally named `foo` must never have its keys rerouted
   *  to a `foo!` whose normalized form collides with it. */
  for (const raw of rawServerNames) {
    if (raw && normalizeServerName(raw) === raw) {
      aliases.set(raw, raw);
    }
  }
  for (const raw of rawServerNames) {
    if (!raw) {
      continue;
    }
    const normalized = normalizeServerName(raw);
    if (!aliases.has(normalized)) {
      aliases.set(normalized, raw);
    }
  }
  return aliases;
}

/**
 * Rewrites a tool key's server segment into the normalized form model-facing
 * keys carry, resolving the boundary against the configured raw names (longest
 * suffix wins, mirroring {@link splitMCPToolKey}). Returns the key unchanged
 * when no configured raw name matches — already-normalized keys, placeholder
 * tokens, and keys for servers that are no longer configured all pass through.
 * Idempotent: a normalized segment never matches a raw candidate that needs
 * rewriting.
 */
export function normalizeMCPToolKey(toolKey: string, rawServerNames: readonly string[]): string {
  let matched: string | undefined;
  for (let i = 0; i < rawServerNames.length; i++) {
    const raw = rawServerNames[i];
    if (!raw || raw.length <= (matched?.length ?? 0)) {
      continue;
    }
    if (toolKey.endsWith(`${Constants.mcp_delimiter}${raw}`)) {
      matched = raw;
    }
  }
  if (matched == null) {
    return toolKey;
  }
  const normalized = normalizeServerName(matched);
  if (normalized === matched) {
    return toolKey;
  }
  return `${toolKey.slice(0, toolKey.length - matched.length)}${normalized}`;
}

/**
 * Strips a redundant leading server-name prefix from a raw upstream tool name
 * before it is embedded into a model-facing key, so the key doesn't carry the
 * server twice (`acme_trace_..._mcp_acme`) and push long tool names
 * past provider function-name limits (64 chars). The match is case-insensitive
 * because display-cased server names ("Acme") conventionally prefix their
 * tools in lowercase. Ingestion that strips must record the original name
 * (`serverToolName` on the cached definition) — tool calls send THAT name back
 * to the server, never the stripped one. Catalog producers must not call this
 * directly: only {@link stripServerNamePrefixes} sees the whole sibling set and
 * can keep colliding results apart.
 */
export function stripServerNamePrefix(toolName: string, normalizedServerName: string): string {
  const prefixLength = normalizedServerName.length + 1;
  if (toolName.length <= prefixLength) {
    return toolName;
  }
  const prefix = toolName.slice(0, prefixLength).toLowerCase();
  if (prefix !== `${normalizedServerName.toLowerCase()}_`) {
    return toolName;
  }
  const stripped = toolName.slice(prefixLength);
  if (isReservedMCPToolName(stripped)) {
    return toolName;
  }
  /** `isActionTool` classifies keys by the RELATIVE position of `_action_`
   *  and `_mcp_`; stripping moves the first `_mcp_` earlier, so a server
   *  whose normalized name contains `_action_` could see a real MCP tool
   *  reclassified as an OpenAPI action (bypassing MCP authorization). Never
   *  produce a key whose classification differs from the raw key's. */
  const keySuffix = `${Constants.mcp_delimiter}${normalizedServerName}`;
  if (isActionTool(`${stripped}${keySuffix}`) !== isActionTool(`${toolName}${keySuffix}`)) {
    return toolName;
  }
  return stripped;
}

/**
 * Synthetic markers consumed by prefix (`isMCPAllPlaceholder`, the server-pin
 * skip, the client's OAuth stream classification), so each reserves BOTH its
 * exact name and its `${marker}${mcp_delimiter}` namespace: a stripped
 * remainder inside any of them would turn a real upstream tool into the
 * server-wide wildcard, the UI pin placeholder, or a synthetic OAuth call.
 */
const RESERVED_MCP_TOOL_MARKERS: readonly string[] = [
  `${Constants.mcp_all}`,
  `${Constants.mcp_server}`,
  'oauth',
];

function isReservedMCPToolName(toolName: string): boolean {
  /** `mcp_` opens the server-scoped pluginKey namespace (`mcp_${serverName}`),
   *  and `lc_transfer_to_` opens the agent-handoff namespace (the client
   *  renders such calls as handoffs; the background and intent passes exclude
   *  them) — pre-strip tool keys could never enter either, since they always
   *  began with the server name itself. */
  if (
    toolName.startsWith(`${Constants.mcp_prefix}`) ||
    toolName.startsWith(`${Constants.LC_TRANSFER_TO_}`)
  ) {
    return true;
  }
  return RESERVED_MCP_TOOL_MARKERS.some(
    (marker) => toolName === marker || toolName.startsWith(`${marker}${Constants.mcp_delimiter}`),
  );
}

/**
 * Maps every raw tool name in a server's catalog to its model-facing name,
 * stripping redundant server-name prefixes collision-free: when two names
 * yield the same result — a bare `foo` next to `<server>_foo`, or the
 * case-variant pair `<server>_Foo` / `<Server>_Foo` under the case-insensitive
 * prefix match — every collider keeps its raw name, so two distinct upstream
 * tools can never collapse onto one key. Unprefixed names count against the
 * result set through their identity mapping, which is what makes the bare-name
 * case fall out of the same counter.
 */
export function stripServerNamePrefixes(
  toolNames: readonly string[],
  normalizedServerName: string,
): Map<string, string> {
  const rawNames = new Set(toolNames);
  const finalNames = new Map<string, string>(
    toolNames.map((name) => {
      const stripped = stripServerNamePrefix(name, normalizedServerName);
      /** Every sibling's RAW name is reserved even when that sibling itself
       *  strips away: keys persisted BEFORE stripping embed raw names, so a
       *  stripped result landing on another sibling's raw name would route
       *  that sibling's legacy references to the wrong upstream tool. */
      return [name, stripped !== name && rawNames.has(stripped) ? name : stripped];
    }),
  );
  /** Reverting a collider to its raw name can itself collide with ANOTHER
   *  sibling's stripped result (`foo` / `acme_foo` / `acme_acme_foo`), so the
   *  guard iterates to a fixpoint. Each pass converts at least one stripped
   *  result back to its unique raw name, so it terminates within the catalog
   *  size. */
  let changed = true;
  while (changed) {
    changed = false;
    const counts = new Map<string, number>();
    finalNames.forEach((result) => {
      counts.set(result, (counts.get(result) ?? 0) + 1);
    });
    finalNames.forEach((result, raw) => {
      if (result !== raw && (counts.get(result) ?? 0) > 1) {
        finalNames.set(raw, raw);
        changed = true;
      }
    });
  }
  return finalNames;
}

export function splitMCPToolKey(
  toolKey: string,
  knownServerNames?: readonly string[],
): [string, string | undefined] {
  if (knownServerNames?.length) {
    let matched: string | undefined;
    for (let i = 0; i < knownServerNames.length; i++) {
      const serverName = knownServerNames[i];
      if (!serverName || serverName.length <= (matched?.length ?? 0)) {
        continue;
      }
      if (toolKey.endsWith(`${Constants.mcp_delimiter}${serverName}`)) {
        matched = serverName;
      }
    }
    if (matched != null) {
      return [
        toolKey.slice(0, toolKey.length - matched.length - Constants.mcp_delimiter.length),
        matched,
      ];
    }
  }

  const idx = toolKey.lastIndexOf(Constants.mcp_delimiter);
  if (idx === -1) {
    return [toolKey, undefined];
  }
  return [toolKey.slice(0, idx), toolKey.slice(idx + Constants.mcp_delimiter.length)];
}

/**
 * Splits a tool-call name for display, where the key may be a synthetic MCP OAuth
 * call (`oauth${mcp_delimiter}${serverName}`) rather than a real tool key.
 *
 * A configured server name is authoritative when one matches, because a real tool key
 * always ends in its server. Only when none matches does the `oauth` prefix decide,
 * which keeps a genuine upstream tool named `oauth${mcp_delimiter}...` from being read
 * as a synthetic call while still resolving OAuth prompts for unconfigured servers.
 */
export function splitToolCallName(
  toolCallName: string,
  knownServerNames?: readonly string[],
): [string, string | undefined] {
  if (knownServerNames?.length) {
    const [toolName, serverName] = splitMCPToolKey(toolCallName, knownServerNames);
    if (serverName != null && knownServerNames.includes(serverName)) {
      return [toolName, serverName];
    }
  }

  const oauthPrefix = `oauth${Constants.mcp_delimiter}`;
  if (toolCallName.startsWith(oauthPrefix)) {
    return ['oauth', toolCallName.slice(oauthPrefix.length)];
  }
  return splitMCPToolKey(toolCallName, knownServerNames);
}

/** Maximum explicit subagent hops allowed from any root agent at runtime. */
/** Upper bound on WebAuthn credentials a single user may register. */
export const MAX_PASSKEYS_PER_USER = 20;

export const MAX_SUBAGENT_DEPTH = 5;

/** Maximum unique explicit subagent targets that may be loaded at runtime. */
export const MAX_SUBAGENT_GRAPH_NODES = 50;

/** Maximum expanded SubagentConfig entries embedded into one run request. */
export const MAX_SUBAGENT_RUN_CONFIGS = 100;

export enum LocalStorageKeys {
  /** Key for the admin defined App Title */
  APP_TITLE = 'appTitle',
  /** Key for the last conversation setup. */
  LAST_CONVO_SETUP = 'lastConversationSetup',
  /** Key for the last selected model. */
  LAST_MODEL = 'lastSelectedModel',
  /** Key for the last selected tools. */
  LAST_TOOLS = 'lastSelectedTools',
  /** Key for the last selected spec by name*/
  LAST_SPEC = 'lastSelectedSpec',
  /** Key for temporary files to delete */
  FILES_TO_DELETE = 'filesToDelete',
  /** Prefix key for the last selected assistant ID by index */
  ASST_ID_PREFIX = 'assistant_id__',
  /** Prefix key for the last selected agent ID by index */
  AGENT_ID_PREFIX = 'agent_id__',
  /** Key for the last selected fork setting */
  FORK_SETTING = 'forkSetting',
  /** Key for remembering the last selected option, instead of manually selecting */
  REMEMBER_FORK_OPTION = 'rememberDefaultFork',
  /** Key for remembering the split at target fork option modifier */
  FORK_SPLIT_AT_TARGET = 'splitAtTarget',
  /** Key for saving text drafts */
  TEXT_DRAFT = 'textDraft_',
  /** Key for saving file drafts */
  FILES_DRAFT = 'filesDraft_',
  /** Key for last Selected Prompt Category */
  LAST_PROMPT_CATEGORY = 'lastPromptCategory',
  /** Key for rendering User Messages as Markdown */
  ENABLE_USER_MSG_MARKDOWN = 'enableUserMsgMarkdown',
  /** Key for auto-expanding tool call details */
  AUTO_EXPAND_TOOLS = 'autoExpandTools',
  /** Last selected MCP values per conversation ID */
  LAST_MCP_ = 'LAST_MCP_',
  /** Last checked toggle for Code Interpreter API per conversation ID */
  LAST_CODE_TOGGLE_ = 'LAST_CODE_TOGGLE_',
  /** Last checked toggle for Web Search per conversation ID */
  LAST_WEB_SEARCH_TOGGLE_ = 'LAST_WEB_SEARCH_TOGGLE_',
  /** Last checked toggle for File Search per conversation ID */
  LAST_FILE_SEARCH_TOGGLE_ = 'LAST_FILE_SEARCH_TOGGLE_',
  /** Last checked toggle for Artifacts per conversation ID */
  LAST_ARTIFACTS_TOGGLE_ = 'LAST_ARTIFACTS_TOGGLE_',
  /** Last checked toggle for Skills per conversation ID */
  LAST_SKILLS_TOGGLE_ = 'LAST_SKILLS_TOGGLE_',
  /** Last checked toggle for Memory per conversation ID */
  LAST_MEMORY_TOGGLE_ = 'LAST_MEMORY_TOGGLE_',
  /** Key for the last selected agent provider */
  LAST_AGENT_PROVIDER = 'lastAgentProvider',
  /** Key for the last selected agent model */
  LAST_AGENT_MODEL = 'lastAgentModel',
  /** Pin state for MCP tools per conversation ID */
  PIN_MCP_ = 'PIN_MCP_',
  /** Pin state for Web Search per conversation ID */
  PIN_WEB_SEARCH_ = 'PIN_WEB_SEARCH_',
  /** Pin state for Code Interpreter per conversation ID */
  PIN_CODE_INTERPRETER_ = 'PIN_CODE_INTERPRETER_',
  /** Key for the last selected code approval mode */
  LAST_CODE_APPROVAL_MODE = 'lastCodeApprovalMode',
}

export enum ForkOptions {
  /** Key for direct path option */
  DIRECT_PATH = 'directPath',
  /** Key for including branches */
  INCLUDE_BRANCHES = 'includeBranches',
  /** Key for target level fork (default) */
  TARGET_LEVEL = 'targetLevel',
  /** Default option */
  DEFAULT = 'default',
}

/**
 * Enum for Cohere related constants
 */
export enum CohereConstants {
  /**
   * Cohere API Endpoint, for special handling
   */
  API_URL = 'https://api.cohere.ai/v1',
  /**
   * Role for "USER" messages
   */
  ROLE_USER = 'USER',
  /**
   * Role for "SYSTEM" messages
   */
  ROLE_SYSTEM = 'SYSTEM',
  /**
   * Role for "CHATBOT" messages
   */
  ROLE_CHATBOT = 'CHATBOT',
  /**
   * Title message as required by Cohere
   */
  TITLE_MESSAGE = 'TITLE:',
}

export enum SystemCategories {
  ALL = 'sys__all__sys',
  MY_PROMPTS = 'sys__my__prompts__sys',
  NO_CATEGORY = 'sys__no__category__sys',
  SHARED_PROMPTS = 'sys__shared__prompts__sys',
}

export const providerEndpointMap = {
  [EModelEndpoint.openAI]: EModelEndpoint.openAI,
  [EModelEndpoint.bedrock]: EModelEndpoint.bedrock,
  [EModelEndpoint.anthropic]: EModelEndpoint.anthropic,
  [EModelEndpoint.azureOpenAI]: EModelEndpoint.azureOpenAI,
};

export const specialVariables = {
  current_date: true,
  current_user: true,
  iso_datetime: true,
  current_datetime: true,
};

export type TSpecialVarLabel = `com_ui_special_var_${keyof typeof specialVariables}`;

/**
 * Retrieves a specific field from the endpoints configuration for a given endpoint key.
 * Does not infer or default any endpoint type when absent.
 */
export function getEndpointField<
  K extends TConfig[keyof TConfig] extends never ? never : keyof TConfig,
>(
  endpointsConfig: TEndpointsConfig | undefined | null,
  endpoint: EModelEndpoint | string | null | undefined,
  property: K,
): TConfig[K] | undefined {
  if (!endpointsConfig || endpoint === null || endpoint === undefined) {
    return undefined;
  }
  const config = endpointsConfig[endpoint];
  if (!config) {
    return undefined;
  }
  return config[property];
}

/**
 * Resolves the effective endpoint type:
 * - Non-agents endpoint: config.type || endpoint
 * - Agents + provider: config[provider].type || provider
 * - Agents, no provider: EModelEndpoint.agents
 *
 * Returns `undefined` when endpoint is null/undefined.
 */
export function resolveEndpointType(
  endpointsConfig: TEndpointsConfig | undefined | null,
  endpoint: string | null | undefined,
  agentProvider?: string | null,
): EModelEndpoint | string | undefined {
  if (!endpoint) {
    return undefined;
  }

  if (!isAgentsEndpoint(endpoint)) {
    return getEndpointField(endpointsConfig, endpoint, 'type') || endpoint;
  }

  if (agentProvider) {
    const providerType = getEndpointField(endpointsConfig, agentProvider, 'type');
    if (providerType) {
      return providerType;
    }
    return agentProvider;
  }

  return EModelEndpoint.agents;
}

/** Resolves the `defaultParamsEndpoint` for a given endpoint from its custom params config */
export function getDefaultParamsEndpoint(
  endpointsConfig: TEndpointsConfig | undefined | null,
  endpoint: string | null | undefined,
): string | undefined {
  if (!endpointsConfig || !endpoint) {
    return undefined;
  }
  return endpointsConfig[endpoint]?.customParams?.defaultParamsEndpoint;
}