{"version":3,"file":"index.mjs","names":["s.BedrockReasoningConfig","s.isMythosClassModel","_obj","s.removeNullishValues","axios","_axios","s.isAssistantsEndpoint"],"sources":["../src/bedrock.ts","../src/types/runs.ts","../src/parsers.ts","../src/azure.ts","../src/langchain.ts","../src/resolve-llm-delivery-path.ts","../src/messages.ts","../src/errors.ts","../src/runSteps.ts","../src/artifacts.ts","../src/permissions.ts","../src/roles.ts","../src/types.ts","../src/types/schedules.ts","../src/cadence.ts","../src/types/skills.ts","../src/types/web.ts","../src/types/insights.ts","../src/types/traces.ts","../src/types/queuedTurns.ts","../src/providers.ts","../src/svg.ts","../src/actions.ts","../src/createPayload.ts","../src/parameterSettings.ts","../src/agentToolOptions.ts","../src/codeEnvRef.ts","../src/code/worker.ts"],"sourcesContent":["import { z } from 'zod';\nimport * as s from './schemas';\n\nconst DEFAULT_THINKING_BUDGET = 2000;\nconst BEDROCK_CLAUDE_SONNET_4_6_MAX_OUTPUT = 64000;\nexport const BEDROCK_OUTPUT_128K_BETA = 'output-128k-2025-02-19';\nexport const BEDROCK_FINE_GRAINED_TOOL_STREAMING_BETA = 'fine-grained-tool-streaming-2025-05-14';\n\n/** Betas LibreChat injects itself, safe to strip from persisted AMRF when a\n * model no longer supports them; anything else in `anthropic_beta` is a user opt-in. */\nconst GENERATED_BEDROCK_BETAS = new Set<string>([\n  BEDROCK_OUTPUT_128K_BETA,\n  BEDROCK_FINE_GRAINED_TOOL_STREAMING_BETA,\n]);\n\nconst bedrockReasoningConfigValues = new Set<string>(Object.values(s.BedrockReasoningConfig));\n\ntype ThinkingConfig =\n  | { type: 'enabled'; budget_tokens: number }\n  | { type: 'adaptive'; display?: s.ThinkingDisplayWireValue }\n  | { type: 'disabled' };\n\n/**\n * Resolves the final `thinking.display` value for an adaptive-thinking request.\n *\n * Starting with Claude Opus 4.7, the Messages API returns empty `thinking`\n * blocks unless the request sets `thinking.display`. This helper encodes the\n * three user-facing modes — `'auto'` (LibreChat decides), `'summarized'`, and\n * `'omitted'` — into the wire value (or `undefined` when the field should be\n * left off).\n *\n * See https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7#thinking-content-omitted-by-default\n */\n/**\n * Safely extracts a nested `thinking.display` string from a persisted\n * `additionalModelRequestFields` object, returning `undefined` if the shape\n * isn't what we expect.\n */\nfunction extractPersistedDisplay(amrf: unknown): string | undefined {\n  if (typeof amrf !== 'object' || amrf === null) {\n    return undefined;\n  }\n  const thinking = (amrf as Record<string, unknown>).thinking;\n  if (typeof thinking !== 'object' || thinking === null) {\n    return undefined;\n  }\n  const display = (thinking as Record<string, unknown>).display;\n  return typeof display === 'string' ? display : undefined;\n}\n\nexport function resolveThinkingDisplay(\n  model: string,\n  explicit?: s.ThinkingDisplay | string | null,\n): s.ThinkingDisplayWireValue | undefined {\n  if (explicit === s.ThinkingDisplay.summarized) {\n    return s.ThinkingDisplay.summarized;\n  }\n  if (explicit === s.ThinkingDisplay.omitted) {\n    return s.ThinkingDisplay.omitted;\n  }\n  if (omitsThinkingByDefault(model)) {\n    return s.ThinkingDisplay.summarized;\n  }\n  return undefined;\n}\n\ntype AnthropicReasoning = {\n  thinking?: ThinkingConfig | boolean;\n  thinkingBudget?: number;\n};\n\ntype AnthropicInput = BedrockConverseInput & {\n  additionalModelRequestFields: BedrockConverseInput['additionalModelRequestFields'] &\n    AnthropicReasoning;\n};\n\n/** Extracts opus major/minor version from both naming formats */\nfunction parseOpusVersion(model: string): { major: number; minor: number } | null {\n  const nameFirst = model.match(/claude-opus[-.]?(\\d+)(?:[-.](\\d{1,2})(?!\\d))?/);\n  if (nameFirst) {\n    return {\n      major: parseInt(nameFirst[1], 10),\n      minor: nameFirst[2] != null ? parseInt(nameFirst[2], 10) : 0,\n    };\n  }\n  const numFirst = model.match(/claude-(\\d+)(?:[-.](\\d{1,2})(?!\\d))?-opus/);\n  if (numFirst) {\n    return {\n      major: parseInt(numFirst[1], 10),\n      minor: numFirst[2] != null ? parseInt(numFirst[2], 10) : 0,\n    };\n  }\n  return null;\n}\n\n/** Extracts sonnet major/minor version from both naming formats.\n *  Uses bounded minor capture to avoid matching date suffixes (e.g., -20250514). */\nfunction parseSonnetVersion(model: string): { major: number; minor: number } | null {\n  const nameFirst = model.match(/claude-sonnet[-.]?(\\d+)(?:[-.](\\d{1,2})(?!\\d))?/);\n  if (nameFirst) {\n    return {\n      major: parseInt(nameFirst[1], 10),\n      minor: nameFirst[2] != null ? parseInt(nameFirst[2], 10) : 0,\n    };\n  }\n  const numFirst = model.match(/claude-(\\d+)(?:[-.](\\d{1,2})(?!\\d))?-sonnet/);\n  if (numFirst) {\n    return {\n      major: parseInt(numFirst[1], 10),\n      minor: numFirst[2] != null ? parseInt(numFirst[2], 10) : 0,\n    };\n  }\n  return null;\n}\n\n/**\n * Mythos-class detection (Claude Fable / Mythos) lives in `schemas.ts` as\n * `isMythosClassModel` — the single source of truth for the family names.\n * The helpers below OR it in alongside the `opus`/`sonnet` version parsers.\n */\n\n/** Checks if a model supports adaptive thinking (Opus 4.6+, Sonnet 4.6+, Fable/Mythos) */\nexport function supportsAdaptiveThinking(model: string): boolean {\n  const opus = parseOpusVersion(model);\n  if (opus && (opus.major > 4 || (opus.major === 4 && opus.minor >= 6))) {\n    return true;\n  }\n  const sonnet = parseSonnetVersion(model);\n  if (sonnet != null && (sonnet.major > 4 || (sonnet.major === 4 && sonnet.minor >= 6))) {\n    return true;\n  }\n  if (s.isMythosClassModel(model)) {\n    return true;\n  }\n  return false;\n}\n\n/**\n * Checks if a model omits `thinking` content from responses by default.\n *\n * Starting with Claude Opus 4.7, the Messages API returns empty `thinking`\n * blocks unless the request explicitly opts in via `thinking.display =\n * \"summarized\"`. This helper narrows the opt-in to Opus 4.7+ (and any future\n * major Opus version) so older adaptive-thinking models are left untouched.\n *\n * See https://platform.claude.com/docs/en/about-claude/models/whats-new-claude-4-7#thinking-content-omitted-by-default\n */\nexport function omitsThinkingByDefault(model: string): boolean {\n  const opus = parseOpusVersion(model);\n  if (opus && (opus.major > 4 || (opus.major === 4 && opus.minor >= 7))) {\n    return true;\n  }\n  const sonnet = parseSonnetVersion(model);\n  if (sonnet != null && sonnet.major >= 5) {\n    return true;\n  }\n  if (s.isMythosClassModel(model)) {\n    return true;\n  }\n  return false;\n}\n\nexport function omitsSamplingParameters(model: string): boolean {\n  const opus = parseOpusVersion(model);\n  if (opus && (opus.major > 4 || (opus.major === 4 && opus.minor >= 7))) {\n    return true;\n  }\n  const sonnet = parseSonnetVersion(model);\n  if (sonnet != null && sonnet.major >= 5) {\n    return true;\n  }\n  if (s.isMythosClassModel(model)) {\n    return true;\n  }\n  return false;\n}\n\n/**\n * Whether disabling thinking requires sending an explicit `{ type: 'disabled' }`\n * config rather than simply omitting the `thinking` field.\n *\n * Sonnet 5 and Opus 5 treat an omitted `thinking` field as adaptive thinking ON\n * by default, so honoring a user who turns thinking off means sending the\n * disabled config explicitly. Opus 4.7/4.8 run without thinking when the field\n * is omitted, and Fable/Mythos reject an explicit disabled config (400,\n * thinking always on), so both are excluded.\n *\n * See https://platform.claude.com/docs/en/about-claude/models/migration-guide#migrating-to-claude-sonnet-5\n */\nexport function requiresExplicitThinkingDisabled(model: string): boolean {\n  const sonnet = parseSonnetVersion(model);\n  if (sonnet != null && sonnet.major >= 5) {\n    return true;\n  }\n  const opus = parseOpusVersion(model);\n  return opus != null && opus.major >= 5;\n}\n\n/** Effort levels Opus 5 rejects while thinking is explicitly disabled. */\nconst EFFORTS_REJECTED_WHEN_THINKING_DISABLED = new Set<string>([\n  s.AnthropicEffort.xhigh,\n  s.AnthropicEffort.max,\n]);\n\n/**\n * Whether the model caps `output_config.effort` while thinking is disabled.\n *\n * Opus 5 rejects `xhigh`/`max` in that combination with a 400: \"output_config\n * .effort 'xhigh' is not supported when thinking is disabled on this model. Use\n * effort 'high' or below, or enable thinking.\" Opus 4.7/4.8, Sonnet 5, and\n * Sonnet 4.6 accept every effort level they otherwise support with thinking\n * off, so the cap is Opus 5+ only.\n */\nexport function capsEffortWhenThinkingDisabled(model: string): boolean {\n  const opus = parseOpusVersion(model);\n  return opus != null && opus.major >= 5;\n}\n\n/**\n * Lowers an effort level the model would reject while thinking is disabled to\n * the highest accepted value (`high`, which is also the API default). Returns\n * the effort unchanged when the combination is valid.\n */\nexport function clampEffortForDisabledThinking(model: string, effort: string): string {\n  if (\n    capsEffortWhenThinkingDisabled(model) &&\n    EFFORTS_REJECTED_WHEN_THINKING_DISABLED.has(effort)\n  ) {\n    return s.AnthropicEffort.high;\n  }\n  return effort;\n}\n\n/** An `output_config` container carrying a usable effort level. */\nfunction hasStringEffort(value: unknown): value is { effort: string } {\n  if (typeof value !== 'object' || value === null || !('effort' in value)) {\n    return false;\n  }\n  return typeof value.effort === 'string';\n}\n\n/**\n * Clamps an `output_config.effort` in place when the model would reject it\n * while thinking is disabled. No-op when the container carries no string\n * effort, so callers can pass a possibly-absent config directly.\n */\nexport function clampOutputConfigEffort(model: string, outputConfig: unknown): void {\n  if (!hasStringEffort(outputConfig)) {\n    return;\n  }\n  outputConfig.effort = clampEffortForDisabledThinking(model, outputConfig.effort);\n}\n\n/** Whether a resolved thinking config is an explicit `{ type: 'disabled' }`. */\nexport function isThinkingDisabled(thinking: unknown): boolean {\n  if (typeof thinking !== 'object' || thinking === null || !('type' in thinking)) {\n    return false;\n  }\n  return thinking.type === 'disabled';\n}\n\n/** Checks if a model has a 1M context window (Sonnet 4.6+, Opus 4.6+, Opus 5+, Fable/Mythos) */\nexport function supportsContext1m(model: string): boolean {\n  const sonnet = parseSonnetVersion(model);\n  if (sonnet != null && (sonnet.major > 4 || (sonnet.major === 4 && sonnet.minor >= 6))) {\n    return true;\n  }\n  const opus = parseOpusVersion(model);\n  if (opus && (opus.major > 4 || (opus.major === 4 && opus.minor >= 6))) {\n    return true;\n  }\n  if (s.isMythosClassModel(model)) {\n    return true;\n  }\n  return false;\n}\n\n/**\n * Checks whether a native Anthropic Claude model supports prompt caching.\n *\n * This uses the configured model ID directly. Resolving it through a token\n * map first can collapse a newly released Claude model to the generic\n * `claude-` fallback and incorrectly disable cache control.\n */\nexport function supportsPromptCache(model: string): boolean {\n  if (model.includes('claude-3-5-sonnet-latest') || model.includes('claude-3.5-sonnet-latest')) {\n    return false;\n  }\n\n  return (\n    /claude-3[-.]7/.test(model) ||\n    /claude-3[-.]5-(?:sonnet|haiku)/.test(model) ||\n    /claude-3-(?:sonnet|haiku|opus)?/.test(model) ||\n    /claude-(?:sonnet|opus|haiku)[-.]?(?:[4-9]|\\d{2,})/.test(model) ||\n    /claude-(?:[4-9]|\\d{2,})(?:[-.](?:sonnet|opus|haiku))?/.test(model) ||\n    s.isMythosClassModel(model)\n  );\n}\n\n/**\n * A Bedrock Claude model ID may be prefixed (`anthropic.claude-*`,\n * `us.anthropic.claude-*`, `global.anthropic.claude-*`) or bare (`claude-*`,\n * used when the LibreChat model ID maps to an application inference profile).\n * Match on the `claude` family token so every form is recognized — requiring\n * the literal `anthropic.` prefix silently dropped thinking config, beta\n * headers, and sampling handling for inference-profile deployments.\n */\nconst BEDROCK_CLAUDE_4PLUS_THINKING =\n  /claude-(?:[4-9](?:\\.\\d+)?(?:-\\d+)?-(?:sonnet|opus|haiku)|(?:sonnet|opus|haiku)-[4-9])/;\n\n/** Whether a Bedrock model ID is an Anthropic Claude model (prefixed or bare). */\nfunction isBedrockClaudeModel(model: string): boolean {\n  return model.includes('claude');\n}\n\n/**\n * Gets the appropriate anthropic_beta headers for Bedrock Anthropic models.\n * Bedrock uses `anthropic_beta` (with underscore) in additionalModelRequestFields.\n *\n * @param model - The Bedrock model identifier (e.g., \"anthropic.claude-sonnet-4-6\")\n * @returns Array of beta header strings, or empty array if not applicable\n */\nfunction getBedrockAnthropicBetaHeaders(model: string): string[] {\n  const betaHeaders: string[] = [];\n\n  /** Mythos-class (Fable/Mythos) is intentionally not matched: these betas are built-in/no-op for the\n   * 4.7+ generation (Fable has native 128K output), so omitting them on Bedrock is lossless. */\n  const isClaude4PlusModel = BEDROCK_CLAUDE_4PLUS_THINKING.test(model);\n  const isClaudeThinkingModel = model.includes('claude-3-7-sonnet') || isClaude4PlusModel;\n\n  if (isClaudeThinkingModel) {\n    betaHeaders.push(BEDROCK_OUTPUT_128K_BETA);\n  }\n\n  if (isClaude4PlusModel) {\n    betaHeaders.push(BEDROCK_FINE_GRAINED_TOOL_STREAMING_BETA);\n  }\n\n  return betaHeaders;\n}\n\n/** Flatten an anthropic_beta value (array, single string, or comma-delimited\n * string) into trimmed, non-empty header tokens. */\nfunction normalizeBetaHeaders(value: unknown): string[] {\n  let values: unknown[] = [];\n  if (Array.isArray(value)) {\n    values = value;\n  } else if (typeof value === 'string') {\n    values = [value];\n  }\n  const headers: string[] = [];\n  values.forEach((entry) => {\n    if (typeof entry !== 'string') {\n      return;\n    }\n    entry\n      .split(',')\n      .map((header) => header.trim())\n      .filter(Boolean)\n      .forEach((header) => headers.push(header));\n  });\n  return headers;\n}\n\nfunction mergeBedrockAnthropicBetaHeaders(existing: unknown, generated: string[]): string[] {\n  const generatedSet = new Set(generated);\n  const betaHeaders = new Set<string>();\n\n  [...normalizeBetaHeaders(existing), ...generated].forEach((header) => {\n    /** Drop a generated beta carried over from a prior model that the current\n     * model does not generate (e.g. fine-grained-tool-streaming on a 3.7\n     * profile); user opt-ins are always preserved. */\n    if (GENERATED_BEDROCK_BETAS.has(header) && !generatedSet.has(header)) {\n      return;\n    }\n    betaHeaders.add(header);\n  });\n\n  return Array.from(betaHeaders);\n}\n\nexport const bedrockInputSchema = s.tConversationSchema\n  .pick({\n    /* LibreChat params; optionType: 'conversation' */\n    chatProjectId: true,\n    modelLabel: true,\n    promptPrefix: true,\n    resendFiles: true,\n    iconURL: true,\n    greeting: true,\n    spec: true,\n    maxOutputTokens: true,\n    maxContextTokens: true,\n    artifacts: true,\n    /* Bedrock params; optionType: 'model' */\n    region: true,\n    system: true,\n    model: true,\n    maxTokens: true,\n    temperature: true,\n    topP: true,\n    stop: true,\n    thinking: true,\n    thinkingBudget: true,\n    effort: true,\n    thinkingDisplay: true,\n    reasoning_effort: true,\n    promptCache: true,\n    promptCacheTtl: true,\n    /* Catch-all fields */\n    topK: true,\n    additionalModelRequestFields: true,\n  })\n  .transform((obj) => {\n    if ((obj as AnthropicInput).additionalModelRequestFields?.thinking != null) {\n      const _obj = obj as AnthropicInput;\n      const thinking = _obj.additionalModelRequestFields.thinking;\n      const isDisabled =\n        typeof thinking === 'object' &&\n        thinking !== null &&\n        (thinking as { type?: string }).type === 'disabled';\n      obj.thinking = isDisabled ? false : !!thinking;\n      obj.thinkingBudget =\n        typeof thinking === 'object' && 'budget_tokens' in thinking\n          ? thinking.budget_tokens\n          : undefined;\n      if (obj.thinkingDisplay == null) {\n        const persistedDisplay = extractPersistedDisplay({ thinking });\n        if (\n          persistedDisplay === s.ThinkingDisplay.summarized ||\n          persistedDisplay === s.ThinkingDisplay.omitted\n        ) {\n          obj.thinkingDisplay = persistedDisplay as s.ThinkingDisplay;\n        }\n      }\n      delete obj.additionalModelRequestFields;\n    }\n    return s.removeNullishValues(obj);\n  })\n  .catch(() => ({}));\n\nexport type BedrockConverseInput = z.infer<typeof bedrockInputSchema>;\n\nexport const bedrockInputParser = s.tConversationSchema\n  .pick({\n    /* LibreChat params; optionType: 'conversation' */\n    chatProjectId: true,\n    modelLabel: true,\n    promptPrefix: true,\n    resendFiles: true,\n    iconURL: true,\n    greeting: true,\n    spec: true,\n    artifacts: true,\n    maxOutputTokens: true,\n    maxContextTokens: true,\n    /* Bedrock params; optionType: 'model' */\n    region: true,\n    model: true,\n    maxTokens: true,\n    temperature: true,\n    topP: true,\n    stop: true,\n    thinking: true,\n    thinkingBudget: true,\n    effort: true,\n    thinkingDisplay: true,\n    reasoning_effort: true,\n    promptCache: true,\n    promptCacheTtl: true,\n    /* Catch-all fields */\n    topK: true,\n    additionalModelRequestFields: true,\n  })\n  .catchall(z.any())\n  .transform((data) => {\n    const knownKeys = [\n      'chatProjectId',\n      'modelLabel',\n      'promptPrefix',\n      'resendFiles',\n      'iconURL',\n      'greeting',\n      'spec',\n      'maxOutputTokens',\n      'artifacts',\n      'additionalModelRequestFields',\n      'region',\n      'model',\n      'maxTokens',\n      'temperature',\n      'topP',\n      'stop',\n      'promptCache',\n      'promptCacheTtl',\n    ];\n\n    const additionalFields: Record<string, unknown> = {};\n    const typedData = data as Record<string, unknown>;\n    const shouldOmitSamplingParameters =\n      typeof typedData.model === 'string' && omitsSamplingParameters(typedData.model);\n\n    Object.entries(typedData).forEach(([key, value]) => {\n      if (!knownKeys.includes(key)) {\n        if (key === 'topK') {\n          additionalFields['top_k'] = value;\n        } else {\n          additionalFields[key] = value;\n        }\n        delete typedData[key];\n      }\n    });\n\n    /**\n     * Persisted `model_parameters` can carry a prior \"thinking off\" only inside\n     * `additionalModelRequestFields.thinking = { type: 'disabled' }` (a known\n     * key that isn't spread into `additionalFields`). `initializeBedrock` feeds\n     * those params straight through this parser, so surface that as\n     * `thinking: false` — otherwise the disabled branch is skipped and the\n     * config rebuilds adaptive, flipping a user's Sonnet 5 setting back on.\n     */\n    const persistedThinking = (\n      typedData.additionalModelRequestFields as { thinking?: unknown } | undefined\n    )?.thinking;\n    if (\n      additionalFields.thinking === undefined &&\n      typeof persistedThinking === 'object' &&\n      persistedThinking !== null &&\n      (persistedThinking as { type?: string }).type === 'disabled'\n    ) {\n      additionalFields.thinking = false;\n    }\n\n    /** Bedrock thinking-capable Claude models: 3.7 Sonnet, Claude 4+ (opus/sonnet/haiku), and Mythos-class (Fable/Mythos). */\n    const isThinkingModel =\n      typeof typedData.model === 'string' &&\n      (typedData.model.includes('claude-3-7-sonnet') ||\n        BEDROCK_CLAUDE_4PLUS_THINKING.test(typedData.model) ||\n        s.isMythosClassModel(typedData.model));\n\n    if (isThinkingModel) {\n      const isAdaptive = supportsAdaptiveThinking(typedData.model as string);\n\n      if (isAdaptive) {\n        /** Persisted AMRF is spread into the final request, so clearing only\n         * `additionalFields` leaves a stale value from a prior selection. */\n        const persistedAmrf = typedData.additionalModelRequestFields as\n          | Record<string, unknown>\n          | undefined;\n        const thinkingDisabled = additionalFields.thinking === false;\n        const effort = additionalFields.effort;\n        if (typeof effort === 'string' && effort !== '') {\n          additionalFields.output_config = { effort };\n        } else if (effort !== undefined && persistedAmrf) {\n          /** Explicit unset ('' or null) clears the persisted effort. An absent\n           * effort (agent resume, where the prior llmConfig persisted\n           * `output_config` but no top-level `effort`) preserves it. */\n          delete persistedAmrf.output_config;\n        }\n        delete additionalFields.effort;\n\n        /**\n         * Opus 5 rejects `xhigh`/`max` effort while thinking is disabled, so\n         * clamp both the effort derived above and any effort still carried in\n         * persisted AMRF (agent resume sends `output_config` with no top-level\n         * `effort`, so the branch above leaves it untouched).\n         */\n        if (thinkingDisabled) {\n          [additionalFields, persistedAmrf].forEach((target) =>\n            clampOutputConfigEffort(typedData.model as string, target?.output_config),\n          );\n        }\n\n        if (additionalFields.thinking === false) {\n          delete additionalFields.thinkingBudget;\n          delete additionalFields.thinkingDisplay;\n          if (requiresExplicitThinkingDisabled(typedData.model as string)) {\n            additionalFields.thinking = { type: 'disabled' };\n          } else {\n            delete additionalFields.thinking;\n            /** Disable-by-omission models (Opus 4.7+): drop the persisted\n             * adaptive config so turning thinking off actually disables it. */\n            if (persistedAmrf) {\n              delete persistedAmrf.thinking;\n            }\n          }\n        } else {\n          /**\n           * Persisted agent `model_parameters` round-trip back through this\n           * parser with the prior `thinking.display` embedded in\n           * `additionalModelRequestFields`. Surface it as the resolver's\n           * explicit value when no top-level `thinkingDisplay` is set so the\n           * prior user choice (e.g. 'omitted') survives instead of being\n           * clobbered by the Opus 4.7+ auto → 'summarized' fallback.\n           */\n          const topLevelDisplay = additionalFields.thinkingDisplay as\n            | s.ThinkingDisplay\n            | string\n            | null\n            | undefined;\n          const persistedDisplay = extractPersistedDisplay(typedData.additionalModelRequestFields);\n          const thinkingConfig: ThinkingConfig = { type: 'adaptive' };\n          const display = resolveThinkingDisplay(\n            typedData.model as string,\n            topLevelDisplay ?? persistedDisplay,\n          );\n          if (display) {\n            thinkingConfig.display = display;\n          }\n          additionalFields.thinking = thinkingConfig;\n          delete additionalFields.thinkingBudget;\n          delete additionalFields.thinkingDisplay;\n        }\n      } else {\n        if (additionalFields.thinking === undefined) {\n          additionalFields.thinking = true;\n        } else if (additionalFields.thinking === false) {\n          delete additionalFields.thinking;\n          delete additionalFields.thinkingBudget;\n        }\n\n        if (additionalFields.thinking === true && additionalFields.thinkingBudget === undefined) {\n          additionalFields.thinkingBudget = DEFAULT_THINKING_BUDGET;\n        }\n        delete additionalFields.effort;\n        delete additionalFields.thinkingDisplay;\n\n        /** A bare non-adaptive thinking profile (e.g. `claude-3-7-sonnet`) must\n         * not inherit an adaptive/disabled thinking object or `output_config`\n         * persisted from another model; this branch's own fields are authoritative. */\n        const persistedAmrf = typedData.additionalModelRequestFields as\n          | Record<string, unknown>\n          | undefined;\n        if (persistedAmrf) {\n          delete persistedAmrf.thinking;\n          delete persistedAmrf.output_config;\n        }\n      }\n\n      /** Anthropic uses 'effort' via output_config, not reasoning_config */\n      delete additionalFields.reasoning_effort;\n\n      if (isBedrockClaudeModel(typedData.model as string)) {\n        const betaHeaders = getBedrockAnthropicBetaHeaders(typedData.model as string);\n        if (betaHeaders.length > 0) {\n          const existingBetaHeaders = (\n            typedData.additionalModelRequestFields as Record<string, unknown> | undefined\n          )?.anthropic_beta;\n          additionalFields.anthropic_beta = mergeBedrockAnthropicBetaHeaders(\n            existingBetaHeaders,\n            betaHeaders,\n          );\n        }\n      }\n    } else {\n      delete additionalFields.thinking;\n      delete additionalFields.thinkingBudget;\n      delete additionalFields.effort;\n      delete additionalFields.thinkingDisplay;\n      delete additionalFields.output_config;\n      delete additionalFields.anthropic_beta;\n\n      const reasoningEffort = additionalFields.reasoning_effort;\n      delete additionalFields.reasoning_effort;\n      if (\n        typeof reasoningEffort === 'string' &&\n        bedrockReasoningConfigValues.has(reasoningEffort)\n      ) {\n        additionalFields.reasoning_config = reasoningEffort;\n      }\n    }\n\n    const isAnthropicModel =\n      typeof typedData.model === 'string' && isBedrockClaudeModel(typedData.model);\n\n    /** Strip stale fields from previously-persisted additionalModelRequestFields */\n    if (\n      typeof typedData.additionalModelRequestFields === 'object' &&\n      typedData.additionalModelRequestFields != null\n    ) {\n      const amrf = typedData.additionalModelRequestFields as Record<string, unknown>;\n      if (!isAnthropicModel) {\n        delete amrf.anthropic_beta;\n        delete amrf.thinking;\n        delete amrf.thinkingBudget;\n        delete amrf.effort;\n        delete amrf.output_config;\n        delete amrf.reasoning_config;\n      } else {\n        delete amrf.reasoning_config;\n        delete amrf.reasoning_effort;\n        /** A Claude model that does not support Bedrock thinking (e.g. a bare\n         * `claude-3-5-sonnet` inference profile) must not carry stale thinking\n         * fields from a previously-selected thinking model. Drop only the\n         * LibreChat-generated betas (output-128k, fine-grained tool streaming);\n         * user opt-ins in `anthropic_beta` are preserved. */\n        if (!isThinkingModel) {\n          delete amrf.thinking;\n          delete amrf.thinkingBudget;\n          delete amrf.effort;\n          delete amrf.output_config;\n          if (amrf.anthropic_beta !== undefined) {\n            const kept = normalizeBetaHeaders(amrf.anthropic_beta).filter(\n              (header) => !GENERATED_BEDROCK_BETAS.has(header),\n            );\n            if (kept.length > 0) {\n              amrf.anthropic_beta = kept;\n            } else {\n              delete amrf.anthropic_beta;\n            }\n          }\n        }\n      }\n\n      if (shouldOmitSamplingParameters) {\n        delete amrf.temperature;\n        delete amrf.topP;\n        delete amrf.top_p;\n        delete amrf.topK;\n        delete amrf.top_k;\n      }\n    }\n\n    if (shouldOmitSamplingParameters) {\n      delete typedData.temperature;\n      delete typedData.topP;\n      delete additionalFields.temperature;\n      delete additionalFields.topP;\n      delete additionalFields.top_p;\n      delete additionalFields.topK;\n      delete additionalFields.top_k;\n    }\n\n    /** Default promptCache for claude and nova models, if not defined */\n    if (\n      typeof typedData.model === 'string' &&\n      (typedData.model.includes('claude') || typedData.model.includes('nova'))\n    ) {\n      if (typedData.promptCache === undefined) {\n        typedData.promptCache = true;\n      }\n    } else if (typedData.promptCache === true) {\n      typedData.promptCache = undefined;\n    }\n\n    /**\n     * A cache TTL is meaningless without caching — tie it to promptCache. When\n     * caching is off or unsupported for the model (cleared above), drop the TTL\n     * so an unsupported `1h` is never sent on a non-caching Bedrock request.\n     */\n    if (typedData.promptCache !== true) {\n      typedData.promptCacheTtl = undefined;\n    }\n\n    if (Object.keys(additionalFields).length > 0) {\n      typedData.additionalModelRequestFields = {\n        ...((typedData.additionalModelRequestFields as Record<string, unknown> | undefined) || {}),\n        ...additionalFields,\n      };\n    }\n\n    if (typedData.maxOutputTokens !== undefined) {\n      typedData.maxTokens = typedData.maxOutputTokens;\n    } else if (typedData.maxTokens !== undefined) {\n      typedData.maxOutputTokens = typedData.maxTokens;\n    }\n\n    return s.removeNullishValues(typedData) as BedrockConverseInput;\n  })\n  .catch(() => ({}));\n\n/**\n * Configures the \"thinking\" parameter based on given input and thinking options.\n *\n * @param data - The parsed Bedrock request options object\n * @returns The object with thinking configured appropriately\n */\n/**\n * `anthropicSettings.maxOutputTokens.reset` only matches the canonical\n * family-first id (`claude-sonnet-5`); Bedrock also accepts number-first\n * aliases (`claude-5-sonnet`, `claude-4-7-sonnet`) that this file gates as\n * thinking models. Canonicalize to family-first so those aliases resolve to the\n * real ceiling instead of the 8192 fallback.\n */\nfunction toFamilyFirstClaudeId(model: string): string {\n  return model.replace(/claude-(\\d+(?:[-.]\\d+)?)-(sonnet|opus|haiku)/, 'claude-$2-$1');\n}\n\nfunction isBedrockClaudeSonnet46(model: string): boolean {\n  return /claude-sonnet[-.]?4[-.]?6(?=$|[^0-9])/.test(toFamilyFirstClaudeId(model));\n}\n\n/**\n * Thinking tokens share the `maxTokens` output budget with tool-call arguments\n * (e.g. a `create_file` `content`), so a low default truncates large authored\n * files mid-argument. Mirror the direct-Anthropic path and default to the\n * model's full max output when the request does not set one explicitly.\n */\nfunction resolveThinkingMaxTokens(data: AnthropicInput): number {\n  const explicit = data.maxTokens ?? data.maxOutputTokens;\n  if (typeof explicit === 'number' && explicit > 0) {\n    return explicit;\n  }\n  const model = typeof data.model === 'string' ? data.model : '';\n  if (isBedrockClaudeSonnet46(model)) {\n    return BEDROCK_CLAUDE_SONNET_4_6_MAX_OUTPUT;\n  }\n  return s.anthropicSettings.maxOutputTokens.reset(toFamilyFirstClaudeId(model));\n}\n\nfunction configureThinking(data: AnthropicInput): AnthropicInput {\n  const updatedData = { ...data };\n  const thinking = updatedData.additionalModelRequestFields?.thinking;\n\n  if (thinking === true) {\n    updatedData.maxTokens = resolveThinkingMaxTokens(updatedData);\n    delete updatedData.maxOutputTokens;\n    const thinkingConfig: ThinkingConfig = {\n      type: 'enabled',\n      budget_tokens:\n        updatedData.additionalModelRequestFields?.thinkingBudget ?? DEFAULT_THINKING_BUDGET,\n    };\n\n    if (thinkingConfig.budget_tokens > updatedData.maxTokens) {\n      thinkingConfig.budget_tokens = Math.floor(updatedData.maxTokens * 0.9);\n    }\n    updatedData.additionalModelRequestFields!.thinking = thinkingConfig;\n    delete updatedData.additionalModelRequestFields!.thinkingBudget;\n  } else if (\n    typeof thinking === 'object' &&\n    thinking != null &&\n    (thinking as { type: string }).type === 'adaptive'\n  ) {\n    updatedData.maxTokens = resolveThinkingMaxTokens(updatedData);\n    delete updatedData.maxOutputTokens;\n    delete updatedData.additionalModelRequestFields!.thinkingBudget;\n  }\n\n  return updatedData;\n}\n\n/** Top-level Converse request fields (issue #14029: `system` from a preset).\n *  The input parser's catch-all routes unknown keys into\n *  additionalModelRequestFields, and Bedrock rejects any that collide with a\n *  field the request already sends (`messages`/`modelId` always,\n *  `inferenceConfig` whenever maxTokens is set, `toolConfig` for agents). */\nconst RESERVED_CONVERSE_FIELDS = [\n  'system',\n  'messages',\n  'modelId',\n  'toolConfig',\n  'inferenceConfig',\n  'guardrailConfig',\n  'promptVariables',\n  'requestMetadata',\n  'performanceConfig',\n  'additionalModelRequestFields',\n  'additionalModelResponseFieldPaths',\n];\n\nexport const bedrockOutputParser = (data: Record<string, unknown>) => {\n  const knownKeys = [...Object.keys(s.tConversationSchema.shape), 'topK', 'top_k'];\n  let result: Record<string, unknown> = {};\n\n  // Extract known fields from the root level\n  Object.entries(data).forEach(([key, value]) => {\n    if (knownKeys.includes(key)) {\n      result[key] = value;\n    }\n  });\n\n  // Extract known fields from additionalModelRequestFields\n  if (\n    typeof data.additionalModelRequestFields === 'object' &&\n    data.additionalModelRequestFields !== null\n  ) {\n    Object.entries(data.additionalModelRequestFields as Record<string, unknown>).forEach(\n      ([key, value]) => {\n        if (knownKeys.includes(key)) {\n          if (key === 'top_k') {\n            result['topK'] = value;\n          } else if (key === 'thinking' || key === 'thinkingBudget') {\n            return;\n          } else {\n            result[key] = value;\n          }\n        }\n      },\n    );\n  }\n\n  // Handle maxTokens and maxOutputTokens\n  if (result.maxTokens !== undefined && result.maxOutputTokens === undefined) {\n    result.maxOutputTokens = result.maxTokens;\n  } else if (result.maxOutputTokens !== undefined && result.maxTokens === undefined) {\n    result.maxTokens = result.maxOutputTokens;\n  }\n\n  result = configureThinking(result as AnthropicInput);\n  let amrf = result.additionalModelRequestFields as Record<string, unknown> | undefined;\n  // Reserved top-level Converse request fields; a copy inside\n  // additionalModelRequestFields makes Bedrock reject the request\n  // (\"The additional field <name> conflicts with an existing field\").\n  // Guard against non-object values, which the schema's DocumentType permits.\n  if (amrf && typeof amrf === 'object') {\n    const reserved = RESERVED_CONVERSE_FIELDS.filter((key) => key in (amrf ?? {}));\n    if (reserved.length > 0) {\n      amrf = { ...amrf };\n      for (const key of reserved) {\n        delete amrf[key];\n      }\n      result.additionalModelRequestFields = amrf;\n    }\n  }\n  if (!amrf || Object.keys(amrf).length === 0) {\n    delete result.additionalModelRequestFields;\n  }\n\n  return result;\n};\n","import type { TFile } from './files';\nimport { inputTokensIncludesCache } from '../schemas';\n\nexport enum ContentTypes {\n  TEXT = 'text',\n  THINK = 'think',\n  TEXT_DELTA = 'text_delta',\n  TOOL_CALL = 'tool_call',\n  IMAGE_FILE = 'image_file',\n  IMAGE_URL = 'image_url',\n  VIDEO_URL = 'video_url',\n  INPUT_AUDIO = 'input_audio',\n  AGENT_UPDATE = 'agent_update',\n  SUMMARY = 'summary',\n  ACTIVITY_LABEL = 'activity_label',\n  STEER = 'steer',\n  ERROR = 'error',\n}\n\nexport enum StepTypes {\n  TOOL_CALLS = 'tool_calls',\n  MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ToolCallTypes {\n  FUNCTION = 'function',\n  RETRIEVAL = 'retrieval',\n  FILE_SEARCH = 'file_search',\n  CODE_INTERPRETER = 'code_interpreter',\n  /* Agents Tool Call */\n  TOOL_CALL = 'tool_call',\n}\n\n/** Event names dispatched by the agent graph and consumed by step handlers. */\nexport enum StepEvents {\n  ON_RUN_STEP = 'on_run_step',\n  ON_AGENT_UPDATE = 'on_agent_update',\n  ON_MESSAGE_DELTA = 'on_message_delta',\n  ON_REASONING_DELTA = 'on_reasoning_delta',\n  ON_RUN_STEP_DELTA = 'on_run_step_delta',\n  ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n  /** Terminal signal for a run step: closed with a status and timestamps. */\n  ON_RUN_STEP_CLOSED = 'on_run_step_closed',\n  ON_SUMMARIZE_START = 'on_summarize_start',\n  ON_SUMMARIZE_DELTA = 'on_summarize_delta',\n  ON_SUMMARIZE_COMPLETE = 'on_summarize_complete',\n  ON_SUBAGENT_UPDATE = 'on_subagent_update',\n  ON_SANDBOX_STARTING = 'on_sandbox_starting',\n  ON_PTC_TOOL_CALL = 'on_ptc_tool_call',\n}\n\n/** Payload for {@link StepEvents.ON_SANDBOX_STARTING} — the stateful code\n * sandbox is cold-booting for the given code tool call. */\nexport type SandboxStartingEvent = {\n  tool_call_id: string;\n  runId?: string;\n};\n\n/** Lifecycle of one tool call made from inside a programmatic (PTC) program. */\nexport type PtcToolCallStatus = 'running' | 'success' | 'error';\n\n/**\n * Payload for {@link StepEvents.ON_PTC_TOOL_CALL} — one tool invocation the\n * sandbox made on behalf of a programmatic tool-calling program. Emitted twice\n * per inner call (`running`, then `success` / `error`) so the PTC card can\n * render a live trace of what the code is doing under the code itself.\n */\nexport type PtcToolCallEvent = {\n  /** The PTC run step's tool call id — the card this line belongs under. */\n  tool_call_id: string;\n  /** Stable per-program id; the settle event reuses the start event's value. */\n  call_id: string;\n  /** Inner tool id, e.g. `search_code_mcp_github`. */\n  name: string;\n  status: PtcToolCallStatus;\n  /** `key=value` preview of the call's input. Start event only. */\n  args?: string;\n  /** Truncated failure message. `error` status only. */\n  error?: string;\n  /** Wall-clock time the inner call took. Settle events only. */\n  durationMs?: number;\n  runId?: string;\n};\n\n/** Token-tracking event names streamed to the client (separate from StepEvents dispatch). */\nexport enum UsageEvents {\n  ON_CONTEXT_USAGE = 'on_context_usage',\n  ON_TOKEN_USAGE = 'on_token_usage',\n}\n\n/**\n * Human-in-the-loop event names. Streamed to live clients when a run pauses for\n * tool approval (or an ask-user question). Reconnecting clients instead read the\n * same record from `resumeState.pendingAction` on the sync event / status route.\n */\nexport enum ApprovalEvents {\n  ON_PENDING_ACTION = 'on_pending_action',\n}\n\n/**\n * Steering event names. `on_steer_applied` streams to live clients when a\n * queued steer message is injected at a tool-batch boundary; reconnecting\n * clients recover injected steers from `aggregatedContent` and still-queued\n * ones from `resumeState.pendingSteers`. Steers that never reach a boundary\n * ride the final/abort events as `pendingSteers`.\n */\nexport enum SteerEvents {\n  ON_STEER_APPLIED = 'on_steer_applied',\n  /** Durable capability correction for queued steers after HITL handover. */\n  ON_STEER_UPDATED = 'on_steer_updated',\n}\n\n/**\n * Activity-label event names. `on_activity_label` streams to live clients\n * when a tool-batch or parent-phase label part is claimed and again when the\n * fast-model label resolves; reconnecting clients recover applied labels\n * from `aggregatedContent` like any other content part.\n */\nexport enum ActivityLabelEvents {\n  ON_ACTIVITY_LABEL = 'on_activity_label',\n}\n\n/** Live title updates for an existing reasoning content part. */\nexport enum ReasoningLabelEvents {\n  ON_REASONING_LABEL = 'on_reasoning_label',\n  /** Internal durable budget reservation; clients intentionally do not render it. */\n  ON_REASONING_LABEL_ATTEMPT = 'on_reasoning_label_attempt',\n}\n\ntype TReasoningLabelEventBase = {\n  /** Completion-local content index of the reasoning part being updated. */\n  index: number;\n  stepId: string;\n  responseMessageId?: string;\n  conversationId?: string;\n};\n\n/** Payload of the `on_reasoning_label` SSE event. */\nexport type TReasoningLabelEvent = TReasoningLabelEventBase &\n  (\n    | {\n        /** Clears a snapshot title when its THINK slot changed during the resume gap. */\n        reset: true;\n        /** Step identity observed in the snapshot and exclusively eligible for this reset. */\n        previousStepId: string;\n        /** Latest run-global call-budget high-water, when present on fresh content. */\n        attempts?: number;\n      }\n    | {\n        reset?: false;\n        /** Run-unique provider-call revision; may contain gaps after unsuccessful attempts. */\n        revision: number;\n        label: string;\n        status: 'streaming' | 'complete';\n      }\n  );\n\n/** Durable run-cumulative call-budget reservation, attributed to one reasoning step. */\nexport type TReasoningLabelAttemptEvent = {\n  index: number;\n  stepId: string;\n  attempts: number;\n  submittedChars: number;\n};\n\n/** Payload of the `on_activity_label` SSE event. */\nexport type TActivityLabelEvent = {\n  /** Absolute content index the label part occupies. */\n  index: number;\n  part: {\n    type: ContentTypes.ACTIVITY_LABEL;\n    [ContentTypes.ACTIVITY_LABEL]: string;\n    /** Missing means a per-batch activity label. */\n    activity_label_type?: 'phase';\n    tool_call_ids?: string[];\n    activity_start_index?: number;\n    activity_end_index?: number;\n    activity_count?: number;\n    agent_ids?: string[];\n    counts?: {\n      searches: number;\n      reads: number;\n      writes: number;\n      commands: number;\n      other: number;\n    };\n    status?: 'ok' | 'partial' | 'failed';\n    agentId?: string;\n    pending?: boolean;\n  };\n  responseMessageId?: string;\n  conversationId?: string;\n};\n\n/** A steer message queued server-side but not yet injected into the run. */\nexport type TPendingSteer = {\n  steerId: string;\n  /** Correlates a server steer with its optimistic chip when terminal delivery\n   *  races ahead of the POST response. */\n  clientSteerId?: string;\n  text: string;\n  createdAt?: number;\n  files?: Partial<TFile>[];\n  /** Quoted excerpts steered with the message (\"Add to chat\" selections);\n   *  merged into the model-bound text at the injection boundary. */\n  quotes?: string[];\n  /** The steer asked to interrupt generation at the next safe boundary —\n   *  kept on parked/replayed chips so the \"interrupting\" label survives. */\n  preempt?: boolean;\n  /** Monotonic server revision for last-writer-wins interrupt labels. */\n  preemptRevision?: number;\n};\n\n/** Payload of the `on_steer_applied` SSE event. */\nexport type TSteerAppliedEvent = {\n  steerId: string;\n  /** Correlates the applied event with the optimistic chip before the POST settles. */\n  clientSteerId?: string;\n  /** Absolute content index the steer part was injected at. */\n  index: number;\n  part: {\n    type: ContentTypes.STEER;\n    [ContentTypes.STEER]: string;\n    steerId?: string;\n    clientSteerId?: string;\n    createdAt?: number;\n    files?: Partial<TFile>[];\n    /** Quoted excerpts steered with the message (mirrors `SteerContentPart`,\n     *  which cannot be imported here without a module cycle). */\n    quotes?: string[];\n  };\n  responseMessageId?: string;\n  conversationId?: string;\n};\n\n/** A queued steer's interrupt label changed without moving its FIFO slot. */\nexport type TSteerUpdatedEvent = {\n  conversationId: string;\n  steers: Array<{\n    steerId: string;\n    clientSteerId?: string;\n    preempt: boolean;\n    preemptRevision: number;\n  }>;\n};\n\n/** Mirrors TokenBudgetBreakdown from @librechat/agents (data-provider cannot import it). */\nexport type TTokenBudgetBreakdown = {\n  maxContextTokens: number;\n  instructionTokens: number;\n  systemMessageTokens: number;\n  dynamicInstructionTokens: number;\n  toolSchemaTokens: number;\n  summaryTokens: number;\n  toolCount: number;\n  messageCount: number;\n  messageTokens: number;\n  availableForMessages: number;\n  /** Per-tool schema token counts (post-multiplier), keyed by tool name */\n  toolTokenCounts?: Record<string, number>;\n  /** Names of counted tools that are deferred (`defer_loading`) and discovered */\n  deferredToolNames?: string[];\n  /** Calibrated retained tool traffic: tool results plus assistant turns made only of tool calls, inline provider tool results and reasoning. A subset of messageTokens, not an additional budget category. */\n  toolMessageTokens?: number;\n  /** Per-tool result-message share; excludes assistant invocation overhead. */\n  toolMessageTokenCounts?: Record<string, number>;\n};\n\n/** Per-model-call context snapshot, dispatched after pruning and before the LLM call. */\nexport type TContextUsageEvent = {\n  runId?: string;\n  agentId?: string;\n  breakdown: TTokenBudgetBreakdown;\n  /** Usable budget this call: maxContextTokens minus output reserve */\n  contextBudget?: number;\n  /** Calibrated instruction overhead actually applied this call */\n  effectiveInstructionTokens?: number;\n  /** Calibrated message tokens before pruning (excluding instructions) */\n  prePruneContextTokens?: number;\n  /** Tokens still free after instructions + pruned messages */\n  remainingContextTokens?: number;\n  calibrationRatio?: number;\n  /** Model and provider of the reconciling primary call, retained across reloads. */\n  model?: string;\n  provider?: string;\n  /** Cache portions of that call's prompt, in normalized display units. */\n  cacheRead?: number;\n  cacheWrite?: number;\n  /** Output tokens of the response's final model call (the call this pre-invoke\n   *  snapshot precedes). Saved in message metadata and used by the client so a\n   *  reloaded multi-call turn adds the same post-snapshot delta the\n   *  live finalizer did — not the full response `tokenCount`, which the snapshot\n   *  already includes for earlier steps. */\n  completedOutputTokens?: number;\n  /** Completed output in a resumable job. Separate from the saved-message field\n   * so older clients do not add it alongside their trailing-text estimate. */\n  resumedOutputTokens?: number;\n};\n\n/**\n * Per-response usage rollup persisted on `responseMessage.metadata.usage`, in\n * display units (input excludes cache; output includes repaired completion).\n * Normalized per-event on the backend before summing so a reloaded conversation\n * reproduces the live branch/total usage exactly, even for mixed-provider turns\n * (summarization/subagent calls on a different provider than the primary).\n */\nexport type TResponseUsage = {\n  input: number;\n  output: number;\n  cacheWrite: number;\n  cacheRead: number;\n  /** Authoritative USD cost; present only when `interface.contextCost` was on at save */\n  cost?: number;\n};\n\n/** Provider-reported usage for a single completed model call. */\nexport type TTokenUsageEvent = {\n  input_tokens?: number;\n  output_tokens?: number;\n  total_tokens?: number;\n  input_token_details?: {\n    cache_creation?: number;\n    cache_read?: number;\n  };\n  model?: string;\n  provider?: string;\n  /** Non-primary buckets fold into session cost/totals but not the live\n   *  context gauge: hidden sequential-agent calls (`sequential`), summary\n   *  passes (`summarization`), isolated subagent runs (`subagent`), and\n   *  fast-model activity headers (`activity-label`, `activity-phase`), and\n   *  live reasoning titles (`reasoning-label`) */\n  usage_type?:\n    | 'summarization'\n    | 'subagent'\n    | 'sequential'\n    | 'activity-label'\n    | 'activity-phase'\n    | 'reasoning-label';\n  runId?: string;\n  /** Per-run emission sequence; keeps identical payloads from distinct model calls unique */\n  seq?: number;\n  /** Authoritative USD cost of this call from the backend (premium tiers, cache\n   *  rates); present only when `interface.contextCost` is enabled. Clients sum\n   *  this rather than re-deriving cost from base rates. */\n  cost?: number;\n};\n\nconst finiteNonNegativeInteger = (value: unknown): number | undefined => {\n  if (typeof value !== 'number' || !Number.isFinite(value)) {\n    return undefined;\n  }\n  return Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.floor(value)));\n};\n\n/**\n * Full prompt token count for one completed model call — the EXACT context the\n * model saw, provider-aware: additive providers (Bedrock) report `input_tokens`\n * excluding cache, so cache reads/writes are added back; subset providers\n * (Anthropic, OpenAI, …) already fold cache into `input_tokens`. When the\n * provider is absent (custom/OpenAI-compatible payloads), fall back to the same\n * magnitude heuristic `normalizeUsageUnits` uses — cache ≤ input means it's\n * already included — so cached events aren't re-inflated. The ground truth the\n * gauge reconciles its calibrated estimate to.\n */\nexport const promptTokensFromUsage = (event: TTokenUsageEvent): number => {\n  const input = finiteNonNegativeInteger(event.input_tokens) ?? 0;\n  const details = event.input_token_details ?? {};\n  const cacheRead = finiteNonNegativeInteger(details.cache_read) ?? 0;\n  const cacheCreation = finiteNonNegativeInteger(details.cache_creation) ?? 0;\n  const includesCache =\n    event.provider != null\n      ? inputTokensIncludesCache(event.provider)\n      : cacheRead + cacheCreation <= input;\n  return includesCache\n    ? input\n    : Math.min(Number.MAX_SAFE_INTEGER, input + cacheRead + cacheCreation);\n};\n\n/**\n * Scales per-tool result-message counts while bounding both malformed input and\n * rounding error. Null-prototype records keep tool names as ordinary data keys;\n * cumulative apportionment preserves the scaled sum in one linear pass.\n */\nconst scaleToolMessageTokenCounts = (\n  value: unknown,\n  oldTotal: number,\n  newTotal: number,\n): Record<string, number> | undefined => {\n  if (value == null || typeof value !== 'object' || Array.isArray(value)) {\n    return undefined;\n  }\n  const scaled: Record<string, number> = Object.create(null);\n  let remaining = oldTotal;\n  let cumulative = 0;\n  let allocated = 0;\n  let found = false;\n  for (const [name, rawCount] of Object.entries(value)) {\n    const count = finiteNonNegativeInteger(rawCount);\n    if (count == null || count === 0) {\n      continue;\n    }\n    const bounded = Math.min(count, remaining);\n    remaining -= bounded;\n    cumulative += bounded;\n    const target = oldTotal > 0 ? Math.round((cumulative / oldTotal) * newTotal) : 0;\n    const apportioned = target - allocated;\n    allocated = target;\n    if (apportioned > 0) {\n      scaled[name] = apportioned;\n      found = true;\n    }\n  }\n  return found ? scaled : undefined;\n};\n\n/**\n * Reconciles a pre-invoke context snapshot's CALIBRATED estimate to a call's\n * ACTUAL prompt tokens. The SDK's calibration multiplier scales only\n * `messageTokens` (instructions/summary are raw tiktoken counts) and can\n * over-shoot badly when a provider injects server-side content the SDK never\n * counted (e.g. Anthropic web search) — pinning the gauge several× too high and\n * persisting it. Trust the provider's own prompt count: keep the raw\n * instruction/summary rows, set `messageTokens` to the remainder, recompute the\n * free space, and rescale the `toolMessageTokens` share to the new message\n * total. No-op when `promptTokens` is unusable.\n */\nexport const reconcileContextUsage = (\n  snapshot: TContextUsageEvent,\n  promptTokens: number,\n): TContextUsageEvent => {\n  if (!Number.isFinite(promptTokens) || promptTokens <= 0) {\n    return snapshot;\n  }\n  const normalizedPromptTokens = Math.min(Number.MAX_SAFE_INTEGER, Math.floor(promptTokens));\n  if (normalizedPromptTokens <= 0) {\n    return snapshot;\n  }\n  const { breakdown } = snapshot;\n  const instructionTokens = finiteNonNegativeInteger(breakdown.instructionTokens) ?? 0;\n  const summaryTokens = finiteNonNegativeInteger(breakdown.summaryTokens) ?? 0;\n  const budget =\n    finiteNonNegativeInteger(snapshot.contextBudget) ??\n    finiteNonNegativeInteger(breakdown.maxContextTokens);\n  const nonMessageTokens = instructionTokens + summaryTokens;\n  const messageTokens = Math.max(0, normalizedPromptTokens - nonMessageTokens);\n  /** `toolMessageTokens` is a subset of the OLD (calibrated) `messageTokens`;\n   * rescale it by the same proportion so the split tracks the provider's real\n   * total. A supplied zero remains a known-zero split; absent fields stay absent\n   * for older snapshots. */\n  const priorMessageTokens = finiteNonNegativeInteger(breakdown.messageTokens) ?? 0;\n  const priorToolMessageTokens = finiteNonNegativeInteger(breakdown.toolMessageTokens);\n  let toolMessageTokens: number | undefined;\n  if (priorToolMessageTokens != null) {\n    toolMessageTokens = 0;\n    if (priorMessageTokens > 0 && priorToolMessageTokens > 0) {\n      toolMessageTokens = Math.min(\n        messageTokens,\n        Math.round(\n          (Math.min(priorToolMessageTokens, priorMessageTokens) / priorMessageTokens) *\n            messageTokens,\n        ),\n      );\n    }\n  }\n  const toolMessageTokenCounts =\n    toolMessageTokens != null\n      ? scaleToolMessageTokenCounts(\n          breakdown.toolMessageTokenCounts,\n          Math.min(priorToolMessageTokens ?? 0, priorMessageTokens),\n          toolMessageTokens,\n        )\n      : undefined;\n\n  const nextBreakdown = {\n    ...breakdown,\n    instructionTokens,\n    summaryTokens,\n    messageTokens,\n  };\n  if (toolMessageTokens == null) {\n    delete nextBreakdown.toolMessageTokens;\n    delete nextBreakdown.toolMessageTokenCounts;\n  } else {\n    nextBreakdown.toolMessageTokens = toolMessageTokens;\n    if (toolMessageTokenCounts == null) {\n      delete nextBreakdown.toolMessageTokenCounts;\n    } else {\n      nextBreakdown.toolMessageTokenCounts = toolMessageTokenCounts;\n    }\n  }\n  const result = {\n    ...snapshot,\n    breakdown: nextBreakdown,\n  };\n  if (budget != null) {\n    result.remainingContextTokens = Math.max(0, budget - normalizedPromptTokens);\n  } else {\n    const remaining = finiteNonNegativeInteger(snapshot.remainingContextTokens);\n    if (remaining == null) {\n      delete result.remainingContextTokens;\n    } else {\n      result.remainingContextTokens = remaining;\n    }\n  }\n  return result;\n};\n\n/** Provider output, including reasoning omitted from an under-reported output count. */\nexport const outputTokensFromUsage = (event: TTokenUsageEvent): number => {\n  const output = finiteNonNegativeInteger(event.output_tokens) ?? 0;\n  const total = finiteNonNegativeInteger(event.total_tokens) ?? 0;\n  return Math.max(output, total - promptTokensFromUsage(event));\n};\n\n/** Reconcile and retain the primary call details on live, saved, and resumable snapshots. */\nexport const reconcileContextUsageFromEvent = (\n  snapshot: TContextUsageEvent,\n  event: TTokenUsageEvent,\n): TContextUsageEvent => ({\n  ...reconcileContextUsage(snapshot, promptTokensFromUsage(event)),\n  model: event.model,\n  provider: event.provider,\n  completedOutputTokens: outputTokensFromUsage(event),\n  cacheRead: finiteNonNegativeInteger(event.input_token_details?.cache_read) ?? 0,\n  cacheWrite: finiteNonNegativeInteger(event.input_token_details?.cache_creation) ?? 0,\n});\n\n/** Lifecycle phase carried on subagent-progress envelopes (mirrors SDK SubagentUpdatePhase). */\nexport type SubagentUpdatePhase =\n  | 'start'\n  | 'run_step'\n  | 'run_step_delta'\n  | 'run_step_completed'\n  | 'run_step_closed'\n  | 'message_delta'\n  | 'reasoning_delta'\n  | 'stop'\n  | 'error';\n\n/** Structured root-to-leaf identity for one nested subagent execution. */\nexport interface SubagentAncestryEntry {\n  readonly subagentRunId: string;\n  readonly subagentType: string;\n  readonly subagentKind: 'agent' | 'graph';\n  /** Execution subject ID; synthetic for graph subagents. */\n  readonly subagentAgentId: string;\n  readonly parentRunId: string;\n  readonly parentAgentId?: string;\n  readonly parentToolCallId?: string;\n}\n\nexport type SubagentIdentity = Pick<SubagentAncestryEntry, 'subagentKind' | 'subagentAgentId'>;\n\n/** Single streamed subagent update forwarded by the SDK's SubagentExecutor. */\nexport interface SubagentUpdateEvent {\n  runId: string;\n  parentRunId?: string;\n  subagentRunId: string;\n  /** Host-assigned identity preserved when one detached update overlaps delivery streams. */\n  activityEventId?: string;\n  /** Host-assigned monotonic sequence within one detached child run. */\n  activitySequence?: number;\n  /** Parent-side `tool_call_id` for the `subagent` tool invocation that\n   *  triggered this run. Surfaces from the SDK (`3.1.67-dev.2`+) so hosts\n   *  can correlate child progress to the parent tool call deterministically. */\n  parentToolCallId?: string;\n  subagentType: string;\n  subagentKind?: 'agent' | 'graph';\n  /** Execution subject ID; synthetic for graph subagents. */\n  subagentAgentId: string;\n  memberAgentId?: string;\n  depth?: number;\n  ancestry?: readonly SubagentAncestryEntry[];\n  parentAgentId?: string;\n  phase: SubagentUpdatePhase;\n  data?: unknown;\n  label?: string;\n  timestamp: string;\n}\n","import dayjs from 'dayjs';\nimport utc from 'dayjs/plugin/utc.js';\nimport timezonePlugin from 'dayjs/plugin/timezone.js';\nimport type { ZodIssue } from 'zod';\nimport type * as a from './types/assistants';\nimport type * as s from './schemas';\nimport type * as t from './types';\nimport {\n  openAISchema,\n  openRouterSchema,\n  googleSchema,\n  EModelEndpoint,\n  Providers,\n  anthropicSchema,\n  assistantSchema,\n  // agentsSchema,\n  compactAgentsSchema,\n  compactGoogleSchema,\n  compactAssistantSchema,\n} from './schemas';\nimport { bedrockInputSchema } from './bedrock';\nimport { ContentTypes } from './types/runs';\nimport { alternateName } from './config';\n\ndayjs.extend(utc);\ndayjs.extend(timezonePlugin);\n\ntype EndpointSchema =\n  | typeof openAISchema\n  | typeof openRouterSchema\n  | typeof googleSchema\n  | typeof anthropicSchema\n  | typeof assistantSchema\n  | typeof compactAgentsSchema\n  | typeof bedrockInputSchema;\n\nexport type EndpointSchemaKey = EModelEndpoint;\ntype EndpointSchemaLookupKey = EModelEndpoint | Providers.OPENROUTER;\n\nconst endpointSchemas: Record<EndpointSchemaLookupKey, EndpointSchema> = {\n  [EModelEndpoint.openAI]: openAISchema,\n  [EModelEndpoint.azureOpenAI]: openAISchema,\n  [EModelEndpoint.custom]: openAISchema,\n  [Providers.OPENROUTER]: openRouterSchema,\n  [EModelEndpoint.google]: googleSchema,\n  [EModelEndpoint.anthropic]: anthropicSchema,\n  [EModelEndpoint.assistants]: assistantSchema,\n  [EModelEndpoint.azureAssistants]: assistantSchema,\n  [EModelEndpoint.agents]: compactAgentsSchema,\n  [EModelEndpoint.bedrock]: bedrockInputSchema,\n};\n\nconst isEndpointSchemaLookupKey = (value?: string | null): value is EndpointSchemaLookupKey =>\n  value != null && Object.prototype.hasOwnProperty.call(endpointSchemas, value);\n\nconst getFallbackEndpointSchema = <TSchema>(\n  schemas: Record<EndpointSchemaLookupKey, TSchema>,\n  endpointType?: EndpointSchemaKey | null,\n  defaultParamsEndpoint?: string | null,\n): TSchema | undefined => {\n  if (!endpointType) {\n    return undefined;\n  }\n\n  const overrideSchema = isEndpointSchemaLookupKey(defaultParamsEndpoint)\n    ? schemas[defaultParamsEndpoint]\n    : undefined;\n  return overrideSchema ?? schemas[endpointType];\n};\n\n// const schemaCreators: Record<EModelEndpoint, (customSchema: DefaultSchemaValues) => EndpointSchema> = {\n//   [EModelEndpoint.google]: createGoogleSchema,\n// };\n\n/** Get the enabled endpoints from the `ENDPOINTS` environment variable */\nexport function getEnabledEndpoints() {\n  const defaultEndpoints: string[] = [\n    EModelEndpoint.openAI,\n    EModelEndpoint.agents,\n    EModelEndpoint.assistants,\n    EModelEndpoint.azureAssistants,\n    EModelEndpoint.azureOpenAI,\n    EModelEndpoint.google,\n    EModelEndpoint.anthropic,\n    EModelEndpoint.bedrock,\n  ];\n\n  const endpointsEnv = process.env.ENDPOINTS ?? '';\n  let enabledEndpoints = defaultEndpoints;\n  if (endpointsEnv) {\n    enabledEndpoints = endpointsEnv\n      .split(',')\n      .filter((endpoint) => endpoint.trim())\n      .map((endpoint) => endpoint.trim());\n  }\n  return enabledEndpoints;\n}\n\n/** Orders an existing EndpointsConfig object based on enabled endpoint/custom ordering */\nexport function orderEndpointsConfig(endpointsConfig: t.TEndpointsConfig) {\n  if (!endpointsConfig) {\n    return {};\n  }\n  const enabledEndpoints = getEnabledEndpoints();\n  const endpointKeys = Object.keys(endpointsConfig);\n  const defaultCustomIndex = enabledEndpoints.indexOf(EModelEndpoint.custom);\n  return endpointKeys.reduce(\n    (accumulatedConfig: Record<string, t.TConfig | null | undefined>, currentEndpointKey) => {\n      const isCustom = !(currentEndpointKey in EModelEndpoint);\n      const isEnabled = enabledEndpoints.includes(currentEndpointKey);\n      if (!isEnabled && !isCustom) {\n        return accumulatedConfig;\n      }\n\n      const index = enabledEndpoints.indexOf(currentEndpointKey);\n\n      if (isCustom) {\n        accumulatedConfig[currentEndpointKey] = {\n          order: defaultCustomIndex >= 0 ? defaultCustomIndex : 9999,\n          ...(endpointsConfig[currentEndpointKey] as Omit<t.TConfig, 'order'> & { order?: number }),\n        };\n      } else if (endpointsConfig[currentEndpointKey]) {\n        accumulatedConfig[currentEndpointKey] = {\n          ...endpointsConfig[currentEndpointKey],\n          order: index,\n        };\n      }\n      return accumulatedConfig;\n    },\n    {},\n  );\n}\n\n/** Converts an array of Zod issues into a string. */\nexport function errorsToString(errors: ZodIssue[]) {\n  return errors\n    .map((error) => {\n      const field = error.path.join('.');\n      const message = error.message;\n\n      return `${field}: ${message}`;\n    })\n    .join(' ');\n}\n\nexport function getFirstDefinedValue(possibleValues: string[]) {\n  let returnValue;\n  for (const value of possibleValues) {\n    if (value) {\n      returnValue = value;\n      break;\n    }\n  }\n  return returnValue;\n}\n\nexport function getNonEmptyValue(possibleValues: string[]) {\n  for (const value of possibleValues) {\n    if (value && value.trim() !== '') {\n      return value;\n    }\n  }\n  return undefined;\n}\n\nexport type TPossibleValues = {\n  models: string[];\n};\n\nexport const parseConvo = ({\n  endpoint,\n  endpointType,\n  conversation,\n  possibleValues,\n  defaultParamsEndpoint,\n}: {\n  endpoint: EndpointSchemaKey;\n  endpointType?: EndpointSchemaKey | null;\n  conversation: Partial<s.TConversation | s.TPreset> | null;\n  possibleValues?: TPossibleValues;\n  defaultParamsEndpoint?: string | null;\n}) => {\n  const primarySchema = endpointSchemas[endpoint] as EndpointSchema | undefined;\n\n  if (!primarySchema && !endpointType) {\n    throw new Error(`Unknown endpoint: ${endpoint}`);\n  }\n\n  const schema =\n    primarySchema ??\n    getFallbackEndpointSchema(endpointSchemas, endpointType, defaultParamsEndpoint);\n  const convo = schema?.parse(conversation) as s.TConversation | undefined;\n  const { models } = possibleValues ?? {};\n\n  if (models && convo) {\n    convo.model = getFirstDefinedValue(models) ?? convo.model;\n  }\n\n  return convo;\n};\n\n/** Match GPT followed by digit, optional decimal, and optional suffix\n *\n * Examples: gpt-4, gpt-4o, gpt-4.5, gpt-5a, etc. */\nconst extractGPTVersion = (modelStr: string): string => {\n  const gptMatch = modelStr.match(/gpt-(\\d+(?:\\.\\d+)?)([a-z])?/i);\n  if (gptMatch) {\n    const version = gptMatch[1];\n    const suffix = gptMatch[2] || '';\n    return `GPT-${version}${suffix}`;\n  }\n  return '';\n};\n\n/** Match omni models (o1, o3, etc.), \"o\" followed by a digit, possibly with decimal */\nconst extractOmniVersion = (modelStr: string): string => {\n  const omniMatch = modelStr.match(/\\bo(\\d+(?:\\.\\d+)?)\\b/i);\n  if (omniMatch) {\n    const version = omniMatch[1];\n    return `o${version}`;\n  }\n  return '';\n};\n\nexport const getResponseSender = (endpointOption: Partial<t.TEndpointOption>): string => {\n  const {\n    model: _m,\n    endpoint: _e,\n    endpointType,\n    modelDisplayLabel: _mdl,\n    chatGptLabel: _cgl,\n    modelLabel: _ml,\n  } = endpointOption;\n\n  const endpoint = _e as EModelEndpoint;\n\n  const model = _m ?? '';\n  const modelDisplayLabel = _mdl ?? '';\n  const chatGptLabel = _cgl ?? '';\n  const modelLabel = _ml ?? '';\n  if (\n    [EModelEndpoint.openAI, EModelEndpoint.bedrock, EModelEndpoint.azureOpenAI].includes(endpoint)\n  ) {\n    if (modelLabel) {\n      return modelLabel;\n    } else if (chatGptLabel) {\n      // @deprecated - prefer modelLabel\n      return chatGptLabel;\n    } else if (model && extractOmniVersion(model)) {\n      return extractOmniVersion(model);\n    } else if (model && (model.includes('mistral') || model.includes('codestral'))) {\n      return 'Mistral';\n    } else if (model && model.includes('deepseek')) {\n      return 'Deepseek';\n    } else if (model && model.includes('kimi')) {\n      return 'Kimi';\n    } else if (model && model.includes('moonshot')) {\n      return 'Moonshot';\n    } else if (model && model.includes('gpt-')) {\n      const gptVersion = extractGPTVersion(model);\n      return gptVersion || 'GPT';\n    }\n    return (alternateName[endpoint] as string | undefined) ?? 'AI';\n  }\n\n  if (endpoint === EModelEndpoint.anthropic) {\n    return modelLabel || 'Claude';\n  }\n\n  if (endpoint === EModelEndpoint.bedrock) {\n    return modelLabel || alternateName[endpoint];\n  }\n\n  if (endpoint === EModelEndpoint.google) {\n    if (modelLabel) {\n      return modelLabel;\n    } else if (model?.toLowerCase().includes('gemma') === true) {\n      return 'Gemma';\n    }\n\n    return 'Gemini';\n  }\n\n  if (endpoint === EModelEndpoint.custom || endpointType === EModelEndpoint.custom) {\n    if (modelLabel) {\n      return modelLabel;\n    } else if (chatGptLabel) {\n      // @deprecated - prefer modelLabel\n      return chatGptLabel;\n    } else if (model && extractOmniVersion(model)) {\n      return extractOmniVersion(model);\n    } else if (model && (model.includes('mistral') || model.includes('codestral'))) {\n      return 'Mistral';\n    } else if (model && model.includes('deepseek')) {\n      return 'Deepseek';\n    } else if (model && model.includes('kimi')) {\n      return 'Kimi';\n    } else if (model && model.includes('moonshot')) {\n      return 'Moonshot';\n    } else if (model && model.includes('gpt-')) {\n      const gptVersion = extractGPTVersion(model);\n      return gptVersion || 'GPT';\n    } else if (modelDisplayLabel) {\n      return modelDisplayLabel;\n    }\n\n    return 'AI';\n  }\n\n  return '';\n};\n\ntype CompactEndpointSchema =\n  | typeof openAISchema\n  | typeof compactAssistantSchema\n  | typeof compactAgentsSchema\n  | typeof compactGoogleSchema\n  | typeof openRouterSchema\n  | typeof anthropicSchema\n  | typeof bedrockInputSchema;\n\nconst compactEndpointSchemas: Record<EndpointSchemaLookupKey, CompactEndpointSchema> = {\n  [EModelEndpoint.openAI]: openAISchema,\n  [EModelEndpoint.azureOpenAI]: openAISchema,\n  [EModelEndpoint.custom]: openAISchema,\n  [Providers.OPENROUTER]: openRouterSchema,\n  [EModelEndpoint.assistants]: compactAssistantSchema,\n  [EModelEndpoint.azureAssistants]: compactAssistantSchema,\n  [EModelEndpoint.agents]: compactAgentsSchema,\n  [EModelEndpoint.google]: compactGoogleSchema,\n  [EModelEndpoint.bedrock]: bedrockInputSchema,\n  [EModelEndpoint.anthropic]: anthropicSchema,\n};\n\nexport const parseCompactConvo = ({\n  endpoint,\n  endpointType,\n  conversation,\n  possibleValues,\n  defaultParamsEndpoint,\n}: {\n  endpoint?: EndpointSchemaKey;\n  endpointType?: EndpointSchemaKey | null;\n  conversation: Partial<s.TConversation | s.TPreset>;\n  possibleValues?: TPossibleValues;\n  defaultParamsEndpoint?: string | null;\n}): Omit<s.TConversation, 'iconURL'> | null => {\n  if (!endpoint) {\n    throw new Error(`undefined endpoint: ${endpoint}`);\n  }\n\n  const primarySchema = compactEndpointSchemas[endpoint] as CompactEndpointSchema | undefined;\n\n  if (!primarySchema && !endpointType) {\n    throw new Error(`Unknown endpoint: ${endpoint}`);\n  }\n\n  const schema =\n    primarySchema ??\n    getFallbackEndpointSchema(compactEndpointSchemas, endpointType, defaultParamsEndpoint);\n\n  if (!schema) {\n    throw new Error(`Unknown endpointType: ${endpointType}`);\n  }\n\n  // Strip iconURL from input before parsing - it should only be derived server-side\n  // from model spec configuration, not accepted from client requests\n  const { iconURL: _clientIconURL, ...conversationWithoutIconURL } = conversation;\n\n  const convo = schema.parse(conversationWithoutIconURL) as s.TConversation | null;\n  const { models } = possibleValues ?? {};\n\n  if (models && convo) {\n    convo.model = getFirstDefinedValue(models) ?? convo.model;\n  }\n\n  return convo;\n};\n\nexport function parseTextParts(\n  contentParts: Array<a.TMessageContentParts | undefined>,\n  skipReasoning: boolean = false,\n  options?: { includeSteer?: boolean },\n): string {\n  let result = '';\n  const append = (textValue: string) => {\n    if (\n      result.length > 0 &&\n      textValue.length > 0 &&\n      result[result.length - 1] !== ' ' &&\n      textValue[0] !== ' '\n    ) {\n      result += ' ';\n    }\n    result += textValue;\n  };\n\n  for (const part of contentParts) {\n    if (!part?.type) {\n      continue;\n    }\n    if (part.type === ContentTypes.TEXT) {\n      append((typeof part.text === 'string' ? part.text : part.text?.value) || '');\n    } else if (part.type === ContentTypes.STEER && options?.includeSteer === true) {\n      /** Mid-run user speech: excluded by default so generic extraction (TTS\n       *  reading assistant output) never speaks the user's own words — the\n       *  full-record surfaces (search indexing, persisted abort text) opt in. */\n      append(typeof part.steer === 'string' ? part.steer : '');\n    } else if (part.type === ContentTypes.THINK && !skipReasoning) {\n      append(typeof part.think === 'string' ? part.think : '');\n    }\n  }\n\n  return result;\n}\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport function findLastSeparatorIndex(text: string, separators = SEPARATORS): number {\n  let lastIndex = -1;\n  for (const separator of separators) {\n    const index = text.lastIndexOf(separator);\n    if (index > lastIndex) {\n      lastIndex = index;\n    }\n  }\n  return lastIndex;\n}\n\n/**\n * Anchors a dayjs instant to the user's IANA timezone when one is supplied,\n * so local-time special vars reflect the user's wall clock rather than the\n * server's. Falls back to the original instant for missing or invalid zones.\n */\nfunction applyTimezone(value: dayjs.Dayjs, timezone?: string): dayjs.Dayjs {\n  if (!timezone) {\n    return value;\n  }\n  try {\n    const zoned = value.tz(timezone);\n    return zoned.isValid() ? zoned : value;\n  } catch {\n    return value;\n  }\n}\n\nexport function replaceSpecialVars({\n  text,\n  user,\n  now: inputNow,\n  timezone,\n}: {\n  text: string;\n  user?: t.TUser | null;\n  now?: string | number | Date;\n  timezone?: string;\n}) {\n  let result = text;\n  if (!result) {\n    return result;\n  }\n\n  const now = applyTimezone(inputNow != null ? dayjs(inputNow) : dayjs(), timezone);\n  const weekdayName = now.format('dddd');\n\n  const currentDate = now.format('YYYY-MM-DD');\n  result = result.replace(/{{\\s*current_date\\s*}}/gi, `${currentDate} (${weekdayName})`);\n\n  const currentDatetime = now.format('YYYY-MM-DD HH:mm:ss Z');\n  result = result.replace(/{{\\s*current_datetime\\s*}}/gi, `${currentDatetime} (${weekdayName})`);\n\n  const isoDatetime = now.toISOString();\n  result = result.replace(/{{\\s*iso_datetime\\s*}}/gi, isoDatetime);\n\n  if (user && user.name) {\n    result = result.replace(/{{\\s*current_user\\s*}}/gi, user.name);\n  }\n\n  return result;\n}\n\n/**\n * Parsed ephemeral agent ID result\n */\nexport type ParsedEphemeralAgentId = {\n  endpoint: string;\n  model: string;\n  sender?: string;\n  index?: number;\n};\n\n/**\n * Resolves the display label (\"sender\") for an ephemeral agent:\n * `modelLabel` (user/preset) → model spec's `label` → endpoint config's\n * `modelDisplayLabel` → `''` (lets consumers fall back to the model name).\n */\nexport function getEphemeralSender({\n  modelLabel,\n  specLabel,\n  modelDisplayLabel,\n}: {\n  modelLabel?: string | null;\n  specLabel?: string | null;\n  modelDisplayLabel?: string | null;\n}): string {\n  return modelLabel ?? specLabel ?? modelDisplayLabel ?? '';\n}\n\n/**\n * Encodes an ephemeral agent ID from endpoint, model, optional sender, and optional index.\n * Uses __ to replace : (reserved in graph node names) and ___ to separate sender.\n *\n * Format: endpoint__model___sender or endpoint__model___sender____index (if index provided)\n *\n * @example\n * encodeEphemeralAgentId({ endpoint: 'openAI', model: 'gpt-4o', sender: 'GPT-4o' })\n * // => 'openAI__gpt-4o___GPT-4o'\n *\n * @example\n * encodeEphemeralAgentId({ endpoint: 'openAI', model: 'gpt-4o', sender: 'GPT-4o', index: 1 })\n * // => 'openAI__gpt-4o___GPT-4o____1'\n */\nexport function encodeEphemeralAgentId({\n  endpoint,\n  model,\n  sender,\n  index,\n}: {\n  endpoint: string;\n  model: string;\n  sender?: string;\n  index?: number;\n}): string {\n  const base = `${endpoint}:${model}`.replace(/:/g, '__');\n  let result = base;\n  if (sender) {\n    // Use ___ as separator before sender to distinguish from __ in model names\n    result = `${base}___${sender.replace(/:/g, '__')}`;\n  }\n  if (index != null) {\n    // Use ____ (4 underscores) as separator for index\n    result = `${result}____${index}`;\n  }\n  return result;\n}\n\n/**\n * Parses an ephemeral agent ID back into its components.\n * Returns undefined if the ID doesn't match the expected format.\n *\n * Format: endpoint__model___sender or endpoint__model___sender____index\n * - ____ (4 underscores) separates optional index suffix\n * - ___ (triple underscore) separates model from optional sender\n * - __ (double underscore) replaces : in endpoint/model names\n *\n * @example\n * parseEphemeralAgentId('openAI__gpt-4o___GPT-4o')\n * // => { endpoint: 'openAI', model: 'gpt-4o', sender: 'GPT-4o' }\n *\n * @example\n * parseEphemeralAgentId('openAI__gpt-4o___GPT-4o____1')\n * // => { endpoint: 'openAI', model: 'gpt-4o', sender: 'GPT-4o', index: 1 }\n */\nexport function parseEphemeralAgentId(agentId: string): ParsedEphemeralAgentId | undefined {\n  if (!agentId.includes('__')) {\n    return undefined;\n  }\n\n  // First check for index suffix (separated by ____)\n  let index: number | undefined;\n  let workingId = agentId;\n  if (agentId.includes('____')) {\n    const lastIndexSep = agentId.lastIndexOf('____');\n    const indexStr = agentId.slice(lastIndexSep + 4);\n    const parsedIndex = parseInt(indexStr, 10);\n    if (!isNaN(parsedIndex)) {\n      index = parsedIndex;\n      workingId = agentId.slice(0, lastIndexSep);\n    }\n  }\n\n  // Check for sender (separated by ___)\n  let sender: string | undefined;\n  let mainPart = workingId;\n  if (workingId.includes('___')) {\n    const [before, after] = workingId.split('___');\n    mainPart = before;\n    // Restore colons in sender if any\n    sender = after?.replace(/__/g, ':');\n  }\n\n  const [endpoint, ...modelParts] = mainPart.split('__');\n  if (!endpoint || modelParts.length === 0) {\n    return undefined;\n  }\n  // Restore colons in model name (model names can contain colons like claude-3:opus)\n  const model = modelParts.join(':');\n  return { endpoint, model, sender, index };\n}\n\n/**\n * Checks if an agent ID represents an ephemeral (non-saved) agent.\n * Real agent IDs always start with \"agent_\", so anything else is ephemeral.\n */\nexport function isEphemeralAgentId(agentId: string | null | undefined): boolean {\n  return !agentId?.startsWith('agent_');\n}\n\n/**\n * Strips the index suffix (____N) from an agent ID if present.\n * Works with both ephemeral and real agent IDs.\n *\n * @example\n * stripAgentIdSuffix('agent_abc123____1') // => 'agent_abc123'\n * stripAgentIdSuffix('openAI__gpt-4o___GPT-4o____1') // => 'openAI__gpt-4o___GPT-4o'\n * stripAgentIdSuffix('agent_abc123') // => 'agent_abc123' (unchanged)\n */\nexport function stripAgentIdSuffix(agentId: string): string {\n  return agentId.replace(/____\\d+$/, '');\n}\n\n/**\n * Appends an index suffix (____N) to an agent ID.\n * Used to distinguish parallel agents with the same base ID.\n *\n * @example\n * appendAgentIdSuffix('agent_abc123', 1) // => 'agent_abc123____1'\n * appendAgentIdSuffix('openAI__gpt-4o___GPT-4o', 1) // => 'openAI__gpt-4o___GPT-4o____1'\n */\nexport function appendAgentIdSuffix(agentId: string, index: number): string {\n  return `${agentId}____${index}`;\n}\n","import type { ZodError } from 'zod';\nimport type {\n  TAzureGroups,\n  TAzureGroupMap,\n  TAzureModelGroupMap,\n  TValidatedAzureConfig,\n  TAzureConfigValidationResult,\n} from '../src/config';\nimport { extractEnvVariable, envVarRegex } from '../src/utils';\nimport { azureGroupConfigsSchema } from '../src/config';\nimport { errorsToString } from '../src/parsers';\n\nexport function validateAzureGroups(configs: TAzureGroups): TAzureConfigValidationResult {\n  let isValid = true;\n  const modelNames: string[] = [];\n  const modelGroupMap: TAzureModelGroupMap = {};\n  const groupMap: TAzureGroupMap = {};\n  const errors: (ZodError | string)[] = [];\n\n  const result = azureGroupConfigsSchema.safeParse(configs);\n  if (!result.success) {\n    isValid = false;\n    errors.push(errorsToString(result.error.errors));\n  } else {\n    for (const group of result.data) {\n      const {\n        group: groupName,\n        apiKey,\n        instanceName = '',\n        deploymentName = '',\n        version = '',\n        baseURL = '',\n        additionalHeaders,\n        models,\n        serverless = false,\n        ...rest\n      } = group;\n\n      if (groupMap[groupName]) {\n        errors.push(`Duplicate group name detected: \"${groupName}\". Group names must be unique.`);\n        return { isValid: false, modelNames, modelGroupMap, groupMap, errors };\n      }\n\n      if (serverless && !baseURL) {\n        errors.push(`Group \"${groupName}\" is serverless but missing mandatory \"baseURL.\"`);\n        return { isValid: false, modelNames, modelGroupMap, groupMap, errors };\n      }\n\n      if (!instanceName && !serverless) {\n        errors.push(\n          `Group \"${groupName}\" is missing an \"instanceName\" for non-serverless configuration.`,\n        );\n        return { isValid: false, modelNames, modelGroupMap, groupMap, errors };\n      }\n\n      groupMap[groupName] = {\n        apiKey,\n        instanceName,\n        deploymentName,\n        version,\n        baseURL,\n        additionalHeaders,\n        models,\n        serverless,\n        ...rest,\n      };\n\n      for (const modelName in group.models) {\n        modelNames.push(modelName);\n        const model = group.models[modelName];\n\n        if (modelGroupMap[modelName]) {\n          errors.push(\n            `Duplicate model name detected: \"${modelName}\". Model names must be unique across groups.`,\n          );\n          return { isValid: false, modelNames, modelGroupMap, groupMap, errors };\n        }\n\n        if (serverless) {\n          modelGroupMap[modelName] = {\n            group: groupName,\n          };\n          continue;\n        }\n\n        const groupDeploymentName = group.deploymentName ?? '';\n        const groupVersion = group.version ?? '';\n        if (typeof model === 'boolean') {\n          // For boolean models, check if group-level deploymentName and version are present.\n          if (!groupDeploymentName || !groupVersion) {\n            errors.push(\n              `Model \"${modelName}\" in group \"${groupName}\" is missing a deploymentName or version.`,\n            );\n            return { isValid: false, modelNames, modelGroupMap, groupMap, errors };\n          }\n\n          modelGroupMap[modelName] = {\n            group: groupName,\n          };\n        } else {\n          const modelDeploymentName = model.deploymentName ?? '';\n          const modelVersion = model.version ?? '';\n          // For object models, check if deploymentName and version are required but missing.\n          if ((!modelDeploymentName && !groupDeploymentName) || (!modelVersion && !groupVersion)) {\n            errors.push(\n              `Model \"${modelName}\" in group \"${groupName}\" is missing a required deploymentName or version.`,\n            );\n            return { isValid: false, modelNames, modelGroupMap, groupMap, errors };\n          }\n\n          modelGroupMap[modelName] = {\n            group: groupName,\n            // deploymentName: modelDeploymentName || groupDeploymentName,\n            // version: modelVersion || groupVersion,\n          };\n        }\n      }\n    }\n  }\n\n  return { isValid, modelNames, modelGroupMap, groupMap, errors };\n}\n\ntype AzureOptions = {\n  azureOpenAIApiKey: string;\n  azureOpenAIApiInstanceName?: string;\n  azureOpenAIApiDeploymentName?: string;\n  azureOpenAIApiVersion?: string;\n};\n\ntype MappedAzureConfig = {\n  azureOptions: AzureOptions;\n  baseURL?: string;\n  headers?: Record<string, string>;\n  serverless?: boolean;\n};\n\nexport function mapModelToAzureConfig({\n  modelName,\n  modelGroupMap,\n  groupMap,\n}: Omit<TValidatedAzureConfig, 'modelNames'> & {\n  modelName: string;\n}): MappedAzureConfig {\n  const modelConfig = modelGroupMap[modelName];\n  if (!modelConfig) {\n    throw new Error(`Model named \"${modelName}\" not found in configuration.`);\n  }\n\n  const groupConfig = groupMap[modelConfig.group];\n  if (!groupConfig) {\n    throw new Error(\n      `Group \"${modelConfig.group}\" for model \"${modelName}\" not found in configuration.`,\n    );\n  }\n\n  const instanceName = groupConfig.instanceName ?? '';\n\n  if (!instanceName && groupConfig.serverless !== true) {\n    throw new Error(\n      `Group \"${modelConfig.group}\" is missing an instanceName for non-serverless configuration.`,\n    );\n  }\n\n  const baseURL = groupConfig.baseURL ?? '';\n  if (groupConfig.serverless === true && !baseURL) {\n    throw new Error(\n      `Group \"${modelConfig.group}\" is missing the required base URL for serverless configuration.`,\n    );\n  }\n\n  if (groupConfig.serverless === true) {\n    const result: MappedAzureConfig = {\n      azureOptions: {\n        azureOpenAIApiVersion: extractEnvVariable(groupConfig.version ?? ''),\n        azureOpenAIApiKey: extractEnvVariable(groupConfig.apiKey),\n      },\n      baseURL: extractEnvVariable(baseURL),\n      serverless: true,\n    };\n\n    const apiKeyValue = result.azureOptions.azureOpenAIApiKey;\n    if (typeof apiKeyValue === 'string' && envVarRegex.test(apiKeyValue)) {\n      throw new Error(`Azure configuration environment variable \"${apiKeyValue}\" was not found.`);\n    }\n\n    if (groupConfig.additionalHeaders) {\n      result.headers = groupConfig.additionalHeaders;\n    }\n\n    return result;\n  }\n\n  if (!instanceName) {\n    throw new Error(\n      `Group \"${modelConfig.group}\" is missing an instanceName for non-serverless configuration.`,\n    );\n  }\n\n  const modelDetails = groupConfig.models[modelName];\n  const { deploymentName = '', version = '' } =\n    typeof modelDetails === 'object'\n      ? {\n          deploymentName: modelDetails.deploymentName ?? groupConfig.deploymentName,\n          version: modelDetails.version ?? groupConfig.version,\n        }\n      : {\n          deploymentName: groupConfig.deploymentName,\n          version: groupConfig.version,\n        };\n\n  if (!deploymentName || !version) {\n    throw new Error(\n      `Model \"${modelName}\" in group \"${modelConfig.group}\" is missing a deploymentName (\"${deploymentName}\") or version (\"${version}\").`,\n    );\n  }\n\n  const azureOptions: AzureOptions = {\n    azureOpenAIApiKey: extractEnvVariable(groupConfig.apiKey),\n    azureOpenAIApiInstanceName: extractEnvVariable(instanceName),\n    azureOpenAIApiDeploymentName: extractEnvVariable(deploymentName),\n    azureOpenAIApiVersion: extractEnvVariable(version),\n  };\n\n  for (const value of Object.values(azureOptions)) {\n    if (typeof value === 'string' && envVarRegex.test(value)) {\n      throw new Error(`Azure configuration environment variable \"${value}\" was not found.`);\n    }\n  }\n\n  const result: MappedAzureConfig = { azureOptions };\n\n  if (baseURL) {\n    result.baseURL = extractEnvVariable(baseURL);\n  }\n\n  if (groupConfig.additionalHeaders) {\n    result.headers = groupConfig.additionalHeaders;\n  }\n\n  return result;\n}\n\nexport function mapGroupToAzureConfig({\n  groupName,\n  groupMap,\n}: {\n  groupName: string;\n  groupMap: TAzureGroupMap;\n}): MappedAzureConfig {\n  const groupConfig = groupMap[groupName];\n  if (!groupConfig) {\n    throw new Error(`Group named \"${groupName}\" not found in configuration.`);\n  }\n\n  const instanceName = groupConfig.instanceName ?? '';\n  const serverless = groupConfig.serverless ?? false;\n  const baseURL = groupConfig.baseURL ?? '';\n\n  if (!instanceName && !serverless) {\n    throw new Error(\n      `Group \"${groupName}\" is missing an instanceName for non-serverless configuration.`,\n    );\n  }\n\n  if (serverless && !baseURL) {\n    throw new Error(\n      `Group \"${groupName}\" is missing the required base URL for serverless configuration.`,\n    );\n  }\n\n  const models = Object.keys(groupConfig.models);\n  if (models.length === 0) {\n    throw new Error(`Group \"${groupName}\" does not have any models configured.`);\n  }\n\n  // Use the first available model in the group\n  const firstModelName = models[0];\n  const modelDetails = groupConfig.models[firstModelName];\n\n  const azureOptions: AzureOptions = {\n    azureOpenAIApiVersion: extractEnvVariable(groupConfig.version ?? ''),\n    azureOpenAIApiKey: extractEnvVariable(groupConfig.apiKey),\n    azureOpenAIApiInstanceName: extractEnvVariable(instanceName),\n    // DeploymentName and Version set below\n  };\n\n  if (serverless) {\n    return {\n      azureOptions,\n      baseURL: extractEnvVariable(baseURL),\n      serverless: true,\n      ...(groupConfig.additionalHeaders && { headers: groupConfig.additionalHeaders }),\n    };\n  }\n\n  const { deploymentName = '', version = '' } =\n    typeof modelDetails === 'object'\n      ? {\n          deploymentName: modelDetails.deploymentName ?? groupConfig.deploymentName,\n          version: modelDetails.version ?? groupConfig.version,\n        }\n      : {\n          deploymentName: groupConfig.deploymentName,\n          version: groupConfig.version,\n        };\n\n  if (!deploymentName || !version) {\n    throw new Error(\n      `Model \"${firstModelName}\" in group \"${groupName}\" or the group itself is missing a deploymentName (\"${deploymentName}\") or version (\"${version}\").`,\n    );\n  }\n\n  azureOptions.azureOpenAIApiDeploymentName = extractEnvVariable(deploymentName);\n  azureOptions.azureOpenAIApiVersion = extractEnvVariable(version);\n\n  const result: MappedAzureConfig = { azureOptions };\n\n  if (baseURL) {\n    result.baseURL = extractEnvVariable(baseURL);\n  }\n\n  if (groupConfig.additionalHeaders) {\n    result.headers = groupConfig.additionalHeaders;\n  }\n\n  return result;\n}\n","/**\n * LangChain classifies a provider failure by mutating the error: it stamps `lc_error_code` and\n * appends `\\n\\nTroubleshooting URL: <docs url>\\n` to the message. Both halves are handled here\n * because the server strips the URL before persisting the message, while the client still reads the\n * code back out of messages persisted before it did.\n */\nconst LANGCHAIN = 'langchain';\nconst ERROR_PATH = '/errors/';\nconst TROUBLESHOOTING_LABEL = 'Troubleshooting URL:';\nconst WHITESPACE = /\\s/;\n\n/** Provider errors cross untyped boundaries, so a `message` is not guaranteed to be a string. */\nfunction toMessageText(message: unknown): string {\n  if (typeof message === 'string') {\n    return message;\n  }\n  return message == null ? '' : String(message);\n}\n\nfunction isErrorCodeCharacter(character: string): boolean {\n  const code = character.charCodeAt(0);\n  return character === '_' || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n}\n\nfunction findTokenEnd(text: string, start: number, limit = text.length): number {\n  let end = start;\n  while (end < limit && !WHITESPACE.test(text[end])) {\n    end += 1;\n  }\n  return end;\n}\n\nfunction findErrorCode(\n  text: string,\n  searchableText: string,\n  start: number,\n  end: number,\n): { start: number; end: number } | undefined {\n  const langChainIndex = searchableText.indexOf(LANGCHAIN, start);\n  if (langChainIndex < 0 || langChainIndex >= end) {\n    return undefined;\n  }\n\n  let errorCode: { start: number; end: number } | undefined;\n  let pathIndex = searchableText.indexOf(ERROR_PATH, langChainIndex + LANGCHAIN.length);\n  while (pathIndex >= 0 && pathIndex < end) {\n    const codeStart = pathIndex + ERROR_PATH.length;\n    let codeEnd = codeStart;\n    while (codeEnd < end && isErrorCodeCharacter(text[codeEnd])) {\n      codeEnd += 1;\n    }\n    if (codeEnd > codeStart) {\n      errorCode = { start: codeStart, end: codeEnd };\n    }\n    pathIndex = searchableText.indexOf(ERROR_PATH, Math.max(codeStart, codeEnd));\n  }\n\n  return errorCode;\n}\n\n/** Removes LangChain's appended docs URL so provider text carries no third-party attribution. */\nexport function stripLangChainTroubleshootingUrl(message: unknown): string {\n  const text = toMessageText(message);\n  const parts: string[] = [];\n  let copiedUntil = 0;\n  let searchFrom = 0;\n\n  while (searchFrom < text.length) {\n    const labelStart = text.indexOf(TROUBLESHOOTING_LABEL, searchFrom);\n    if (labelStart < 0) {\n      break;\n    }\n\n    let matchStart = labelStart;\n    while (matchStart > copiedUntil && WHITESPACE.test(text[matchStart - 1])) {\n      matchStart -= 1;\n    }\n\n    let urlStart = labelStart + TROUBLESHOOTING_LABEL.length;\n    while (urlStart < text.length && WHITESPACE.test(text[urlStart])) {\n      urlStart += 1;\n    }\n    if (!text.startsWith('https://', urlStart) && !text.startsWith('http://', urlStart)) {\n      searchFrom = urlStart;\n      continue;\n    }\n\n    const urlEnd = findTokenEnd(text, urlStart);\n    const errorCode = findErrorCode(text, text, urlStart, urlEnd);\n    if (errorCode == null) {\n      searchFrom = urlEnd;\n      continue;\n    }\n\n    let matchEnd = errorCode.end;\n    if (text[matchEnd] === '/') {\n      matchEnd += 1;\n    }\n    while (matchEnd < text.length && WHITESPACE.test(text[matchEnd])) {\n      matchEnd += 1;\n    }\n\n    parts.push(text.slice(copiedUntil, matchStart), ' ');\n    copiedUntil = matchEnd;\n    searchFrom = matchEnd;\n  }\n\n  parts.push(text.slice(copiedUntil));\n  return parts.join('').trim();\n}\n\n/** The classification LangChain encoded in the docs URL it appended, when the text carries one. */\nexport function parseLangChainErrorCode(message: unknown): string | undefined {\n  const text = toMessageText(message);\n  const searchableText = text.toLowerCase();\n  let searchFrom = 0;\n\n  while (searchFrom < text.length) {\n    const langChainIndex = searchableText.indexOf(LANGCHAIN, searchFrom);\n    if (langChainIndex < 0) {\n      return undefined;\n    }\n    const tokenEnd = findTokenEnd(text, langChainIndex);\n    const errorCode = findErrorCode(text, searchableText, langChainIndex, tokenEnd);\n    if (errorCode != null) {\n      return text.slice(errorCode.start, errorCode.end).toUpperCase();\n    }\n    searchFrom = tokenEnd + 1;\n  }\n\n  return undefined;\n}\n","import type { TDefaultLLMDeliveryPath, TDefaultLLMDeliveryPathConfig } from './file-config';\nimport type { EndpointFileConfig, FileConfig } from './types/files';\nimport {\n  EModelEndpoint,\n  isDocumentSupportedProvider,\n  isKnownProviderIdentifier,\n  isMediaSupportedProvider,\n} from './schemas';\nimport { retrievalMimeTypes, isBedrockDocumentType, codeInterpreterMimeTypes } from './file-config';\nimport { EToolResources } from './types/assistants';\n\n/** Audio and video reach the model only through the media encoders, which support a\n *  narrower provider set than documents. Images use the broadly supported vision\n *  path and are never gated here. */\nconst isProviderCapable = (\n  mimeType: string,\n  endpoint: string,\n  useResponsesApi?: boolean,\n): boolean => {\n  if (mimeType.startsWith('audio/') || mimeType.startsWith('video/')) {\n    return isMediaSupportedProvider(endpoint);\n  }\n  if (mimeType === 'application/pdf') {\n    /* Azure is out of the document set because it needs the Responses API for native\n     * documents, so the encoder's own condition decides rather than the endpoint alone. */\n    return useResponsesApi === true || isDocumentSupportedProvider(endpoint);\n  }\n  return true;\n};\n\nexport const SYSTEM_LLM_DELIVERY_DEFAULTS: Required<TDefaultLLMDeliveryPathConfig> = {\n  fallback: 'text',\n  overrides: {\n    'image/*': 'provider',\n    'video/*': 'provider',\n    'audio/*': 'provider',\n    'application/pdf': 'provider',\n  },\n};\n\n/**\n * Types some step in the upload pipeline can turn into text: natively readable text,\n * documents a parser or OCR handles, images through OCR, and audio through transcription.\n *\n * Everything absent from this list, notably archives, tarballs, columnar data files and\n * video, has no such step, and the default text matcher accepts any well-formed type, so\n * routing them to text ends in their bytes being decoded as UTF-8.\n */\nconst TEXT_RECOVERABLE_MIME_TYPES: RegExp[] = [\n  /^text\\//,\n  /^image\\//,\n  /^audio\\//,\n  /^application\\/(json|javascript|xml|sql|yaml|x-yaml|csv|typescript|x-sh|vnd\\.coffeescript)$/,\n  /^application\\/pdf$/,\n  /* Only the formats the built-in document parser handles. Presentations and graphics\n   * are absent from documentParserMimeTypes, so on a deployment without OCR they would\n   * fall through to the permissive text matcher and be decoded as ZIP bytes. */\n  /^application\\/vnd\\.openxmlformats-officedocument\\.(wordprocessingml\\.document|spreadsheetml\\.sheet)$/,\n  /^application\\/vnd\\.oasis\\.opendocument\\.(text|spreadsheet)$/,\n  /^application\\/(vnd\\.ms-excel|x-msexcel|msexcel|x-ms-excel|x-excel|x-dos_ms_excel|xls|x-xls)$/,\n  /^message\\/rfc822$/,\n];\n\n/**\n * Types whose bytes are text already, so reading them directly is meaningful. Everything\n * else needs a real extractor: decoding it as UTF-8 produces mojibake rather than content.\n */\n/** Application types whose payload is text. Mirrors the set the content-protection code\n *  treats as textual, plus the source and data formats this pipeline also accepts. */\nconst TEXTUAL_APPLICATION_MIME_TYPES = new Set([\n  'application/json',\n  'application/javascript',\n  'application/sql',\n  'application/xml',\n  'application/x-yaml',\n  'application/yaml',\n  'application/csv',\n  'application/typescript',\n  'application/x-sh',\n  'application/vnd.coffeescript',\n]);\n\nexport function isNativelyReadableText(mimeType: string): boolean {\n  const normalized = mimeType.split(';', 1)[0].trim().toLowerCase();\n  return (\n    normalized.startsWith('text/') ||\n    TEXTUAL_APPLICATION_MIME_TYPES.has(normalized) ||\n    normalized === 'message/rfc822'\n  );\n}\n\nexport function hasTextExtractionPath(mimeType: string): boolean {\n  return TEXT_RECOVERABLE_MIME_TYPES.some((pattern) => pattern.test(mimeType));\n}\n\n/**\n * Resolves the default file path destination for a given mime type.\n * Resolution chain: endpoint overrides -> endpoint fallback -> global overrides -> global fallback -> system defaults.\n */\nexport function resolveDefaultLLMDeliveryPath(\n  mimeType: string,\n  endpointConfig?: TDefaultLLMDeliveryPathConfig,\n  globalConfig?: TDefaultLLMDeliveryPathConfig,\n  endpoint?: string,\n  useResponsesApi?: boolean,\n  sttConfigured?: boolean,\n): TDefaultLLMDeliveryPath {\n  const wildcard = mimeType.split('/')[0] + '/*';\n\n  if (endpointConfig?.overrides) {\n    if (endpointConfig.overrides[mimeType]) {\n      return endpointConfig.overrides[mimeType] as TDefaultLLMDeliveryPath;\n    }\n    if (endpointConfig.overrides[wildcard]) {\n      return endpointConfig.overrides[wildcard] as TDefaultLLMDeliveryPath;\n    }\n  }\n\n  if (endpointConfig?.fallback) {\n    return endpointConfig.fallback;\n  }\n\n  if (globalConfig?.overrides) {\n    if (globalConfig.overrides[mimeType]) {\n      return globalConfig.overrides[mimeType] as TDefaultLLMDeliveryPath;\n    }\n    if (globalConfig.overrides[wildcard]) {\n      return globalConfig.overrides[wildcard] as TDefaultLLMDeliveryPath;\n    }\n  }\n\n  if (globalConfig?.fallback) {\n    return globalConfig.fallback;\n  }\n\n  const systemDefault = (SYSTEM_LLM_DELIVERY_DEFAULTS.overrides[mimeType] ??\n    SYSTEM_LLM_DELIVERY_DEFAULTS.overrides[wildcard] ??\n    SYSTEM_LLM_DELIVERY_DEFAULTS.fallback) as TDefaultLLMDeliveryPath;\n\n  /** Only the system default is capability-gated: an explicit config above is the\n   *  admin's decision. A known endpoint that cannot encode documents or media would\n   *  otherwise accept the upload and hand the model nothing at all. */\n  /** `agents` is a container, not a provider: it is what an upload reports when the\n   *  agent's real provider could not be resolved, as for ephemeral agents. A custom\n   *  endpoint name is likewise unresolvable here, since its real provider is chosen\n   *  at request time and is usually OpenAI- or Anthropic-compatible. Judging\n   *  capability from either would downgrade media the actual provider can deliver,\n   *  so an unresolved provider keeps the system default. */\n  const namedEndpoint = endpoint != null && endpoint !== EModelEndpoint.agents;\n  const providerKnown = namedEndpoint && isKnownProviderIdentifier(endpoint);\n  /* Media is judged for any named endpoint, identified or not. The media encoders emit a\n   * payload only for the providers they name, so a custom endpoint gets nothing whatever\n   * it proxies to, and leaving it on the provider path delivers neither media nor text.\n   * Documents keep the narrower rule: an unidentified endpoint is usually OpenAI- or\n   * Anthropic-compatible, both of which do carry them. */\n  const isMedia = mimeType.startsWith('audio/') || mimeType.startsWith('video/');\n  /* Audio's text path is transcription, so on a deployment with no speech provider it is\n   * not recoverable at all. Routing it to text there sends the upload to a service that\n   * is not there and fails it outright. Unknown is left alone; only an explicit absence\n   * closes the path. */\n  const canRecoverText = (type: string): boolean =>\n    type.startsWith('audio/') && sttConfigured === false ? false : hasTextExtractionPath(type);\n  const canJudgeCapability = isMedia ? namedEndpoint : providerKnown;\n  if (\n    systemDefault === 'provider' &&\n    canJudgeCapability &&\n    !isProviderCapable(mimeType, endpoint as string, useResponsesApi)\n  ) {\n    /* Downgrading is only useful where text can actually be recovered. Video has no\n     * extraction step: speech-to-text covers audio, and the default text matcher accepts\n     * any well-formed MIME type, so routing it to text ends in the raw bytes being\n     * decoded as UTF-8 and handed to the model. Keep it off the model path instead; the\n     * file is still stored and still reachable by tools. */\n    return canRecoverText(mimeType) ? 'text' : 'none';\n  }\n\n  /** Bedrock's Converse document path natively accepts more than PDF, so on that\n   *  endpoint its document types belong on the provider path rather than being\n   *  extracted, which would drop non-text content and layout. */\n  if (\n    systemDefault !== 'provider' &&\n    endpoint === EModelEndpoint.bedrock &&\n    isBedrockDocumentType(mimeType)\n  ) {\n    return 'provider';\n  }\n\n  /* The text fallback is only meaningful where text can be recovered. An archive or a\n   * columnar data file reaching it would be decoded as UTF-8 into the prompt, so keep it\n   * off the model path instead; the file is still stored and reachable by tools. An\n   * explicit configuration above has already returned, so this governs the system default\n   * alone. */\n  if (systemDefault === 'text' && !canRecoverText(mimeType)) {\n    return 'none';\n  }\n\n  return systemDefault;\n}\n\n/**\n * Delivery path for an upload that named no tool resource. The legacy chooser makes the\n * destination explicit, so nothing is inferred there.\n */\nexport function resolveDefaultUploadLLMDeliveryPath({\n  mimeType,\n  endpointConfig,\n  fileConfig,\n  endpoint,\n  useResponsesApi,\n  sttConfigured,\n}: {\n  mimeType: string;\n  endpointConfig?: EndpointFileConfig;\n  fileConfig?: FileConfig;\n  endpoint?: string;\n  useResponsesApi?: boolean;\n  sttConfigured?: boolean;\n}): TDefaultLLMDeliveryPath {\n  if (endpointConfig?.legacyFileUploadUX === true) {\n    return 'provider';\n  }\n  return resolveDefaultLLMDeliveryPath(\n    mimeType,\n    endpointConfig?.defaultLLMDeliveryPath,\n    fileConfig?.defaultLLMDeliveryPath,\n    endpoint,\n    useResponsesApi,\n    sttConfigured,\n  );\n}\n\n/** Delivery path for an upload, honoring an explicitly chosen tool resource. */\nexport function resolveUploadLLMDeliveryPath({\n  toolResource,\n  mimeType,\n  endpointConfig,\n  fileConfig,\n  endpoint,\n  useResponsesApi,\n  sttConfigured,\n}: {\n  toolResource?: string | null;\n  mimeType: string;\n  endpointConfig?: EndpointFileConfig;\n  fileConfig?: FileConfig;\n  endpoint?: string;\n  useResponsesApi?: boolean;\n  sttConfigured?: boolean;\n}): TDefaultLLMDeliveryPath {\n  if (toolResource === EToolResources.context || toolResource === EToolResources.ocr) {\n    return 'text';\n  }\n  if (toolResource === EToolResources.file_search || toolResource === EToolResources.execute_code) {\n    return 'none';\n  }\n  return resolveDefaultUploadLLMDeliveryPath({\n    mimeType,\n    endpointConfig,\n    fileConfig,\n    endpoint,\n    useResponsesApi,\n    sttConfigured,\n  });\n}\n\n/**\n * Whether a file tool can do anything with this type. `file_search` indexes extracted\n * text, so it needs a type some step can turn into text and cannot use media, whose\n * extraction paths are OCR and speech rather than the vector store. Code execution is\n * judged by the list the client offers it from. Shared by upload-time selection and\n * deferred provisioning so the two cannot queue a file the other would refuse.\n */\nexport function canToolResourceConsume(toolResource: string, mimeType: string): boolean {\n  if (toolResource === EToolResources.file_search) {\n    /* The union of both readers rather than either alone: the extraction set describes\n     * the document parser and omits presentations, which RAG does handle and the chooser\n     * already offers, while the retrieval set omits csv and the spreadsheet formats. */\n    return (\n      !mimeType.startsWith('image') &&\n      !mimeType.startsWith('audio') &&\n      !mimeType.startsWith('video') &&\n      (hasTextExtractionPath(mimeType) || matchesMimeList(mimeType, retrievalMimeTypes))\n    );\n  }\n  if (toolResource === EToolResources.execute_code) {\n    return matchesMimeList(mimeType, codeInterpreterMimeTypes);\n  }\n  return true;\n}\n\nconst matchesMimeList = (mimeType: string, patterns: RegExp[]): boolean =>\n  patterns.some((pattern) => pattern.test(mimeType));\n\n/** Why an upload cannot be accepted, when nothing would be able to read it. */\nexport type UploadRejection = 'no-agent-resource' | 'context-disabled' | 'no-consumer';\n\n/**\n * Where a unified upload will end up, and whether it can be accepted at all.\n *\n * An upload has to be readable by something: the model, an extraction step, or a file\n * tool. A permanent one has to land on an agent resource too, or storing it succeeds\n * while leaving the agent no reference to it. Both outcomes are decided here rather than\n * discovered later, so a request that would change nothing is refused with a reason.\n *\n * `agentTools` is undefined when no agent record backs the upload, as for an ephemeral\n * agent that exists only for the request. An unknown tool set is not judged.\n */\nexport function resolveUploadDestination(params: {\n  toolResource?: string | null;\n  deliveryPath: TDefaultLLMDeliveryPath;\n  mimeType: string;\n  agentTools?: string[];\n  hasAgent: boolean;\n  isMessageAttachment: boolean;\n  /** True when a message attachment may acquire a compatible tool on a later turn. */\n  allowUnknownMessageConsumer?: boolean;\n  /** Undefined when not looked up, as for an upload that cannot land on context. */\n  contextEnabled?: boolean;\n}): { toolResource?: string; rejection?: UploadRejection } {\n  const {\n    toolResource,\n    deliveryPath,\n    mimeType,\n    agentTools,\n    hasAgent,\n    isMessageAttachment,\n    allowUnknownMessageConsumer = false,\n    contextEnabled,\n  } = params;\n\n  /* A permanent context resource is only readable while the capability is on: priming\n   * skips those ids entirely when it is off, so storing one reports success and leaves\n   * the agent a file it can never open. */\n  const refusesContext = (resource: string): boolean =>\n    resource === EToolResources.context &&\n    hasAgent &&\n    !isMessageAttachment &&\n    contextEnabled === false;\n\n  if (toolResource) {\n    const resolved =\n      toolResource === EToolResources.ocr ? EToolResources.context : (toolResource as string);\n    return refusesContext(resolved)\n      ? { rejection: 'context-disabled' }\n      : { toolResource: resolved };\n  }\n\n  if (deliveryPath === 'text') {\n    return refusesContext(EToolResources.context)\n      ? { rejection: 'context-disabled' }\n      : { toolResource: EToolResources.context };\n  }\n\n  /* Skills contribute file tools per turn without being stored on the agent, so this list\n   * can name a consumer but its silence proves nothing. Used to file an upload, never to\n   * refuse one, and matched on what each tool can actually read so the choice does not\n   * depend on the order the agent happens to list its tools in. */\n  const consumingTool = agentTools?.find(\n    (tool) =>\n      (tool === EToolResources.execute_code || tool === EToolResources.file_search) &&\n      canToolResourceConsume(tool, mimeType),\n  );\n\n  if (deliveryPath === 'none' && consumingTool) {\n    return { toolResource: consumingTool };\n  }\n\n  if (hasAgent && !isMessageAttachment) {\n    return { rejection: 'no-agent-resource' };\n  }\n\n  /* Message attachments may acquire a compatible tool after upload. Permanent agent files\n   * cannot: they must be assigned to a durable resource before this request returns. */\n  if (deliveryPath === 'none' && (!isMessageAttachment || !allowUnknownMessageConsumer)) {\n    return { rejection: 'no-consumer' };\n  }\n\n  return {};\n}\n","import type { TMessageContentParts } from './types/assistants';\nimport type { TFile } from './types/files';\nimport type { TMessage } from './types';\nimport { ContentTypes } from './types/runs';\n\n/** A generated reasoning title describes the text as it existed at generation time.\n *  Any manual edit or merge into a different reasoning step invalidates the entire\n *  title revision domain while preserving unrelated content metadata. */\nexport function stripReasoningLabelMetadata(part: TMessageContentParts): TMessageContentParts {\n  if (part.type !== ContentTypes.THINK) {\n    return part;\n  }\n  const {\n    reasoning_label: _label,\n    reasoning_label_step_id: _stepId,\n    reasoning_label_attempts: _attempts,\n    reasoning_label_submitted_chars: _submittedChars,\n    reasoning_label_revision: _revision,\n    reasoning_label_status: _status,\n    ...unlabeledPart\n  } = part;\n  return unlabeledPart;\n}\n\nexport type ParentMessage = TMessage & { children: TMessage[]; depth: number };\n\n/**\n * Memoizes built trees per messages-array identity. The same query data feeds\n * several independent `select`s (ChatView plus the branch-tail helpers), which\n * used to rebuild the full tree five times per cache write. Exactly two slots\n * per array — the bare tree and the tree for the LATEST fileMap identity — so\n * a long-lived cached conversation cannot accumulate a tree per historical\n * file-map; entries die with the messages array itself.\n */\ntype TreeCacheEntry = {\n  bare?: TMessage[];\n  fileMap?: Record<string, TFile>;\n  hydrated?: TMessage[];\n};\nconst treeCache = new WeakMap<(TMessage | undefined)[], TreeCacheEntry>();\n\n/**\n * Builds the render tree from the flat messages array. Order-robust: live\n * stream/steer/preempt cache writes can momentarily place a child before its\n * parent, and a single-pass link would hoist such rows into phantom root\n * branches — folding the visible thread to one dangling branch until a\n * refetch restores creation order. Linking happens only after every message\n * is indexed, so array order never changes the tree shape.\n */\nexport function buildTree({\n  messages,\n  fileMap,\n}: {\n  messages: (TMessage | undefined)[] | null;\n  fileMap?: Record<string, TFile>;\n}) {\n  if (messages === null) {\n    return null;\n  }\n\n  const cached = treeCache.get(messages);\n  if (cached) {\n    if (fileMap == null && cached.bare) {\n      return cached.bare;\n    }\n    if (fileMap != null && cached.fileMap === fileMap && cached.hydrated) {\n      return cached.hydrated;\n    }\n  }\n\n  const messageMap: Record<string, ParentMessage> = {};\n  const orderedMessages: ParentMessage[] = [];\n  const rootMessages: ParentMessage[] = [];\n  const childrenCount: Record<string, number> = {};\n\n  for (const message of messages) {\n    if (!message) {\n      continue;\n    }\n    /** A self-parented row can never link under itself (it becomes a root),\n     *  so count it with the parentless group — charging its own id would\n     *  inflate the sibling indices of its real children past\n     *  `children.length`. */\n    const parentId =\n      message.parentMessageId === message.messageId ? '' : (message.parentMessageId ?? '');\n    childrenCount[parentId] = (childrenCount[parentId] || 0) + 1;\n\n    const extendedMessage: ParentMessage = {\n      ...message,\n      children: [],\n      depth: 0,\n      siblingIndex: childrenCount[parentId] - 1,\n    };\n\n    if (message.files && fileMap) {\n      extendedMessage.files = message.files.map((file) => fileMap[file.file_id ?? ''] ?? file);\n    }\n\n    messageMap[message.messageId] = extendedMessage;\n    orderedMessages.push(extendedMessage);\n  }\n\n  for (const extendedMessage of orderedMessages) {\n    const parentMessage = messageMap[extendedMessage.parentMessageId ?? ''];\n    if (parentMessage && parentMessage !== extendedMessage) {\n      parentMessage.children.push(extendedMessage);\n    } else {\n      rootMessages.push(extendedMessage);\n    }\n  }\n\n  /** Depth comes from a roots-down walk (a child linked before its parent\n   *  can't inherit depth at link time). The `visited` set doubles as the\n   *  cycle guard: nodes on a corrupt parent cycle are unreachable from any\n   *  root, so they resurface as roots instead of disappearing. */\n  const visited = new Set<ParentMessage>();\n  const assignDepths = (root: ParentMessage) => {\n    visited.add(root);\n    const stack: ParentMessage[] = [root];\n    while (stack.length > 0) {\n      const node = stack.pop() as ParentMessage;\n      /** Every node has one parent, so this walk reaches each node once — an\n       *  already-visited child is a cycle back-edge. Sever it (not just skip\n       *  it) so consumers that recurse `children` terminate. */\n      if ((node.children as ParentMessage[]).some((child) => visited.has(child))) {\n        node.children = (node.children as ParentMessage[]).filter((child) => !visited.has(child));\n      }\n      for (const child of node.children as ParentMessage[]) {\n        child.depth = node.depth + 1;\n        visited.add(child);\n        stack.push(child);\n      }\n    }\n  };\n  for (const root of rootMessages) {\n    assignDepths(root);\n  }\n  for (const extendedMessage of orderedMessages) {\n    if (!visited.has(extendedMessage)) {\n      rootMessages.push(extendedMessage);\n      assignDepths(extendedMessage);\n    }\n  }\n\n  const tree = rootMessages as TMessage[];\n  const entry = cached ?? {};\n  if (fileMap == null) {\n    entry.bare = tree;\n  } else {\n    entry.fileMap = fileMap;\n    entry.hydrated = tree;\n  }\n  if (!cached) {\n    treeCache.set(messages, entry);\n  }\n  return tree;\n}\n\n/**\n * Memoizes a messages array's id index. Every row that needs to look another\n * message up (the hover controls resolving the turn a rerun would replay) would\n * otherwise scan the whole array, which is quadratic in the conversation. A\n * cache write replaces the array, so the index dies with the array it indexes\n * and can never answer from stale rows.\n */\nconst indexCache = new WeakMap<(TMessage | undefined)[], Map<string, TMessage>>();\n\n/** The message with this id, resolved through the array's memoized index. */\nexport function findMessageById(\n  messages: (TMessage | undefined)[] | null | undefined,\n  messageId?: string | null,\n): TMessage | undefined {\n  if (messages == null || messageId == null) {\n    return undefined;\n  }\n  let index = indexCache.get(messages);\n  if (index == null) {\n    index = new Map<string, TMessage>();\n    for (const message of messages) {\n      if (message?.messageId != null && !index.has(message.messageId)) {\n        index.set(message.messageId, message);\n      }\n    }\n    indexCache.set(messages, index);\n  }\n  return index.get(messageId);\n}\n\n/**\n * True when a turn carries the marker the server stamps on a manual compaction:\n * `markCompactionSummary` sets `initiatedBy: 'user'` on the summary a Compact\n * action produced, and nothing else writes it, so an automatic summary detour is\n * not one. This is the compaction's own identity, independent of where it hangs:\n * Compact runs on whatever leaf the branch ends with, so its response can parent\n * onto a user message as easily as onto the answer it summarized. Redoing one is\n * the context indicator's Compact action, never a rerun of the turn behind it.\n */\nexport function isUserInitiatedCompaction(message?: Pick<TMessage, 'content'> | null): boolean {\n  const content = message?.content;\n  if (!Array.isArray(content)) {\n    return false;\n  }\n  return content.some((part) => part?.type === ContentTypes.SUMMARY && part.initiatedBy === 'user');\n}\n\n/**\n * True when a message is a finished manual compaction: every content part is a\n * summary and at least one of them carries text. A part that is still streaming\n * or that failed contributes no text of its own, so an interrupted compaction\n * can be retried.\n */\nexport function isCompactedLeaf(message?: Pick<TMessage, 'content'> | null): boolean {\n  const content = message?.content;\n  if (!Array.isArray(content) || content.length === 0) {\n    return false;\n  }\n  let usable = false;\n  for (const part of content) {\n    if (part?.type !== ContentTypes.SUMMARY) {\n      return false;\n    }\n    if (part.summarizing === true || part.failed === true) {\n      continue;\n    }\n    const hasText = (part.content ?? []).some(\n      (block) => typeof block?.text === 'string' && block.text.trim().length > 0,\n    );\n    usable = usable || hasText;\n  }\n  return usable;\n}\n","const TOOL_CALL_ERROR_PREFIX = /^Error:\\s*(?:\\[[^\\]]*\\]\\s*)*tool call failed:\\s*/i;\n\nexport function hasToolCallErrorPrefix(text: string): boolean {\n  return TOOL_CALL_ERROR_PREFIX.test(text);\n}\n\nexport function stripToolCallErrorPrefix(text: string): string {\n  return text.replace(TOOL_CALL_ERROR_PREFIX, '');\n}\n","/**\n * The timestamp pair these helpers derive from.\n *\n * Both stamps are optional here even though `closed_at` is required on\n * `Agents.RunStepClosedEvent`, because not every caller holds a well-typed\n * event: the Redis replay branch reconstructs closures from persisted JSON and\n * legitimately has nothing stronger than \"might be a number\". Widening the\n * parameter rather than making callers assert keeps the guards below as the\n * single place that decides what is trustworthy — an assertion at a call site\n * would move that decision somewhere it cannot be enforced.\n */\nexport interface RunStepTimestamps {\n  created_at?: number;\n  closed_at?: number;\n}\n\n/**\n * Below this, a duration is noise rather than information: sub-second tool\n * calls are the common case, and labelling every one of them `· 0.3s` adds a\n * moving number to the end of most cards without telling the reader anything\n * they could act on. Callers use {@link isReportableRunStepDuration} rather\n * than comparing against this directly.\n */\nexport const MIN_REPORTABLE_RUN_STEP_DURATION_MS = 1000;\n\n/**\n * Wall-clock duration of a run step, derived from the terminal\n * `on_run_step_closed` event.\n *\n * Returns `undefined` rather than a fallback whenever the value would be a\n * guess, because a wrong duration is worse than an absent one — an absent one\n * renders nothing, a wrong one is indistinguishable from a real measurement:\n *\n * - `created_at` is optional on the event; emitters that do not know when the\n *   step opened cannot have their duration inferred from anything else.\n * - A negative result means the two timestamps came from clocks that disagree.\n *   That is not hypothetical: since `@librechat/agents` v3.6.0 a step can be\n *   opened in one process and closed in another after a checkpoint resume, so\n *   the two stamps can legitimately originate on different machines.\n * - Non-finite input is treated as absent instead of propagating `NaN` into\n *   rendering.\n *\n * Known limits, accepted rather than guessed at: only the negative direction\n * of clock skew is detectable from a single stamp pair — positive skew\n * inflates the result and cannot be distinguished from a genuinely long\n * step. And the value is wall-clock elapsed between open and close, so a\n * step held open across a suspension (a checkpoint resume, a HITL approval\n * wait) includes that held-open time. Both are properties of the only data\n * available, not derivation bugs.\n */\nexport function getRunStepDurationMs(closed: RunStepTimestamps): number | undefined {\n  const { created_at: createdAt, closed_at: closedAt } = closed;\n  if (typeof createdAt !== 'number' || typeof closedAt !== 'number') {\n    return undefined;\n  }\n  if (!Number.isFinite(createdAt) || !Number.isFinite(closedAt)) {\n    return undefined;\n  }\n  const durationMs = closedAt - createdAt;\n  return durationMs >= 0 ? durationMs : undefined;\n}\n\n/**\n * Whether a derived duration is worth showing to the reader.\n *\n * This is a presentation judgment, so it belongs at render time only. The\n * stamp sites persist the raw {@link getRunStepDurationMs} value instead of\n * pre-filtering through this — thresholding at write time would bake a\n * display rule into stored data, making \"fast\" indistinguishable from \"not\n * derivable\" and unrecoverable if the rule ever changes.\n */\nexport function isReportableRunStepDuration(durationMs?: number): durationMs is number {\n  return typeof durationMs === 'number' && durationMs >= MIN_REPORTABLE_RUN_STEP_DURATION_MS;\n}\n","export enum ArtifactModes {\n  DEFAULT = 'default',\n  SHADCNUI = 'shadcnui',\n  CUSTOM = 'custom',\n}\n\nexport const utils = `\nimport { type ClassValue, clsx } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n`;\nexport const accordian = `import * as React from \"react\"\nimport * as AccordionPrimitive from \"@radix-ui/react-accordion\"\nimport { ChevronDown } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Accordion = AccordionPrimitive.Root\n\nconst AccordionItem = React.forwardRef<\n  React.ElementRef<typeof AccordionPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>\n>(({ className, ...props }, ref) => (\n  <AccordionPrimitive.Item\n    ref={ref}\n    className={cn(\"border-b\", className)}\n    {...props}\n  />\n))\nAccordionItem.displayName = \"AccordionItem\"\n\nconst AccordionTrigger = React.forwardRef<\n  React.ElementRef<typeof AccordionPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n  <AccordionPrimitive.Header className=\"flex\">\n    <AccordionPrimitive.Trigger\n      ref={ref}\n      className={cn(\n        \"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180\",\n        className\n      )}\n      {...props}\n    >\n      {children}\n      <ChevronDown className=\"h-4 w-4 shrink-0 transition-transform duration-200\" />\n    </AccordionPrimitive.Trigger>\n  </AccordionPrimitive.Header>\n))\nAccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName\n\nconst AccordionContent = React.forwardRef<\n  React.ElementRef<typeof AccordionPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <AccordionPrimitive.Content\n    ref={ref}\n    className=\"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down\"\n    {...props}\n  >\n    <div className={cn(\"pb-4 pt-0\", className)}>{children}</div>\n  </AccordionPrimitive.Content>\n))\n\nAccordionContent.displayName = AccordionPrimitive.Content.displayName\n\nexport { Accordion, AccordionItem, AccordionTrigger, AccordionContent }\n`;\nexport const alertDialog = `import * as React from \"react\"\nimport * as AlertDialogPrimitive from \"@radix-ui/react-alert-dialog\"\n\nimport { cn } from \"../../lib/utils\"\nimport { buttonVariants } from \"./button\"\n\nconst AlertDialog = AlertDialogPrimitive.Root\n\nconst AlertDialogTrigger = AlertDialogPrimitive.Trigger\n\nconst AlertDialogPortal = AlertDialogPrimitive.Portal\n\nconst AlertDialogOverlay = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Overlay\n    className={cn(\n      \"fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0\",\n      className\n    )}\n    {...props}\n    ref={ref}\n  />\n))\nAlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName\n\nconst AlertDialogContent = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPortal>\n    <AlertDialogOverlay />\n    <AlertDialogPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-gray-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg dark:border-gray-800 dark:bg-gray-950\",\n        className\n      )}\n      {...props}\n    />\n  </AlertDialogPortal>\n))\nAlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName\n\nconst AlertDialogHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col space-y-2 text-center sm:text-left\",\n      className\n    )}\n    {...props}\n  />\n)\nAlertDialogHeader.displayName = \"AlertDialogHeader\"\n\nconst AlertDialogFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n      className\n    )}\n    {...props}\n  />\n)\nAlertDialogFooter.displayName = \"AlertDialogFooter\"\n\nconst AlertDialogTitle = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Title\n    ref={ref}\n    className={cn(\"text-lg font-semibold\", className)}\n    {...props}\n  />\n))\nAlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName\n\nconst AlertDialogDescription = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-gray-500 dark:text-gray-400\", className)}\n    {...props}\n  />\n))\nAlertDialogDescription.displayName =\n  AlertDialogPrimitive.Description.displayName\n\nconst AlertDialogAction = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Action>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Action\n    ref={ref}\n    className={cn(buttonVariants(), className)}\n    {...props}\n  />\n))\nAlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName\n\nconst AlertDialogCancel = React.forwardRef<\n  React.ElementRef<typeof AlertDialogPrimitive.Cancel>,\n  React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>\n>(({ className, ...props }, ref) => (\n  <AlertDialogPrimitive.Cancel\n    ref={ref}\n    className={cn(\n      buttonVariants({ variant: \"outline\" }),\n      \"mt-2 sm:mt-0\",\n      className\n    )}\n    {...props}\n  />\n))\nAlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName\n\nexport {\n  AlertDialog,\n  AlertDialogPortal,\n  AlertDialogOverlay,\n  AlertDialogTrigger,\n  AlertDialogContent,\n  AlertDialogHeader,\n  AlertDialogFooter,\n  AlertDialogTitle,\n  AlertDialogDescription,\n  AlertDialogAction,\n  AlertDialogCancel,\n}\n`;\nexport const alert = `import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst alertVariants = cva(\n  \"relative w-full rounded-lg border border-gray-200 p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-gray-950 dark:border-gray-800 dark:[&>svg]:text-gray-50\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-white text-gray-950 dark:bg-gray-950 dark:text-gray-50\",\n        destructive:\n          \"border-red-500/50 text-red-500 dark:border-red-500 [&>svg]:text-red-500 dark:border-red-900/50 dark:text-red-900 dark:dark:border-red-900 dark:[&>svg]:text-red-900\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n    },\n  }\n)\n\nconst Alert = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>\n>(({ className, variant, ...props }, ref) => (\n  <div\n    ref={ref}\n    role=\"alert\"\n    className={cn(alertVariants({ variant }), className)}\n    {...props}\n  />\n))\nAlert.displayName = \"Alert\"\n\nconst AlertTitle = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLHeadingElement>\n>(({ className, ...props }, ref) => (\n  <h5\n    ref={ref}\n    className={cn(\"mb-1 font-medium leading-none tracking-tight\", className)}\n    {...props}\n  />\n))\nAlertTitle.displayName = \"AlertTitle\"\n\nconst AlertDescription = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\"text-sm [&_p]:leading-relaxed\", className)}\n    {...props}\n  />\n))\nAlertDescription.displayName = \"AlertDescription\"\n\nexport { Alert, AlertTitle, AlertDescription }\n\n`;\nexport const avatar = `import * as React from \"react\"\nimport * as AvatarPrimitive from \"@radix-ui/react-avatar\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Avatar = React.forwardRef<\n  React.ElementRef<typeof AvatarPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <AvatarPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full\",\n      className\n    )}\n    {...props}\n  />\n))\nAvatar.displayName = AvatarPrimitive.Root.displayName\n\nconst AvatarImage = React.forwardRef<\n  React.ElementRef<typeof AvatarPrimitive.Image>,\n  React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>\n>(({ className, ...props }, ref) => (\n  <AvatarPrimitive.Image\n    ref={ref}\n    className={cn(\"aspect-square h-full w-full\", className)}\n    {...props}\n  />\n))\nAvatarImage.displayName = AvatarPrimitive.Image.displayName\n\nconst AvatarFallback = React.forwardRef<\n  React.ElementRef<typeof AvatarPrimitive.Fallback>,\n  React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>\n>(({ className, ...props }, ref) => (\n  <AvatarPrimitive.Fallback\n    ref={ref}\n    className={cn(\n      \"flex h-full w-full items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800\",\n      className\n    )}\n    {...props}\n  />\n))\nAvatarFallback.displayName = AvatarPrimitive.Fallback.displayName\n\nexport { Avatar, AvatarImage, AvatarFallback }\n\n`;\nexport const badge = `import * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst badgeVariants = cva(\n  \"inline-flex items-center rounded-full border border-gray-200 px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 dark:border-gray-800 dark:focus:ring-gray-300\",\n  {\n    variants: {\n      variant: {\n        default:\n          \"border-transparent bg-gray-900 text-gray-50 hover:bg-gray-900/80 dark:bg-gray-50 dark:text-gray-900 dark:hover:bg-gray-50/80\",\n        secondary:\n          \"border-transparent bg-gray-100 text-gray-900 hover:bg-gray-100/80 dark:bg-gray-800 dark:text-gray-50 dark:hover:bg-gray-800/80\",\n        destructive:\n          \"border-transparent bg-red-500 text-gray-50 hover:bg-red-500/80 dark:bg-red-900 dark:text-gray-50 dark:hover:bg-red-900/80\",\n        outline: \"text-gray-950 dark:text-gray-50\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n    },\n  }\n)\n\nexport interface BadgeProps\n  extends React.HTMLAttributes<HTMLDivElement>,\n    VariantProps<typeof badgeVariants> {}\n\nfunction Badge({ className, variant, ...props }: BadgeProps) {\n  return (\n    <div className={cn(badgeVariants({ variant }), className)} {...props} />\n  )\n}\n\nexport { Badge, badgeVariants }\n\n`;\nexport const breadcrumb = `import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { ChevronRight, MoreHorizontal } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Breadcrumb = React.forwardRef<\n  HTMLElement,\n  React.ComponentPropsWithoutRef<\"nav\"> & {\n    separator?: React.ReactNode\n  }\n>(({ ...props }, ref) => <nav ref={ref} aria-label=\"breadcrumb\" {...props} />)\nBreadcrumb.displayName = \"Breadcrumb\"\n\nconst BreadcrumbList = React.forwardRef<\n  HTMLOListElement,\n  React.ComponentPropsWithoutRef<\"ol\">\n>(({ className, ...props }, ref) => (\n  <ol\n    ref={ref}\n    className={cn(\n      \"flex flex-wrap items-center gap-1.5 break-words text-sm text-gray-500 sm:gap-2.5 dark:text-gray-400\",\n      className\n    )}\n    {...props}\n  />\n))\nBreadcrumbList.displayName = \"BreadcrumbList\"\n\nconst BreadcrumbItem = React.forwardRef<\n  HTMLLIElement,\n  React.ComponentPropsWithoutRef<\"li\">\n>(({ className, ...props }, ref) => (\n  <li\n    ref={ref}\n    className={cn(\"inline-flex items-center gap-1.5\", className)}\n    {...props}\n  />\n))\nBreadcrumbItem.displayName = \"BreadcrumbItem\"\n\nconst BreadcrumbLink = React.forwardRef<\n  HTMLAnchorElement,\n  React.ComponentPropsWithoutRef<\"a\"> & {\n    asChild?: boolean\n  }\n>(({ asChild, className, ...props }, ref) => {\n  const Comp = asChild ? Slot : \"a\"\n\n  return (\n    <Comp\n      ref={ref}\n      className={cn(\"transition-colors hover:text-gray-950 dark:hover:text-gray-50\", className)}\n      {...props}\n    />\n  )\n})\nBreadcrumbLink.displayName = \"BreadcrumbLink\"\n\nconst BreadcrumbPage = React.forwardRef<\n  HTMLSpanElement,\n  React.ComponentPropsWithoutRef<\"span\">\n>(({ className, ...props }, ref) => (\n  <span\n    ref={ref}\n    role=\"link\"\n    aria-disabled=\"true\"\n    aria-current=\"page\"\n    className={cn(\"font-normal text-gray-950 dark:text-gray-50\", className)}\n    {...props}\n  />\n))\nBreadcrumbPage.displayName = \"BreadcrumbPage\"\n\nconst BreadcrumbSeparator = ({\n  children,\n  className,\n  ...props\n}: React.ComponentProps<\"li\">) => (\n  <li\n    role=\"presentation\"\n    aria-hidden=\"true\"\n    className={cn(\"[&>svg]:size-3.5\", className)}\n    {...props}\n  >\n    {children ?? <ChevronRight />}\n  </li>\n)\nBreadcrumbSeparator.displayName = \"BreadcrumbSeparator\"\n\nconst BreadcrumbEllipsis = ({\n  className,\n  ...props\n}: React.ComponentProps<\"span\">) => (\n  <span\n    role=\"presentation\"\n    aria-hidden=\"true\"\n    className={cn(\"flex h-9 w-9 items-center justify-center\", className)}\n    {...props}\n  >\n    <MoreHorizontal className=\"h-4 w-4\" />\n    <span className=\"sr-only\">More</span>\n  </span>\n)\nBreadcrumbEllipsis.displayName = \"BreadcrumbElipssis\"\n\nexport {\n  Breadcrumb,\n  BreadcrumbList,\n  BreadcrumbItem,\n  BreadcrumbLink,\n  BreadcrumbPage,\n  BreadcrumbSeparator,\n  BreadcrumbEllipsis,\n}\n\n`;\nexport const button = `import * as React from \"react\"\nimport { Slot } from \"@radix-ui/react-slot\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from '../../lib/utils';\n\nconst buttonVariants = cva(\n  \"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-white transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 dark:ring-offset-gray-950 dark:focus-visible:ring-gray-300\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-gray-900 text-gray-50 hover:bg-gray-900/90 dark:bg-gray-50 dark:text-gray-900 dark:hover:bg-gray-50/90\",\n        destructive:\n          \"bg-red-500 text-gray-50 hover:bg-red-500/90 dark:bg-red-900 dark:text-gray-50 dark:hover:bg-red-900/90\",\n        outline:\n          \"border border-gray-200 bg-white hover:bg-gray-100 hover:text-gray-900 dark:border-gray-800 dark:bg-gray-950 dark:hover:bg-gray-800 dark:hover:text-gray-50\",\n        secondary:\n          \"bg-gray-100 text-gray-900 hover:bg-gray-100/80 dark:bg-gray-800 dark:text-gray-50 dark:hover:bg-gray-800/80\",\n        ghost: \"hover:bg-gray-100 hover:text-gray-900 dark:hover:bg-gray-800 dark:hover:text-gray-50\",\n        link: \"text-gray-900 underline-offset-4 hover:underline dark:text-gray-50\",\n      },\n      size: {\n        default: \"h-10 px-4 py-2\",\n        sm: \"h-9 rounded-md px-3\",\n        lg: \"h-11 rounded-md px-8\",\n        icon: \"h-10 w-10\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n      size: \"default\",\n    },\n  }\n)\n\nexport interface ButtonProps\n  extends React.ButtonHTMLAttributes<HTMLButtonElement>,\n    VariantProps<typeof buttonVariants> {\n  asChild?: boolean\n}\n\nconst Button = React.forwardRef<HTMLButtonElement, ButtonProps>(\n  ({ className, variant, size, asChild = false, ...props }, ref) => {\n    const Comp = asChild ? Slot : \"button\"\n    return (\n      <Comp\n        className={cn(buttonVariants({ variant, size, className }))}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nButton.displayName = \"Button\"\n\nexport { Button, buttonVariants }\n`;\nexport const calendar = `import * as React from \"react\"\nimport { ChevronLeft, ChevronRight } from \"lucide-react\"\nimport { DayPicker } from \"react-day-picker\"\n\nimport { cn } from \"../../lib/utils\"\nimport { buttonVariants } from \"./button\"\n\nexport type CalendarProps = React.ComponentProps<typeof DayPicker>\n\nfunction Calendar({\n  className,\n  classNames,\n  showOutsideDays = true,\n  ...props\n}: CalendarProps) {\n  return (\n    <DayPicker\n      showOutsideDays={showOutsideDays}\n      className={cn(\"p-3\", className)}\n      classNames={{\n        months: \"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0\",\n        month: \"space-y-4\",\n        caption: \"flex justify-center pt-1 relative items-center\",\n        caption_label: \"text-sm font-medium\",\n        nav: \"space-x-1 flex items-center\",\n        nav_button: cn(\n          buttonVariants({ variant: \"outline\" }),\n          \"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100\"\n        ),\n        nav_button_previous: \"absolute left-1\",\n        nav_button_next: \"absolute right-1\",\n        table: \"w-full border-collapse space-y-1\",\n        head_row: \"flex\",\n        head_cell:\n          \"text-gray-500 rounded-md w-9 font-normal text-[0.8rem] dark:text-gray-400\",\n        row: \"flex w-full mt-2\",\n        cell: \"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-gray-100/50 [&:has([aria-selected])]:bg-gray-100 first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20 dark:[&:has([aria-selected].day-outside)]:bg-gray-800/50 dark:[&:has([aria-selected])]:bg-gray-800\",\n        day: cn(\n          buttonVariants({ variant: \"ghost\" }),\n          \"h-9 w-9 p-0 font-normal aria-selected:opacity-100\"\n        ),\n        day_range_end: \"day-range-end\",\n        day_selected:\n          \"bg-gray-900 text-gray-50 hover:bg-gray-900 hover:text-gray-50 focus:bg-gray-900 focus:text-gray-50 dark:bg-gray-50 dark:text-gray-900 dark:hover:bg-gray-50 dark:hover:text-gray-900 dark:focus:bg-gray-50 dark:focus:text-gray-900\",\n        day_today: \"bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-50\",\n        day_outside:\n          \"day-outside text-gray-500 opacity-50 aria-selected:bg-gray-100/50 aria-selected:text-gray-500 aria-selected:opacity-30 dark:text-gray-400 dark:aria-selected:bg-gray-800/50 dark:aria-selected:text-gray-400\",\n        day_disabled: \"text-gray-500 opacity-50 dark:text-gray-400\",\n        day_range_middle:\n          \"aria-selected:bg-gray-100 aria-selected:text-gray-900 dark:aria-selected:bg-gray-800 dark:aria-selected:text-gray-50\",\n        day_hidden: \"invisible\",\n        ...classNames,\n      }}\n      components={{\n        IconLeft: ({ ...props }) => <ChevronLeft className=\"h-4 w-4\" />,\n        IconRight: ({ ...props }) => <ChevronRight className=\"h-4 w-4\" />,\n      }}\n      {...props}\n    />\n  )\n}\nCalendar.displayName = \"Calendar\"\n\nexport { Calendar }\n\n`;\nexport const card = `import * as React from 'react';\n\nimport { cn } from '../../lib/utils';\n\nconst Card = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\n      \"rounded-lg border border-gray-200 bg-white text-gray-950 shadow-sm dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nCard.displayName = \"Card\"\n\nconst CardHeader = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\"flex flex-col space-y-1.5 p-6\", className)}\n    {...props}\n  />\n))\nCardHeader.displayName = \"CardHeader\"\n\nconst CardTitle = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLHeadingElement>\n>(({ className, ...props }, ref) => (\n  <h3\n    ref={ref}\n    className={cn(\n      \"text-2xl font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nCardTitle.displayName = \"CardTitle\"\n\nconst CardDescription = React.forwardRef<\n  HTMLParagraphElement,\n  React.HTMLAttributes<HTMLParagraphElement>\n>(({ className, ...props }, ref) => (\n  <p\n    ref={ref}\n    className={cn(\"text-sm text-gray-500 dark:text-gray-400\", className)}\n    {...props}\n  />\n))\nCardDescription.displayName = \"CardDescription\"\n\nconst CardContent = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div ref={ref} className={cn(\"p-6 pt-0\", className)} {...props} />\n))\nCardContent.displayName = \"CardContent\"\n\nconst CardFooter = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => (\n  <div\n    ref={ref}\n    className={cn(\"flex items-center p-6 pt-0\", className)}\n    {...props}\n  />\n))\nCardFooter.displayName = \"CardFooter\"\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }\n`;\nexport const carousel = `import * as React from \"react\"\nimport useEmblaCarousel, {\n  type UseEmblaCarouselType,\n} from \"embla-carousel-react\"\nimport { ArrowLeft, ArrowRight } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\nimport { Button } from \"./button\"\n\ntype CarouselApi = UseEmblaCarouselType[1]\ntype UseCarouselParameters = Parameters<typeof useEmblaCarousel>\ntype CarouselOptions = UseCarouselParameters[0]\ntype CarouselPlugin = UseCarouselParameters[1]\n\ntype CarouselProps = {\n  opts?: CarouselOptions\n  plugins?: CarouselPlugin\n  orientation?: \"horizontal\" | \"vertical\"\n  setApi?: (api: CarouselApi) => void\n}\n\ntype CarouselContextProps = {\n  carouselRef: ReturnType<typeof useEmblaCarousel>[0]\n  api: ReturnType<typeof useEmblaCarousel>[1]\n  scrollPrev: () => void\n  scrollNext: () => void\n  canScrollPrev: boolean\n  canScrollNext: boolean\n} & CarouselProps\n\nconst CarouselContext = React.createContext<CarouselContextProps | null>(null)\n\nfunction useCarousel() {\n  const context = React.useContext(CarouselContext)\n\n  if (!context) {\n    throw new Error(\"useCarousel must be used within a <Carousel />\")\n  }\n\n  return context\n}\n\nconst Carousel = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement> & CarouselProps\n>(\n  (\n    {\n      orientation = \"horizontal\",\n      opts,\n      setApi,\n      plugins,\n      className,\n      children,\n      ...props\n    },\n    ref\n  ) => {\n    const [carouselRef, api] = useEmblaCarousel(\n      {\n        ...opts,\n        axis: orientation === \"horizontal\" ? \"x\" : \"y\",\n      },\n      plugins\n    )\n    const [canScrollPrev, setCanScrollPrev] = React.useState(false)\n    const [canScrollNext, setCanScrollNext] = React.useState(false)\n\n    const onSelect = React.useCallback((api: CarouselApi) => {\n      if (!api) {\n        return\n      }\n\n      setCanScrollPrev(api.canScrollPrev())\n      setCanScrollNext(api.canScrollNext())\n    }, [])\n\n    const scrollPrev = React.useCallback(() => {\n      api?.scrollPrev()\n    }, [api])\n\n    const scrollNext = React.useCallback(() => {\n      api?.scrollNext()\n    }, [api])\n\n    const handleKeyDown = React.useCallback(\n      (event: React.KeyboardEvent<HTMLDivElement>) => {\n        if (event.key === \"ArrowLeft\") {\n          event.preventDefault()\n          scrollPrev()\n        } else if (event.key === \"ArrowRight\") {\n          event.preventDefault()\n          scrollNext()\n        }\n      },\n      [scrollPrev, scrollNext]\n    )\n\n    React.useEffect(() => {\n      if (!api || !setApi) {\n        return\n      }\n\n      setApi(api)\n    }, [api, setApi])\n\n    React.useEffect(() => {\n      if (!api) {\n        return\n      }\n\n      onSelect(api)\n      api.on(\"reInit\", onSelect)\n      api.on(\"select\", onSelect)\n\n      return () => {\n        api?.off(\"select\", onSelect)\n      }\n    }, [api, onSelect])\n\n    return (\n      <CarouselContext.Provider\n        value={{\n          carouselRef,\n          api: api,\n          opts,\n          orientation:\n            orientation || (opts?.axis === \"y\" ? \"vertical\" : \"horizontal\"),\n          scrollPrev,\n          scrollNext,\n          canScrollPrev,\n          canScrollNext,\n        }}\n      >\n        <div\n          ref={ref}\n          onKeyDownCapture={handleKeyDown}\n          className={cn(\"relative\", className)}\n          role=\"region\"\n          aria-roledescription=\"carousel\"\n          {...props}\n        >\n          {children}\n        </div>\n      </CarouselContext.Provider>\n    )\n  }\n)\nCarousel.displayName = \"Carousel\"\n\nconst CarouselContent = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => {\n  const { carouselRef, orientation } = useCarousel()\n\n  return (\n    <div ref={carouselRef} className=\"overflow-hidden\">\n      <div\n        ref={ref}\n        className={cn(\n          \"flex\",\n          orientation === \"horizontal\" ? \"-ml-4\" : \"-mt-4 flex-col\",\n          className\n        )}\n        {...props}\n      />\n    </div>\n  )\n})\nCarouselContent.displayName = \"CarouselContent\"\n\nconst CarouselItem = React.forwardRef<\n  HTMLDivElement,\n  React.HTMLAttributes<HTMLDivElement>\n>(({ className, ...props }, ref) => {\n  const { orientation } = useCarousel()\n\n  return (\n    <div\n      ref={ref}\n      role=\"group\"\n      aria-roledescription=\"slide\"\n      className={cn(\n        \"min-w-0 shrink-0 grow-0 basis-full\",\n        orientation === \"horizontal\" ? \"pl-4\" : \"pt-4\",\n        className\n      )}\n      {...props}\n    />\n  )\n})\nCarouselItem.displayName = \"CarouselItem\"\n\nconst CarouselPrevious = React.forwardRef<\n  HTMLButtonElement,\n  React.ComponentProps<typeof Button>\n>(({ className, variant = \"outline\", size = \"icon\", ...props }, ref) => {\n  const { orientation, scrollPrev, canScrollPrev } = useCarousel()\n\n  return (\n    <Button\n      ref={ref}\n      variant={variant}\n      size={size}\n      className={cn(\n        \"absolute  h-8 w-8 rounded-full\",\n        orientation === \"horizontal\"\n          ? \"-left-12 top-1/2 -translate-y-1/2\"\n          : \"-top-12 left-1/2 -translate-x-1/2 rotate-90\",\n        className\n      )}\n      disabled={!canScrollPrev}\n      onClick={scrollPrev}\n      {...props}\n    >\n      <ArrowLeft className=\"h-4 w-4\" />\n      <span className=\"sr-only\">Previous slide</span>\n    </Button>\n  )\n})\nCarouselPrevious.displayName = \"CarouselPrevious\"\n\nconst CarouselNext = React.forwardRef<\n  HTMLButtonElement,\n  React.ComponentProps<typeof Button>\n>(({ className, variant = \"outline\", size = \"icon\", ...props }, ref) => {\n  const { orientation, scrollNext, canScrollNext } = useCarousel()\n\n  return (\n    <Button\n      ref={ref}\n      variant={variant}\n      size={size}\n      className={cn(\n        \"absolute h-8 w-8 rounded-full\",\n        orientation === \"horizontal\"\n          ? \"-right-12 top-1/2 -translate-y-1/2\"\n          : \"-bottom-12 left-1/2 -translate-x-1/2 rotate-90\",\n        className\n      )}\n      disabled={!canScrollNext}\n      onClick={scrollNext}\n      {...props}\n    >\n      <ArrowRight className=\"h-4 w-4\" />\n      <span className=\"sr-only\">Next slide</span>\n    </Button>\n  )\n})\nCarouselNext.displayName = \"CarouselNext\"\n\nexport {\n  type CarouselApi,\n  Carousel,\n  CarouselContent,\n  CarouselItem,\n  CarouselPrevious,\n  CarouselNext,\n}\n\n`;\nexport const checkbox = `import * as React from \"react\"\nimport * as CheckboxPrimitive from \"@radix-ui/react-checkbox\"\nimport { Check } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Checkbox = React.forwardRef<\n  React.ElementRef<typeof CheckboxPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <CheckboxPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"peer h-4 w-4 shrink-0 rounded-sm border border-gray-200 dark:border-gray-900 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-gray-900 data-[state=checked]:text-gray-50  dark:ring-offset-gray-950 dark:focus-visible:ring-gray-300 dark:data-[state=checked]:bg-gray-50 dark:data-[state=checked]:text-gray-900\",\n      className\n    )}\n    {...props}\n  >\n    <CheckboxPrimitive.Indicator\n      className={cn(\"flex items-center justify-center text-current\")}\n    >\n      <Check className=\"h-4 w-4\" />\n    </CheckboxPrimitive.Indicator>\n  </CheckboxPrimitive.Root>\n))\nCheckbox.displayName = CheckboxPrimitive.Root.displayName\n\nexport { Checkbox }\n\n`;\nexport const collapsible = `import * as CollapsiblePrimitive from \"@radix-ui/react-collapsible\"\n\nconst Collapsible = CollapsiblePrimitive.Root\n\nconst CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger\n\nconst CollapsibleContent = CollapsiblePrimitive.CollapsibleContent\n\nexport { Collapsible, CollapsibleTrigger, CollapsibleContent }\n\n`;\nexport const dialog = `import * as React from \"react\"\nimport * as DialogPrimitive from \"@radix-ui/react-dialog\"\nimport { X } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Dialog = DialogPrimitive.Root\n\nconst DialogTrigger = DialogPrimitive.Trigger\n\nconst DialogPortal = DialogPrimitive.Portal\n\nconst DialogClose = DialogPrimitive.Close\n\nconst DialogOverlay = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Overlay\n    ref={ref}\n    className={cn(\n      \"fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0\",\n      className\n    )}\n    {...props}\n  />\n))\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName\n\nconst DialogContent = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <DialogPortal>\n    <DialogOverlay />\n    <DialogPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-gray-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg dark:border-gray-800 dark:bg-gray-950\",\n        className\n      )}\n      {...props}\n    >\n      {children}\n      <DialogPrimitive.Close className=\"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-gray-100 data-[state=open]:text-gray-500 dark:ring-offset-gray-950 dark:focus:ring-gray-300 dark:data-[state=open]:bg-gray-800 dark:data-[state=open]:text-gray-400\">\n        <X className=\"h-4 w-4\" />\n        <span className=\"sr-only\">Close</span>\n      </DialogPrimitive.Close>\n    </DialogPrimitive.Content>\n  </DialogPortal>\n))\nDialogContent.displayName = DialogPrimitive.Content.displayName\n\nconst DialogHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col space-y-1.5 text-center sm:text-left\",\n      className\n    )}\n    {...props}\n  />\n)\nDialogHeader.displayName = \"DialogHeader\"\n\nconst DialogFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\n      \"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2\",\n      className\n    )}\n    {...props}\n  />\n)\nDialogFooter.displayName = \"DialogFooter\"\n\nconst DialogTitle = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Title\n    ref={ref}\n    className={cn(\n      \"text-lg font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nDialogTitle.displayName = DialogPrimitive.Title.displayName\n\nconst DialogDescription = React.forwardRef<\n  React.ElementRef<typeof DialogPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <DialogPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-gray-500 dark:text-gray-400\", className)}\n    {...props}\n  />\n))\nDialogDescription.displayName = DialogPrimitive.Description.displayName\n\nexport {\n  Dialog,\n  DialogPortal,\n  DialogOverlay,\n  DialogClose,\n  DialogTrigger,\n  DialogContent,\n  DialogHeader,\n  DialogFooter,\n  DialogTitle,\n  DialogDescription,\n}\n\n`;\nexport const drawer = `import * as React from \"react\"\nimport { Drawer as DrawerPrimitive } from \"vaul\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Drawer = ({\n  shouldScaleBackground = true,\n  ...props\n}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (\n  <DrawerPrimitive.Root\n    shouldScaleBackground={shouldScaleBackground}\n    {...props}\n  />\n)\nDrawer.displayName = \"Drawer\"\n\nconst DrawerTrigger = DrawerPrimitive.Trigger\n\nconst DrawerPortal = DrawerPrimitive.Portal\n\nconst DrawerClose = DrawerPrimitive.Close\n\nconst DrawerOverlay = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Overlay>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n  <DrawerPrimitive.Overlay\n    ref={ref}\n    className={cn(\"fixed inset-0 z-50 bg-black/80\", className)}\n    {...props}\n  />\n))\nDrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName\n\nconst DrawerContent = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>\n>(({ className, children, ...props }, ref) => (\n  <DrawerPortal>\n    <DrawerOverlay />\n    <DrawerPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-950\",\n        className\n      )}\n      {...props}\n    >\n      <div className=\"mx-auto mt-4 h-2 w-[100px] rounded-full bg-gray-100 dark:bg-gray-800\" />\n      {children}\n    </DrawerPrimitive.Content>\n  </DrawerPortal>\n))\nDrawerContent.displayName = \"DrawerContent\"\n\nconst DrawerHeader = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\"grid gap-1.5 p-4 text-center sm:text-left\", className)}\n    {...props}\n  />\n)\nDrawerHeader.displayName = \"DrawerHeader\"\n\nconst DrawerFooter = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) => (\n  <div\n    className={cn(\"mt-auto flex flex-col gap-2 p-4\", className)}\n    {...props}\n  />\n)\nDrawerFooter.displayName = \"DrawerFooter\"\n\nconst DrawerTitle = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Title>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>\n>(({ className, ...props }, ref) => (\n  <DrawerPrimitive.Title\n    ref={ref}\n    className={cn(\n      \"text-lg font-semibold leading-none tracking-tight\",\n      className\n    )}\n    {...props}\n  />\n))\nDrawerTitle.displayName = DrawerPrimitive.Title.displayName\n\nconst DrawerDescription = React.forwardRef<\n  React.ElementRef<typeof DrawerPrimitive.Description>,\n  React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>\n>(({ className, ...props }, ref) => (\n  <DrawerPrimitive.Description\n    ref={ref}\n    className={cn(\"text-sm text-gray-500 dark:text-gray-400\", className)}\n    {...props}\n  />\n))\nDrawerDescription.displayName = DrawerPrimitive.Description.displayName\n\nexport {\n  Drawer,\n  DrawerPortal,\n  DrawerOverlay,\n  DrawerTrigger,\n  DrawerClose,\n  DrawerContent,\n  DrawerHeader,\n  DrawerFooter,\n  DrawerTitle,\n  DrawerDescription,\n}\n\n`;\nexport const dropdownMenu = `import * as React from \"react\"\nimport * as DropdownMenuPrimitive from \"@radix-ui/react-dropdown-menu\"\nimport { Check, ChevronRight, Circle } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst DropdownMenu = DropdownMenuPrimitive.Root\n\nconst DropdownMenuTrigger = DropdownMenuPrimitive.Trigger\n\nconst DropdownMenuGroup = DropdownMenuPrimitive.Group\n\nconst DropdownMenuPortal = DropdownMenuPrimitive.Portal\n\nconst DropdownMenuSub = DropdownMenuPrimitive.Sub\n\nconst DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup\n\nconst DropdownMenuSubTrigger = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {\n    inset?: boolean\n  }\n>(({ className, inset, children, ...props }, ref) => (\n  <DropdownMenuPrimitive.SubTrigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-gray-100 data-[state=open]:bg-gray-100 dark:focus:bg-gray-800 dark:data-[state=open]:bg-gray-800\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <ChevronRight className=\"ml-auto h-4 w-4\" />\n  </DropdownMenuPrimitive.SubTrigger>\n))\nDropdownMenuSubTrigger.displayName =\n  DropdownMenuPrimitive.SubTrigger.displayName\n\nconst DropdownMenuSubContent = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>\n>(({ className, ...props }, ref) => (\n  <DropdownMenuPrimitive.SubContent\n    ref={ref}\n    className={cn(\n      \"z-50 min-w-[8rem] overflow-hidden rounded-md border border-gray-200 bg-white p-1 text-gray-950 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nDropdownMenuSubContent.displayName =\n  DropdownMenuPrimitive.SubContent.displayName\n\nconst DropdownMenuContent = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n  <DropdownMenuPrimitive.Portal>\n    <DropdownMenuPrimitive.Content\n      ref={ref}\n      sideOffset={sideOffset}\n      className={cn(\n        \"z-50 min-w-[8rem] overflow-hidden rounded-md border border-gray-200 bg-white p-1 text-gray-950 shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n        className\n      )}\n      {...props}\n    />\n  </DropdownMenuPrimitive.Portal>\n))\nDropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName\n\nconst DropdownMenuItem = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <DropdownMenuPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nDropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName\n\nconst DropdownMenuCheckboxItem = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>\n>(({ className, children, checked, ...props }, ref) => (\n  <DropdownMenuPrimitive.CheckboxItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      className\n    )}\n    checked={checked}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <DropdownMenuPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </DropdownMenuPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </DropdownMenuPrimitive.CheckboxItem>\n))\nDropdownMenuCheckboxItem.displayName =\n  DropdownMenuPrimitive.CheckboxItem.displayName\n\nconst DropdownMenuRadioItem = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>\n>(({ className, children, ...props }, ref) => (\n  <DropdownMenuPrimitive.RadioItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <DropdownMenuPrimitive.ItemIndicator>\n        <Circle className=\"h-2 w-2 fill-current\" />\n      </DropdownMenuPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </DropdownMenuPrimitive.RadioItem>\n))\nDropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName\n\nconst DropdownMenuLabel = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <DropdownMenuPrimitive.Label\n    ref={ref}\n    className={cn(\n      \"px-2 py-1.5 text-sm font-semibold\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nDropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName\n\nconst DropdownMenuSeparator = React.forwardRef<\n  React.ElementRef<typeof DropdownMenuPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <DropdownMenuPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-gray-100 dark:bg-gray-800\", className)}\n    {...props}\n  />\n))\nDropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName\n\nconst DropdownMenuShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\"ml-auto text-xs tracking-widest opacity-60\", className)}\n      {...props}\n    />\n  )\n}\nDropdownMenuShortcut.displayName = \"DropdownMenuShortcut\"\n\nexport {\n  DropdownMenu,\n  DropdownMenuTrigger,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuCheckboxItem,\n  DropdownMenuRadioItem,\n  DropdownMenuLabel,\n  DropdownMenuSeparator,\n  DropdownMenuShortcut,\n  DropdownMenuGroup,\n  DropdownMenuPortal,\n  DropdownMenuSub,\n  DropdownMenuSubContent,\n  DropdownMenuSubTrigger,\n  DropdownMenuRadioGroup,\n}\n\n`;\nexport const hoverCard = `import * as React from \"react\"\nimport * as HoverCardPrimitive from \"@radix-ui/react-hover-card\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst HoverCard = HoverCardPrimitive.Root\n\nconst HoverCardTrigger = HoverCardPrimitive.Trigger\n\nconst HoverCardContent = React.forwardRef<\n  React.ElementRef<typeof HoverCardPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>\n>(({ className, align = \"center\", sideOffset = 4, ...props }, ref) => (\n  <HoverCardPrimitive.Content\n    ref={ref}\n    align={align}\n    sideOffset={sideOffset}\n    className={cn(\n      \"z-50 w-64 rounded-md border border-gray-200 bg-white p-4 text-gray-950 shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nHoverCardContent.displayName = HoverCardPrimitive.Content.displayName\n\nexport { HoverCard, HoverCardTrigger, HoverCardContent }\n\n`;\nexport const input = `import * as React from \"react\"\nimport { cn } from \"../../lib/utils\"\n\nexport interface InputProps\n  extends React.InputHTMLAttributes<HTMLInputElement> {}\n\nconst Input = React.forwardRef<HTMLInputElement, InputProps>(\n  ({ className, type, ...props }, ref) => {\n    return (\n      <input\n        type={type}\n        className={cn(\n          \"flex h-10 w-full rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-gray-950 dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus-visible:ring-gray-300\",\n          className\n        )}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nInput.displayName = \"Input\"\n\nexport { Input }\n`;\nexport const label = `import * as React from 'react';\nimport * as LabelPrimitive from '@radix-ui/react-label';\nimport { cva, type VariantProps } from 'class-variance-authority';\n\nimport { cn } from '../../lib/utils';\n\nconst labelVariants = cva(\n  \"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70\"\n)\n\nconst Label = React.forwardRef<\n  React.ElementRef<typeof LabelPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &\n    VariantProps<typeof labelVariants>\n>(({ className, ...props }, ref) => (\n  <LabelPrimitive.Root\n    ref={ref}\n    className={cn(labelVariants(), className)}\n    {...props}\n  />\n))\nLabel.displayName = LabelPrimitive.Root.displayName\n\nexport { Label }\n`;\nexport const menuBar = `\nimport * as React from \"react\"\nimport * as MenubarPrimitive from \"@radix-ui/react-menubar\"\nimport { Check, ChevronRight, Circle } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst MenubarMenu = MenubarPrimitive.Menu\n\nconst MenubarGroup = MenubarPrimitive.Group\n\nconst MenubarPortal = MenubarPrimitive.Portal\n\nconst MenubarSub = MenubarPrimitive.Sub\n\nconst MenubarRadioGroup = MenubarPrimitive.RadioGroup\n\nconst Menubar = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"flex h-10 items-center space-x-1 rounded-md border border-gray-200 bg-white p-1 dark:border-gray-800 dark:bg-gray-950\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubar.displayName = MenubarPrimitive.Root.displayName\n\nconst MenubarTrigger = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.Trigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-gray-100 focus:text-gray-900 data-[state=open]:bg-gray-100 data-[state=open]:text-gray-900 dark:focus:bg-gray-800 dark:focus:text-gray-50 dark:data-[state=open]:bg-gray-800 dark:data-[state=open]:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName\n\nconst MenubarSubTrigger = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.SubTrigger>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {\n    inset?: boolean\n  }\n>(({ className, inset, children, ...props }, ref) => (\n  <MenubarPrimitive.SubTrigger\n    ref={ref}\n    className={cn(\n      \"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-gray-100 focus:text-gray-900 data-[state=open]:bg-gray-100 data-[state=open]:text-gray-900 dark:focus:bg-gray-800 dark:focus:text-gray-50 dark:data-[state=open]:bg-gray-800 dark:data-[state=open]:text-gray-50\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <ChevronRight className=\"ml-auto h-4 w-4\" />\n  </MenubarPrimitive.SubTrigger>\n))\nMenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName\n\nconst MenubarSubContent = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.SubContent>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.SubContent\n    ref={ref}\n    className={cn(\n      \"z-50 min-w-[8rem] overflow-hidden rounded-md border border-gray-200 bg-white p-1 text-gray-950 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName\n\nconst MenubarContent = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>\n>(\n  (\n    { className, align = \"start\", alignOffset = -4, sideOffset = 8, ...props },\n    ref\n  ) => (\n    <MenubarPrimitive.Portal>\n      <MenubarPrimitive.Content\n        ref={ref}\n        align={align}\n        alignOffset={alignOffset}\n        sideOffset={sideOffset}\n        className={cn(\n          \"z-50 min-w-[12rem] overflow-hidden rounded-md border border-gray-200 bg-white p-1 text-gray-950 shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n          className\n        )}\n        {...props}\n      />\n    </MenubarPrimitive.Portal>\n  )\n)\nMenubarContent.displayName = MenubarPrimitive.Content.displayName\n\nconst MenubarItem = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <MenubarPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarItem.displayName = MenubarPrimitive.Item.displayName\n\nconst MenubarCheckboxItem = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>\n>(({ className, children, checked, ...props }, ref) => (\n  <MenubarPrimitive.CheckboxItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      className\n    )}\n    checked={checked}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <MenubarPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </MenubarPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </MenubarPrimitive.CheckboxItem>\n))\nMenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName\n\nconst MenubarRadioItem = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.RadioItem>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>\n>(({ className, children, ...props }, ref) => (\n  <MenubarPrimitive.RadioItem\n    ref={ref}\n    className={cn(\n      \"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <MenubarPrimitive.ItemIndicator>\n        <Circle className=\"h-2 w-2 fill-current\" />\n      </MenubarPrimitive.ItemIndicator>\n    </span>\n    {children}\n  </MenubarPrimitive.RadioItem>\n))\nMenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName\n\nconst MenubarLabel = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {\n    inset?: boolean\n  }\n>(({ className, inset, ...props }, ref) => (\n  <MenubarPrimitive.Label\n    ref={ref}\n    className={cn(\n      \"px-2 py-1.5 text-sm font-semibold\",\n      inset && \"pl-8\",\n      className\n    )}\n    {...props}\n  />\n))\nMenubarLabel.displayName = MenubarPrimitive.Label.displayName\n\nconst MenubarSeparator = React.forwardRef<\n  React.ElementRef<typeof MenubarPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <MenubarPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-gray-100 dark:bg-gray-800\", className)}\n    {...props}\n  />\n))\nMenubarSeparator.displayName = MenubarPrimitive.Separator.displayName\n\nconst MenubarShortcut = ({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLSpanElement>) => {\n  return (\n    <span\n      className={cn(\n        \"ml-auto text-xs tracking-widest text-gray-500 dark:text-gray-400\",\n        className\n      )}\n      {...props}\n    />\n  )\n}\nMenubarShortcut.displayname = \"MenubarShortcut\"\n\nexport {\n  Menubar,\n  MenubarMenu,\n  MenubarTrigger,\n  MenubarContent,\n  MenubarItem,\n  MenubarSeparator,\n  MenubarLabel,\n  MenubarCheckboxItem,\n  MenubarRadioGroup,\n  MenubarRadioItem,\n  MenubarPortal,\n  MenubarSubContent,\n  MenubarSubTrigger,\n  MenubarGroup,\n  MenubarSub,\n  MenubarShortcut,\n}\n\n`;\nexport const navigationMenu = `import * as React from \"react\"\nimport * as NavigationMenuPrimitive from \"@radix-ui/react-navigation-menu\"\nimport { cva } from \"class-variance-authority\"\nimport { ChevronDown } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst NavigationMenu = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>\n>(({ className, children, ...props }, ref) => (\n  <NavigationMenuPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative z-10 flex max-w-max flex-1 items-center justify-center\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <NavigationMenuViewport />\n  </NavigationMenuPrimitive.Root>\n))\nNavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName\n\nconst NavigationMenuList = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>\n>(({ className, ...props }, ref) => (\n  <NavigationMenuPrimitive.List\n    ref={ref}\n    className={cn(\n      \"group flex flex-1 list-none items-center justify-center space-x-1\",\n      className\n    )}\n    {...props}\n  />\n))\nNavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName\n\nconst NavigationMenuItem = NavigationMenuPrimitive.Item\n\nconst navigationMenuTriggerStyle = cva(\n  \"group inline-flex h-10 w-max items-center justify-center rounded-md bg-white px-4 py-2 text-sm font-medium transition-colors hover:bg-gray-100 hover:text-gray-900 focus:bg-gray-100 focus:text-gray-900 focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-gray-100/50 data-[state=open]:bg-gray-100/50 dark:bg-gray-950 dark:hover:bg-gray-800 dark:hover:text-gray-50 dark:focus:bg-gray-800 dark:focus:text-gray-50 dark:data-[active]:bg-gray-800/50 dark:data-[state=open]:bg-gray-800/50\"\n)\n\nconst NavigationMenuTrigger = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n  <NavigationMenuPrimitive.Trigger\n    ref={ref}\n    className={cn(navigationMenuTriggerStyle(), \"group\", className)}\n    {...props}\n  >\n    {children}{\"\"}\n    <ChevronDown\n      className=\"relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180\"\n      aria-hidden=\"true\"\n    />\n  </NavigationMenuPrimitive.Trigger>\n))\nNavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName\n\nconst NavigationMenuContent = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <NavigationMenuPrimitive.Content\n    ref={ref}\n    className={cn(\n      \"left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto\",\n      className\n    )}\n    {...props}\n  />\n))\nNavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName\n\nconst NavigationMenuLink = NavigationMenuPrimitive.Link\n\nconst NavigationMenuViewport = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>\n>(({ className, ...props }, ref) => (\n  <div className={cn(\"absolute left-0 top-full flex justify-center\")}>\n    <NavigationMenuPrimitive.Viewport\n      className={cn(\n        \"origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border border-gray-200 bg-white text-gray-950 shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)] dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n        className\n      )}\n      ref={ref}\n      {...props}\n    />\n  </div>\n))\nNavigationMenuViewport.displayName =\n  NavigationMenuPrimitive.Viewport.displayName\n\nconst NavigationMenuIndicator = React.forwardRef<\n  React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,\n  React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>\n>(({ className, ...props }, ref) => (\n  <NavigationMenuPrimitive.Indicator\n    ref={ref}\n    className={cn(\n      \"top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in\",\n      className\n    )}\n    {...props}\n  >\n    <div className=\"relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-gray-200 shadow-md dark:bg-gray-800\" />\n  </NavigationMenuPrimitive.Indicator>\n))\nNavigationMenuIndicator.displayName =\n  NavigationMenuPrimitive.Indicator.displayName\n\nexport {\n  navigationMenuTriggerStyle,\n  NavigationMenu,\n  NavigationMenuList,\n  NavigationMenuItem,\n  NavigationMenuContent,\n  NavigationMenuTrigger,\n  NavigationMenuLink,\n  NavigationMenuIndicator,\n  NavigationMenuViewport,\n}\n\n`;\nexport const pagination = `import * as React from \"react\"\nimport { ChevronLeft, ChevronRight, MoreHorizontal } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\nimport { ButtonProps, buttonVariants } from \"./button\"\n\nconst Pagination = ({ className, ...props }: React.ComponentProps<\"nav\">) => (\n  <nav\n    role=\"navigation\"\n    aria-label=\"pagination\"\n    className={cn(\"mx-auto flex w-full justify-center\", className)}\n    {...props}\n  />\n)\nPagination.displayName = \"Pagination\"\n\nconst PaginationContent = React.forwardRef<\n  HTMLUListElement,\n  React.ComponentProps<\"ul\">\n>(({ className, ...props }, ref) => (\n  <ul\n    ref={ref}\n    className={cn(\"flex flex-row items-center gap-1\", className)}\n    {...props}\n  />\n))\nPaginationContent.displayName = \"PaginationContent\"\n\nconst PaginationItem = React.forwardRef<\n  HTMLLIElement,\n  React.ComponentProps<\"li\">\n>(({ className, ...props }, ref) => (\n  <li ref={ref} className={cn(\"\", className)} {...props} />\n))\nPaginationItem.displayName = \"PaginationItem\"\n\ntype PaginationLinkProps = {\n  isActive?: boolean\n} & Pick<ButtonProps, \"size\"> &\n  React.ComponentProps<\"a\">\n\nconst PaginationLink = ({\n  className,\n  isActive,\n  size = \"icon\",\n  ...props\n}: PaginationLinkProps) => (\n  <a\n    aria-current={isActive ? \"page\" : undefined}\n    className={cn(\n      buttonVariants({\n        variant: isActive ? \"outline\" : \"ghost\",\n        size,\n      }),\n      className\n    )}\n    {...props}\n  />\n)\nPaginationLink.displayName = \"PaginationLink\"\n\nconst PaginationPrevious = ({\n  className,\n  ...props\n}: React.ComponentProps<typeof PaginationLink>) => (\n  <PaginationLink\n    aria-label=\"Go to previous page\"\n    size=\"default\"\n    className={cn(\"gap-1 pl-2.5\", className)}\n    {...props}\n  >\n    <ChevronLeft className=\"h-4 w-4\" />\n    <span>Previous</span>\n  </PaginationLink>\n)\nPaginationPrevious.displayName = \"PaginationPrevious\"\n\nconst PaginationNext = ({\n  className,\n  ...props\n}: React.ComponentProps<typeof PaginationLink>) => (\n  <PaginationLink\n    aria-label=\"Go to next page\"\n    size=\"default\"\n    className={cn(\"gap-1 pr-2.5\", className)}\n    {...props}\n  >\n    <span>Next</span>\n    <ChevronRight className=\"h-4 w-4\" />\n  </PaginationLink>\n)\nPaginationNext.displayName = \"PaginationNext\"\n\nconst PaginationEllipsis = ({\n  className,\n  ...props\n}: React.ComponentProps<\"span\">) => (\n  <span\n    aria-hidden\n    className={cn(\"flex h-9 w-9 items-center justify-center\", className)}\n    {...props}\n  >\n    <MoreHorizontal className=\"h-4 w-4\" />\n    <span className=\"sr-only\">More pages</span>\n  </span>\n)\nPaginationEllipsis.displayName = \"PaginationEllipsis\"\n\nexport {\n  Pagination,\n  PaginationContent,\n  PaginationEllipsis,\n  PaginationItem,\n  PaginationLink,\n  PaginationNext,\n  PaginationPrevious,\n}\n\n`;\nexport const popover = `import * as React from \"react\"\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Popover = PopoverPrimitive.Root\n\nconst PopoverTrigger = PopoverPrimitive.Trigger\n\nconst PopoverContent = React.forwardRef<\n  React.ElementRef<typeof PopoverPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = \"center\", sideOffset = 4, ...props }, ref) => (\n  <PopoverPrimitive.Portal>\n    <PopoverPrimitive.Content\n      ref={ref}\n      align={align}\n      sideOffset={sideOffset}\n      className={cn(\n        \"z-50 w-72 rounded-md border border-gray-200 bg-white p-4 text-gray-950 shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n        className\n      )}\n      {...props}\n    />\n  </PopoverPrimitive.Portal>\n))\nPopoverContent.displayName = PopoverPrimitive.Content.displayName\n\nexport { Popover, PopoverTrigger, PopoverContent }\n\n`;\nexport const progress = `import * as React from \"react\"\nimport * as ProgressPrimitive from \"@radix-ui/react-progress\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Progress = React.forwardRef<\n  React.ElementRef<typeof ProgressPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>\n>(({ className, value, ...props }, ref) => (\n  <ProgressPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative h-4 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800\",\n      className\n    )}\n    {...props}\n  >\n    <ProgressPrimitive.Indicator\n      className=\"h-full w-full flex-1 bg-gray-900 transition-all dark:bg-gray-50\"\n      style={{ transform: \\`translateX(-\\${100 - (value || 0)}%)\\` }}\n    />\n  </ProgressPrimitive.Root>\n))\nProgress.displayName = ProgressPrimitive.Root.displayName\n\nexport { Progress }\n`;\nexport const radioGroup = `import * as React from \"react\"\nimport * as RadioGroupPrimitive from \"@radix-ui/react-radio-group\"\nimport { Circle } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst RadioGroup = React.forwardRef<\n  React.ElementRef<typeof RadioGroupPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>\n>(({ className, ...props }, ref) => {\n  return (\n    <RadioGroupPrimitive.Root\n      className={cn(\"grid gap-2\", className)}\n      {...props}\n      ref={ref}\n    />\n  )\n})\nRadioGroup.displayName = RadioGroupPrimitive.Root.displayName\n\nconst RadioGroupItem = React.forwardRef<\n  React.ElementRef<typeof RadioGroupPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>\n>(({ className, ...props }, ref) => {\n  return (\n    <RadioGroupPrimitive.Item\n      ref={ref}\n      className={cn(\n        \"aspect-square h-4 w-4 rounded-full border border-gray-200 dark:border-gray-900 text-gray-900 ring-offset-white focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50  dark:text-gray-50 dark:ring-offset-gray-950 dark:focus-visible:ring-gray-300\",\n        className\n      )}\n      {...props}\n    >\n      <RadioGroupPrimitive.Indicator className=\"flex items-center justify-center\">\n        <Circle className=\"h-2.5 w-2.5 fill-current text-current\" />\n      </RadioGroupPrimitive.Indicator>\n    </RadioGroupPrimitive.Item>\n  )\n})\nRadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName\n\nexport { RadioGroup, RadioGroupItem }\n\n`;\nexport const select = `import * as React from \"react\"\nimport * as SelectPrimitive from \"@radix-ui/react-select\"\nimport { Check, ChevronDown, ChevronUp } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Select = SelectPrimitive.Root\n\nconst SelectGroup = SelectPrimitive.Group\n\nconst SelectValue = SelectPrimitive.Value\n\nconst SelectTrigger = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n  <SelectPrimitive.Trigger\n    ref={ref}\n    className={cn(\n      \"flex h-10 w-full items-center justify-between rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 dark:border-gray-800 dark:bg-gray-950 dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus:ring-gray-300\",\n      className\n    )}\n    {...props}\n  >\n    {children}\n    <SelectPrimitive.Icon asChild>\n      <ChevronDown className=\"h-4 w-4 opacity-50\" />\n    </SelectPrimitive.Icon>\n  </SelectPrimitive.Trigger>\n))\nSelectTrigger.displayName = SelectPrimitive.Trigger.displayName\n\nconst SelectScrollUpButton = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.ScrollUpButton\n    ref={ref}\n    className={cn(\n      \"flex cursor-default items-center justify-center py-1\",\n      className\n    )}\n    {...props}\n  >\n    <ChevronUp className=\"h-4 w-4\" />\n  </SelectPrimitive.ScrollUpButton>\n))\nSelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName\n\nconst SelectScrollDownButton = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.ScrollDownButton\n    ref={ref}\n    className={cn(\n      \"flex cursor-default items-center justify-center py-1\",\n      className\n    )}\n    {...props}\n  >\n    <ChevronDown className=\"h-4 w-4\" />\n  </SelectPrimitive.ScrollDownButton>\n))\nSelectScrollDownButton.displayName =\n  SelectPrimitive.ScrollDownButton.displayName\n\nconst SelectContent = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>\n>(({ className, children, position = \"popper\", ...props }, ref) => (\n  <SelectPrimitive.Portal>\n    <SelectPrimitive.Content\n      ref={ref}\n      className={cn(\n        \"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border border-gray-200 bg-white text-gray-950 shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n        position === \"popper\" &&\n          \"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1\",\n        className\n      )}\n      position={position}\n      {...props}\n    >\n      <SelectScrollUpButton />\n      <SelectPrimitive.Viewport\n        className={cn(\n          \"p-1\",\n          position === \"popper\" &&\n            \"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]\"\n        )}\n      >\n        {children}\n      </SelectPrimitive.Viewport>\n      <SelectScrollDownButton />\n    </SelectPrimitive.Content>\n  </SelectPrimitive.Portal>\n))\nSelectContent.displayName = SelectPrimitive.Content.displayName\n\nconst SelectLabel = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Label>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.Label\n    ref={ref}\n    className={cn(\"py-1.5 pl-8 pr-2 text-sm font-semibold\", className)}\n    {...props}\n  />\n))\nSelectLabel.displayName = SelectPrimitive.Label.displayName\n\nconst SelectItem = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>\n>(({ className, children, ...props }, ref) => (\n  <SelectPrimitive.Item\n    ref={ref}\n    className={cn(\n      \"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-gray-100 focus:text-gray-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:focus:bg-gray-800 dark:focus:text-gray-50\",\n      className\n    )}\n    {...props}\n  >\n    <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n      <SelectPrimitive.ItemIndicator>\n        <Check className=\"h-4 w-4\" />\n      </SelectPrimitive.ItemIndicator>\n    </span>\n\n    <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n  </SelectPrimitive.Item>\n))\nSelectItem.displayName = SelectPrimitive.Item.displayName\n\nconst SelectSeparator = React.forwardRef<\n  React.ElementRef<typeof SelectPrimitive.Separator>,\n  React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n  <SelectPrimitive.Separator\n    ref={ref}\n    className={cn(\"-mx-1 my-1 h-px bg-gray-100 dark:bg-gray-800\", className)}\n    {...props}\n  />\n))\nSelectSeparator.displayName = SelectPrimitive.Separator.displayName\n\nexport {\n  Select,\n  SelectGroup,\n  SelectValue,\n  SelectTrigger,\n  SelectContent,\n  SelectLabel,\n  SelectItem,\n  SelectSeparator,\n  SelectScrollUpButton,\n  SelectScrollDownButton,\n}\n\n`;\nexport const separator = `import * as React from \"react\"\nimport * as SeparatorPrimitive from \"@radix-ui/react-separator\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Separator = React.forwardRef<\n  React.ElementRef<typeof SeparatorPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>\n>(\n  (\n    { className, orientation = \"horizontal\", decorative = true, ...props },\n    ref\n  ) => (\n    <SeparatorPrimitive.Root\n      ref={ref}\n      decorative={decorative}\n      orientation={orientation}\n      className={cn(\n        \"shrink-0 bg-gray-200 dark:bg-gray-800\",\n        orientation === \"horizontal\" ? \"h-[1px] w-full\" : \"h-full w-[1px]\",\n        className\n      )}\n      {...props}\n    />\n  )\n)\nSeparator.displayName = SeparatorPrimitive.Root.displayName\n\nexport { Separator }\n\n`;\nexport const skeleton = `import { cn } from \"../../lib/utils\"\n\nfunction Skeleton({\n  className,\n  ...props\n}: React.HTMLAttributes<HTMLDivElement>) {\n  return (\n    <div\n      className={cn(\"animate-pulse rounded-md bg-gray-100 dark:bg-gray-800\", className)}\n      {...props}\n    />\n  )\n}\n\nexport { Skeleton }\n`;\nexport const slider = `import * as React from \"react\"\nimport * as SliderPrimitive from \"@radix-ui/react-slider\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Slider = React.forwardRef<\n  React.ElementRef<typeof SliderPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>\n>(({ className, ...props }, ref) => (\n  <SliderPrimitive.Root\n    ref={ref}\n    className={cn(\n      \"relative flex w-full touch-none select-none items-center\",\n      className\n    )}\n    {...props}\n  >\n    <SliderPrimitive.Track className=\"relative h-2 w-full grow overflow-hidden rounded-full bg-gray-100 dark:bg-gray-800\">\n      <SliderPrimitive.Range className=\"absolute h-full bg-gray-900 dark:bg-gray-50\" />\n    </SliderPrimitive.Track>\n    <SliderPrimitive.Thumb className=\"block h-5 w-5 rounded-full border-2 border-gray-900 bg-white ring-offset-white transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 dark:border-gray-50 dark:bg-gray-950 dark:ring-offset-gray-950 dark:focus-visible:ring-gray-300\" />\n  </SliderPrimitive.Root>\n))\nSlider.displayName = SliderPrimitive.Root.displayName\n\nexport { Slider }\n\n`;\nexport const switchComponent = `import * as React from \"react\"\nimport * as SwitchPrimitives from \"@radix-ui/react-switch\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Switch = React.forwardRef<\n  React.ElementRef<typeof SwitchPrimitives.Root>,\n  React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>\n>(({ className, ...props }, ref) => (\n  <SwitchPrimitives.Root\n    className={cn(\n      \"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 focus-visible:ring-offset-white disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-gray-900 data-[state=unchecked]:bg-gray-200 dark:focus-visible:ring-gray-300 dark:focus-visible:ring-offset-gray-950 dark:data-[state=checked]:bg-gray-50 dark:data-[state=unchecked]:bg-gray-800\",\n      className\n    )}\n    {...props}\n    ref={ref}\n  >\n    <SwitchPrimitives.Thumb\n      className={cn(\n        \"pointer-events-none block h-5 w-5 rounded-full bg-white shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0 dark:bg-gray-950\"\n      )}\n    />\n  </SwitchPrimitives.Root>\n))\nSwitch.displayName = SwitchPrimitives.Root.displayName\n\nexport { Switch }\n\n`;\nexport const table = `import * as React from \"react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Table = React.forwardRef<\n  HTMLTableElement,\n  React.HTMLAttributes<HTMLTableElement>\n>(({ className, ...props }, ref) => (\n  <div className=\"relative w-full overflow-auto\">\n    <table\n      ref={ref}\n      className={cn(\"w-full caption-bottom text-sm\", className)}\n      {...props}\n    />\n  </div>\n))\nTable.displayName = \"Table\"\n\nconst TableHeader = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <thead ref={ref} className={cn(\"[&_tr]:border-b\", className)} {...props} />\n))\nTableHeader.displayName = \"TableHeader\"\n\nconst TableBody = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <tbody\n    ref={ref}\n    className={cn(\"[&_tr:last-child]:border-0\", className)}\n    {...props}\n  />\n))\nTableBody.displayName = \"TableBody\"\n\nconst TableFooter = React.forwardRef<\n  HTMLTableSectionElement,\n  React.HTMLAttributes<HTMLTableSectionElement>\n>(({ className, ...props }, ref) => (\n  <tfoot\n    ref={ref}\n    className={cn(\n      \"border-t bg-gray-100/50 font-medium [&>tr]:last:border-b-0 dark:bg-gray-800/50\",\n      className\n    )}\n    {...props}\n  />\n))\nTableFooter.displayName = \"TableFooter\"\n\nconst TableRow = React.forwardRef<\n  HTMLTableRowElement,\n  React.HTMLAttributes<HTMLTableRowElement>\n>(({ className, ...props }, ref) => (\n  <tr\n    ref={ref}\n    className={cn(\n      \"border-b transition-colors hover:bg-gray-100/50 data-[state=selected]:bg-gray-100 dark:hover:bg-gray-800/50 dark:data-[state=selected]:bg-gray-800\",\n      className\n    )}\n    {...props}\n  />\n))\nTableRow.displayName = \"TableRow\"\n\nconst TableHead = React.forwardRef<\n  HTMLTableCellElement,\n  React.ThHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n  <th\n    ref={ref}\n    className={cn(\n      \"h-12 px-4 text-left align-middle font-medium text-gray-500 [&:has([role=checkbox])]:pr-0 dark:text-gray-400\",\n      className\n    )}\n    {...props}\n  />\n))\nTableHead.displayName = \"TableHead\"\n\nconst TableCell = React.forwardRef<\n  HTMLTableCellElement,\n  React.TdHTMLAttributes<HTMLTableCellElement>\n>(({ className, ...props }, ref) => (\n  <td\n    ref={ref}\n    className={cn(\"p-4 align-middle [&:has([role=checkbox])]:pr-0\", className)}\n    {...props}\n  />\n))\nTableCell.displayName = \"TableCell\"\n\nconst TableCaption = React.forwardRef<\n  HTMLTableCaptionElement,\n  React.HTMLAttributes<HTMLTableCaptionElement>\n>(({ className, ...props }, ref) => (\n  <caption\n    ref={ref}\n    className={cn(\"mt-4 text-sm text-gray-500 dark:text-gray-400\", className)}\n    {...props}\n  />\n))\nTableCaption.displayName = \"TableCaption\"\n\nexport {\n  Table,\n  TableHeader,\n  TableBody,\n  TableFooter,\n  TableHead,\n  TableRow,\n  TableCell,\n  TableCaption,\n}\n\n`;\nexport const tabs = `import * as React from \"react\"\nimport * as TabsPrimitive from \"@radix-ui/react-tabs\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst Tabs = TabsPrimitive.Root\n\nconst TabsList = React.forwardRef<\n  React.ElementRef<typeof TabsPrimitive.List>,\n  React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>\n>(({ className, ...props }, ref) => (\n  <TabsPrimitive.List\n    ref={ref}\n    className={cn(\n      \"inline-flex h-10 items-center justify-center rounded-md bg-gray-100 p-1 text-gray-500 dark:bg-gray-800 dark:text-gray-400\",\n      className\n    )}\n    {...props}\n  />\n))\nTabsList.displayName = TabsPrimitive.List.displayName\n\nconst TabsTrigger = React.forwardRef<\n  React.ElementRef<typeof TabsPrimitive.Trigger>,\n  React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>\n>(({ className, ...props }, ref) => (\n  <TabsPrimitive.Trigger\n    ref={ref}\n    className={cn(\n      \"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-white data-[state=active]:text-gray-950 data-[state=active]:shadow-sm dark:ring-offset-gray-950 dark:focus-visible:ring-gray-300 dark:data-[state=active]:bg-gray-950 dark:data-[state=active]:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nTabsTrigger.displayName = TabsPrimitive.Trigger.displayName\n\nconst TabsContent = React.forwardRef<\n  React.ElementRef<typeof TabsPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>\n>(({ className, ...props }, ref) => (\n  <TabsPrimitive.Content\n    ref={ref}\n    className={cn(\n      \"mt-2 ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 dark:ring-offset-gray-950 dark:focus-visible:ring-gray-300\",\n      className\n    )}\n    {...props}\n  />\n))\nTabsContent.displayName = TabsPrimitive.Content.displayName\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent }\n\n`;\nexport const textarea = `import * as React from \"react\"\n\nimport { cn } from \"../../lib/utils\"\n\nexport interface TextareaProps\n  extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}\n\nconst Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(\n  ({ className, ...props }, ref) => {\n    return (\n      <textarea\n        className={cn(\n          \"flex min-h-[80px] w-full rounded-md border border-gray-200 bg-white px-3 py-2 text-sm ring-offset-white placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-800 dark:bg-gray-950 dark:ring-offset-gray-950 dark:placeholder:text-gray-400 dark:focus-visible:ring-gray-300\",\n          className\n        )}\n        ref={ref}\n        {...props}\n      />\n    )\n  }\n)\nTextarea.displayName = \"Textarea\"\n\nexport { Textarea }\n\n`;\nexport const toast = `import * as React from \"react\"\nimport * as ToastPrimitives from \"@radix-ui/react-toast\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\nimport { X } from \"lucide-react\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst ToastProvider = ToastPrimitives.Provider\n\nconst ToastViewport = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Viewport>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Viewport\n    ref={ref}\n    className={cn(\n      \"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]\",\n      className\n    )}\n    {...props}\n  />\n))\nToastViewport.displayName = ToastPrimitives.Viewport.displayName\n\nconst toastVariants = cva(\n  \"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border border-gray-200 p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full dark:border-gray-800\",\n  {\n    variants: {\n      variant: {\n        default: \"border bg-white text-gray-950 dark:bg-gray-950 dark:text-gray-50\",\n        destructive:\n          \"destructive group border-red-500 bg-red-500 text-gray-50 dark:border-red-900 dark:bg-red-900 dark:text-gray-50\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n    },\n  }\n)\n\nconst Toast = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Root>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &\n    VariantProps<typeof toastVariants>\n>(({ className, variant, ...props }, ref) => {\n  return (\n    <ToastPrimitives.Root\n      ref={ref}\n      className={cn(toastVariants({ variant }), className)}\n      {...props}\n    />\n  )\n})\nToast.displayName = ToastPrimitives.Root.displayName\n\nconst ToastAction = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Action>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Action\n    ref={ref}\n    className={cn(\n      \"inline-flex h-8 shrink-0 items-center justify-center rounded-md border border-gray-200 bg-transparent px-3 text-sm font-medium ring-offset-white transition-colors hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-gray-100/40 group-[.destructive]:hover:border-red-500/30 group-[.destructive]:hover:bg-red-500 group-[.destructive]:hover:text-gray-50 group-[.destructive]:focus:ring-red-500 dark:border-gray-800 dark:ring-offset-gray-950 dark:hover:bg-gray-800 dark:focus:ring-gray-300 dark:group-[.destructive]:border-gray-800/40 dark:group-[.destructive]:hover:border-red-900/30 dark:group-[.destructive]:hover:bg-red-900 dark:group-[.destructive]:hover:text-gray-50 dark:group-[.destructive]:focus:ring-red-900\",\n      className\n    )}\n    {...props}\n  />\n))\nToastAction.displayName = ToastPrimitives.Action.displayName\n\nconst ToastClose = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Close>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Close\n    ref={ref}\n    className={cn(\n      \"absolute right-2 top-2 rounded-md p-1 text-gray-950/50 opacity-0 transition-opacity hover:text-gray-950 focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600 dark:text-gray-50/50 dark:hover:text-gray-50\",\n      className\n    )}\n    toast-close=\"\"\n    {...props}\n  >\n    <X className=\"h-4 w-4\" />\n  </ToastPrimitives.Close>\n))\nToastClose.displayName = ToastPrimitives.Close.displayName\n\nconst ToastTitle = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Title>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Title\n    ref={ref}\n    className={cn(\"text-sm font-semibold\", className)}\n    {...props}\n  />\n))\nToastTitle.displayName = ToastPrimitives.Title.displayName\n\nconst ToastDescription = React.forwardRef<\n  React.ElementRef<typeof ToastPrimitives.Description>,\n  React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>\n>(({ className, ...props }, ref) => (\n  <ToastPrimitives.Description\n    ref={ref}\n    className={cn(\"text-sm opacity-90\", className)}\n    {...props}\n  />\n))\nToastDescription.displayName = ToastPrimitives.Description.displayName\n\ntype ToastProps = React.ComponentPropsWithoutRef<typeof Toast>\n\ntype ToastActionElement = React.ReactElement<typeof ToastAction>\n\nexport {\n  type ToastProps,\n  type ToastActionElement,\n  ToastProvider,\n  ToastViewport,\n  Toast,\n  ToastTitle,\n  ToastDescription,\n  ToastClose,\n  ToastAction,\n}\n\n`;\nexport const toaster = `import {\n  Toast,\n  ToastClose,\n  ToastDescription,\n  ToastProvider,\n  ToastTitle,\n  ToastViewport,\n} from \"./toast\"\nimport { useToast } from \"./use-toast\"\n\nexport function Toaster() {\n  const { toasts } = useToast()\n\n  return (\n    <ToastProvider>\n      {toasts.map(function ({ id, title, description, action, ...props }) {\n        return (\n          <Toast key={id} {...props}>\n            <div className=\"grid gap-1\">\n              {title && <ToastTitle>{title}</ToastTitle>}\n              {description && (\n                <ToastDescription>{description}</ToastDescription>\n              )}\n            </div>\n            {action}\n            <ToastClose />\n          </Toast>\n        )\n      })}\n      <ToastViewport />\n    </ToastProvider>\n  )\n}\n\n`;\nexport const toggleGroup = `import * as React from \"react\"\nimport * as ToggleGroupPrimitive from \"@radix-ui/react-toggle-group\"\nimport { type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"../../lib/utils\"\nimport { toggleVariants } from \"./toggle\"\n\nconst ToggleGroupContext = React.createContext<\n  VariantProps<typeof toggleVariants>\n>({\n  size: \"default\",\n  variant: \"default\",\n})\n\nconst ToggleGroup = React.forwardRef<\n  React.ElementRef<typeof ToggleGroupPrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &\n    VariantProps<typeof toggleVariants>\n>(({ className, variant, size, children, ...props }, ref) => (\n  <ToggleGroupPrimitive.Root\n    ref={ref}\n    className={cn(\"flex items-center justify-center gap-1\", className)}\n    {...props}\n  >\n    <ToggleGroupContext.Provider value={{ variant, size }}>\n      {children}\n    </ToggleGroupContext.Provider>\n  </ToggleGroupPrimitive.Root>\n))\n\nToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName\n\nconst ToggleGroupItem = React.forwardRef<\n  React.ElementRef<typeof ToggleGroupPrimitive.Item>,\n  React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &\n    VariantProps<typeof toggleVariants>\n>(({ className, children, variant, size, ...props }, ref) => {\n  const context = React.useContext(ToggleGroupContext)\n\n  return (\n    <ToggleGroupPrimitive.Item\n      ref={ref}\n      className={cn(\n        toggleVariants({\n          variant: context.variant || variant,\n          size: context.size || size,\n        }),\n        className\n      )}\n      {...props}\n    >\n      {children}\n    </ToggleGroupPrimitive.Item>\n  )\n})\n\nToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName\n\nexport { ToggleGroup, ToggleGroupItem }\n\n`;\nexport const toggle = `import * as React from \"react\"\nimport * as TogglePrimitive from \"@radix-ui/react-toggle\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst toggleVariants = cva(\n  \"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-white transition-colors hover:bg-gray-100 hover:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-gray-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-gray-100 data-[state=on]:text-gray-900 dark:ring-offset-gray-950 dark:hover:bg-gray-800 dark:hover:text-gray-400 dark:focus-visible:ring-gray-300 dark:data-[state=on]:bg-gray-800 dark:data-[state=on]:text-gray-50\",\n  {\n    variants: {\n      variant: {\n        default: \"bg-transparent\",\n        outline:\n          \"border border-gray-200 bg-transparent hover:bg-gray-100 hover:text-gray-900 dark:border-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-50\",\n      },\n      size: {\n        default: \"h-10 px-3\",\n        sm: \"h-9 px-2.5\",\n        lg: \"h-11 px-5\",\n      },\n    },\n    defaultVariants: {\n      variant: \"default\",\n      size: \"default\",\n    },\n  }\n)\n\nconst Toggle = React.forwardRef<\n  React.ElementRef<typeof TogglePrimitive.Root>,\n  React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &\n    VariantProps<typeof toggleVariants>\n>(({ className, variant, size, ...props }, ref) => (\n  <TogglePrimitive.Root\n    ref={ref}\n    className={cn(toggleVariants({ variant, size, className }))}\n    {...props}\n  />\n))\n\nToggle.displayName = TogglePrimitive.Root.displayName\n\nexport { Toggle, toggleVariants }\n\n`;\nexport const tooltip = `import * as React from \"react\"\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\"\n\nimport { cn } from \"../../lib/utils\"\n\nconst TooltipProvider = TooltipPrimitive.Provider\n\nconst Tooltip = TooltipPrimitive.Root\n\nconst TooltipTrigger = TooltipPrimitive.Trigger\n\nconst TooltipContent = React.forwardRef<\n  React.ElementRef<typeof TooltipPrimitive.Content>,\n  React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n  <TooltipPrimitive.Content\n    ref={ref}\n    sideOffset={sideOffset}\n    className={cn(\n      \"z-50 overflow-hidden rounded-md border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-950 shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 dark:border-gray-800 dark:bg-gray-950 dark:text-gray-50\",\n      className\n    )}\n    {...props}\n  />\n))\nTooltipContent.displayName = TooltipPrimitive.Content.displayName\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }\n\n`;\nexport const useToast = `import * as React from \"react\"\n\nimport type {\n  ToastActionElement,\n  ToastProps,\n} from \"./toast\"\n\nconst TOAST_LIMIT = 1\nconst TOAST_REMOVE_DELAY = 1000000\n\ntype ToasterToast = ToastProps & {\n  id: string\n  title?: React.ReactNode\n  description?: React.ReactNode\n  action?: ToastActionElement\n}\n\nconst actionTypes = {\n  ADD_TOAST: \"ADD_TOAST\",\n  UPDATE_TOAST: \"UPDATE_TOAST\",\n  DISMISS_TOAST: \"DISMISS_TOAST\",\n  REMOVE_TOAST: \"REMOVE_TOAST\",\n} as const\n\nlet count = 0\n\nfunction genId() {\n  count = (count + 1) % Number.MAX_SAFE_INTEGER\n  return count.toString()\n}\n\ntype ActionType = typeof actionTypes\n\ntype Action =\n  | {\n      type: ActionType[\"ADD_TOAST\"]\n      toast: ToasterToast\n    }\n  | {\n      type: ActionType[\"UPDATE_TOAST\"]\n      toast: Partial<ToasterToast>\n    }\n  | {\n      type: ActionType[\"DISMISS_TOAST\"]\n      toastId?: ToasterToast[\"id\"]\n    }\n  | {\n      type: ActionType[\"REMOVE_TOAST\"]\n      toastId?: ToasterToast[\"id\"]\n    }\n\ninterface State {\n  toasts: ToasterToast[]\n}\n\nconst toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()\n\nconst addToRemoveQueue = (toastId: string) => {\n  if (toastTimeouts.has(toastId)) {\n    return\n  }\n\n  const timeout = setTimeout(() => {\n    toastTimeouts.delete(toastId)\n    dispatch({\n      type: \"REMOVE_TOAST\",\n      toastId: toastId,\n    })\n  }, TOAST_REMOVE_DELAY)\n\n  toastTimeouts.set(toastId, timeout)\n}\n\nexport const reducer = (state: State, action: Action): State => {\n  switch (action.type) {\n    case \"ADD_TOAST\":\n      return {\n        ...state,\n        toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),\n      }\n\n    case \"UPDATE_TOAST\":\n      return {\n        ...state,\n        toasts: state.toasts.map((t) =>\n          t.id === action.toast.id ? { ...t, ...action.toast } : t\n        ),\n      }\n\n    case \"DISMISS_TOAST\": {\n      const { toastId } = action\n\n      // ! Side effects ! - This could be extracted into a dismissToast() action,\n      // but I'll keep it here for simplicity\n      if (toastId) {\n        addToRemoveQueue(toastId)\n      } else {\n        state.toasts.forEach((toast) => {\n          addToRemoveQueue(toast.id)\n        })\n      }\n\n      return {\n        ...state,\n        toasts: state.toasts.map((t) =>\n          t.id === toastId || toastId === undefined\n            ? {\n                ...t,\n                open: false,\n              }\n            : t\n        ),\n      }\n    }\n    case \"REMOVE_TOAST\":\n      if (action.toastId === undefined) {\n        return {\n          ...state,\n          toasts: [],\n        }\n      }\n      return {\n        ...state,\n        toasts: state.toasts.filter((t) => t.id !== action.toastId),\n      }\n  }\n}\n\nconst listeners: Array<(state: State) => void> = []\n\nlet memoryState: State = { toasts: [] }\n\nfunction dispatch(action: Action) {\n  memoryState = reducer(memoryState, action)\n  listeners.forEach((listener) => {\n    listener(memoryState)\n  })\n}\n\ntype Toast = Omit<ToasterToast, \"id\">\n\nfunction toast({ ...props }: Toast) {\n  const id = genId()\n\n  const update = (props: ToasterToast) =>\n    dispatch({\n      type: \"UPDATE_TOAST\",\n      toast: { ...props, id },\n    })\n  const dismiss = () => dispatch({ type: \"DISMISS_TOAST\", toastId: id })\n\n  dispatch({\n    type: \"ADD_TOAST\",\n    toast: {\n      ...props,\n      id,\n      open: true,\n      onOpenChange: (open) => {\n        if (!open) dismiss()\n      },\n    },\n  })\n\n  return {\n    id: id,\n    dismiss,\n    update,\n  }\n}\n\nfunction useToast() {\n  const [state, setState] = React.useState<State>(memoryState)\n\n  React.useEffect(() => {\n    listeners.push(setState)\n    return () => {\n      const index = listeners.indexOf(setState)\n      if (index > -1) {\n        listeners.splice(index, 1)\n      }\n    }\n  }, [state])\n\n  return {\n    ...state,\n    toast,\n    dismiss: (toastId?: string) => dispatch({ type: \"DISMISS_TOAST\", toastId }),\n  }\n}\n\nexport { useToast, toast }\n`;\n\nexport const shadcnComponents = {\n  utils: utils,\n  accordian: accordian,\n  alertDialog: alertDialog,\n  alert: alert,\n  avatar: avatar,\n  badge: badge,\n  breadcrumb: breadcrumb,\n  button: button,\n  calendar: calendar,\n  card: card,\n  carousel: carousel,\n  checkbox: checkbox,\n  collapsible: collapsible,\n  dialog: dialog,\n  drawer: drawer,\n  dropdownMenu: dropdownMenu,\n  hoverCard: hoverCard,\n  input: input,\n  label: label,\n  menuBar: menuBar,\n  navigationMenu: navigationMenu,\n  pagination: pagination,\n  popover: popover,\n  progress: progress,\n  radioGroup: radioGroup,\n  select: select,\n  separator: separator,\n  skeleton: skeleton,\n  slider: slider,\n  switchComponent: switchComponent,\n  table: table,\n  tabs: tabs,\n  textarea: textarea,\n  toast: toast,\n  toaster: toaster,\n  toggleGroup: toggleGroup,\n  toggle: toggle,\n  tooltip: tooltip,\n  useToast: useToast,\n};\n\nexport const essentialShadcnComponents = {\n  utils: utils,\n  avatar: avatar,\n  button: button,\n  card: card,\n  checkbox: checkbox,\n  input: input,\n  label: label,\n  radioGroup: radioGroup,\n  select: select,\n  textarea: textarea,\n  // badge: badge,\n  // dialog: dialog,\n  // table: table,\n};\n","import { z } from 'zod';\n\n/**\n * Enum for Permission Types\n */\nexport enum PermissionTypes {\n  /**\n   * Type for Prompt Permissions\n   */\n  PROMPTS = 'PROMPTS',\n  /**\n   * Type for Bookmark Permissions\n   */\n  BOOKMARKS = 'BOOKMARKS',\n  /**\n   * Type for Agent Permissions\n   */\n  AGENTS = 'AGENTS',\n  /**\n   * Type for Memory Permissions\n   */\n  MEMORIES = 'MEMORIES',\n  /**\n   * Type for Multi-Conversation Permissions\n   */\n  MULTI_CONVO = 'MULTI_CONVO',\n  /**\n   * Type for Temporary Chat\n   */\n  TEMPORARY_CHAT = 'TEMPORARY_CHAT',\n  /**\n   * Type for using the \"Run Code\" LC Code Interpreter API feature\n   */\n  RUN_CODE = 'RUN_CODE',\n  /**\n   * Type for using the \"Web Search\" feature\n   */\n  WEB_SEARCH = 'WEB_SEARCH',\n  /**\n   * Type for People Picker Permissions\n   */\n  PEOPLE_PICKER = 'PEOPLE_PICKER',\n  /**\n   * Type for Marketplace Permissions\n   */\n  MARKETPLACE = 'MARKETPLACE',\n  /**\n   * Type for using the \"File Search\" feature\n   */\n  FILE_SEARCH = 'FILE_SEARCH',\n  /**\n   * Type for using the \"File Citations\" feature in agents\n   */\n  FILE_CITATIONS = 'FILE_CITATIONS',\n  /**\n   * Type for MCP Server Permissions\n   */\n  MCP_SERVERS = 'MCP_SERVERS',\n  /**\n   * Type for Remote Agent (API) Permissions\n   */\n  REMOTE_AGENTS = 'REMOTE_AGENTS',\n  /**\n   * Type for Skill Permissions\n   */\n  SKILLS = 'SKILLS',\n  /**\n   * Type for Shared Link Permissions\n   */\n  SHARED_LINKS = 'SHARED_LINKS',\n  /**\n   * Type for Scheduled Chats Permissions\n   */\n  SCHEDULES = 'SCHEDULES',\n}\n\n/**\n * Maps PermissionTypes to their corresponding `interface` config field names.\n * Used to identify which interface fields seed role permissions at startup\n * and must NOT be overridden via DB config (use the role permissions editor instead).\n */\nexport const PERMISSION_TYPE_INTERFACE_FIELDS: Record<PermissionTypes, string> = {\n  [PermissionTypes.PROMPTS]: 'prompts',\n  [PermissionTypes.AGENTS]: 'agents',\n  [PermissionTypes.BOOKMARKS]: 'bookmarks',\n  [PermissionTypes.MEMORIES]: 'memories',\n  [PermissionTypes.MULTI_CONVO]: 'multiConvo',\n  [PermissionTypes.TEMPORARY_CHAT]: 'temporaryChat',\n  [PermissionTypes.RUN_CODE]: 'runCode',\n  [PermissionTypes.WEB_SEARCH]: 'webSearch',\n  [PermissionTypes.FILE_SEARCH]: 'fileSearch',\n  [PermissionTypes.FILE_CITATIONS]: 'fileCitations',\n  [PermissionTypes.PEOPLE_PICKER]: 'peoplePicker',\n  [PermissionTypes.MARKETPLACE]: 'marketplace',\n  [PermissionTypes.MCP_SERVERS]: 'mcpServers',\n  [PermissionTypes.REMOTE_AGENTS]: 'remoteAgents',\n  [PermissionTypes.SKILLS]: 'skills',\n  [PermissionTypes.SHARED_LINKS]: 'sharedLinks',\n  [PermissionTypes.SCHEDULES]: 'schedules',\n};\n\n/** Set of interface config field names that correspond to role permissions. */\nexport const INTERFACE_PERMISSION_FIELDS = new Set(Object.values(PERMISSION_TYPE_INTERFACE_FIELDS));\n\n/**\n * Interface fields that seed a permission (use/create) BUT also carry runtime\n * config that must survive DB/tenant/user overrides. For these, override\n * sanitizers strip only the permission sub-keys (use/create) from the object\n * form and PRESERVE the boolean form — for `schedules`, `interface.schedules: false`\n * is the runtime feature disable that `getLimits` reads, not a permission toggle.\n */\nexport const RUNTIME_CONFIG_INTERFACE_FIELDS = new Set<string>(['schedules']);\n\n/**\n * YAML sub-keys within composite interface permission fields that map to permission bits.\n * When an interface permission field is an object, only these sub-keys are stripped from\n * DB overrides — other sub-keys (like `placeholder`, `trustCheckbox`) are UI-only and pass through.\n *\n * Mapping to Permissions enum:\n *   'use'           → Permissions.USE       (agents, prompts, mcpServers, remoteAgents, marketplace)\n *   'create'        → Permissions.CREATE    (agents, prompts, mcpServers, remoteAgents)\n *   'share'         → Permissions.SHARE     (agents, prompts, mcpServers, remoteAgents)\n *   'public'        → Permissions.SHARE_PUBLIC (agents, prompts, mcpServers, remoteAgents)\n *   'users'         → Permissions.VIEW_USERS   (peoplePicker only)\n *   'groups'        → Permissions.VIEW_GROUPS  (peoplePicker only)\n *   'roles'         → Permissions.VIEW_ROLES   (peoplePicker only)\n *   'configureObo'  → Permissions.CONFIGURE_OBO (mcpServers only)\n */\nexport const PERMISSION_SUB_KEYS = new Set([\n  'use',\n  'create',\n  'share',\n  'public',\n  'users',\n  'groups',\n  'roles',\n  'configureObo',\n]);\n\n/**\n * Enum for Role-Based Access Control Constants\n */\nexport enum Permissions {\n  USE = 'USE',\n  CREATE = 'CREATE',\n  UPDATE = 'UPDATE',\n  READ = 'READ',\n  READ_AUTHOR = 'READ_AUTHOR',\n  SHARE = 'SHARE',\n  /** Can disable if desired */\n  OPT_OUT = 'OPT_OUT',\n  VIEW_USERS = 'VIEW_USERS',\n  VIEW_GROUPS = 'VIEW_GROUPS',\n  VIEW_ROLES = 'VIEW_ROLES',\n  /** Can share resources publicly (with everyone) */\n  SHARE_PUBLIC = 'SHARE_PUBLIC',\n  /**\n   * Can configure MCP server On-Behalf-Of (OBO) token exchange. Gates the\n   * `obo` field on MCP server configs because OBO silently mints and forwards\n   * per-user delegated tokens to whatever URL the server points at.\n   */\n  CONFIGURE_OBO = 'CONFIGURE_OBO',\n}\n\nexport const promptPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n  [Permissions.CREATE]: z.boolean().default(true),\n  [Permissions.SHARE]: z.boolean().default(false),\n  [Permissions.SHARE_PUBLIC]: z.boolean().default(false),\n});\nexport type TPromptPermissions = z.infer<typeof promptPermissionsSchema>;\n\nexport const bookmarkPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TBookmarkPermissions = z.infer<typeof bookmarkPermissionsSchema>;\n\nexport const memoryPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n  [Permissions.CREATE]: z.boolean().default(true),\n  [Permissions.UPDATE]: z.boolean().default(true),\n  [Permissions.READ]: z.boolean().default(true),\n  [Permissions.OPT_OUT]: z.boolean().default(true),\n});\nexport type TMemoryPermissions = z.infer<typeof memoryPermissionsSchema>;\n\nexport const agentPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n  [Permissions.CREATE]: z.boolean().default(true),\n  [Permissions.SHARE]: z.boolean().default(false),\n  [Permissions.SHARE_PUBLIC]: z.boolean().default(false),\n});\nexport type TAgentPermissions = z.infer<typeof agentPermissionsSchema>;\n\nexport const multiConvoPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TMultiConvoPermissions = z.infer<typeof multiConvoPermissionsSchema>;\n\nexport const temporaryChatPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TTemporaryChatPermissions = z.infer<typeof temporaryChatPermissionsSchema>;\n\nexport const runCodePermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TRunCodePermissions = z.infer<typeof runCodePermissionsSchema>;\n\nexport const webSearchPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TWebSearchPermissions = z.infer<typeof webSearchPermissionsSchema>;\n\nexport const peoplePickerPermissionsSchema = z.object({\n  [Permissions.VIEW_USERS]: z.boolean().default(true),\n  [Permissions.VIEW_GROUPS]: z.boolean().default(true),\n  [Permissions.VIEW_ROLES]: z.boolean().default(true),\n});\nexport type TPeoplePickerPermissions = z.infer<typeof peoplePickerPermissionsSchema>;\n\nexport const marketplacePermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(false),\n});\nexport type TMarketplacePermissions = z.infer<typeof marketplacePermissionsSchema>;\n\nexport const fileSearchPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TFileSearchPermissions = z.infer<typeof fileSearchPermissionsSchema>;\n\nexport const fileCitationsPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n});\nexport type TFileCitationsPermissions = z.infer<typeof fileCitationsPermissionsSchema>;\n\nexport const mcpServersPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n  [Permissions.CREATE]: z.boolean().default(true),\n  [Permissions.SHARE]: z.boolean().default(false),\n  [Permissions.SHARE_PUBLIC]: z.boolean().default(false),\n  [Permissions.CONFIGURE_OBO]: z.boolean().default(false),\n});\nexport type TMcpServersPermissions = z.infer<typeof mcpServersPermissionsSchema>;\n\nexport const remoteAgentsPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(false),\n  [Permissions.CREATE]: z.boolean().default(false),\n  [Permissions.SHARE]: z.boolean().default(false),\n  [Permissions.SHARE_PUBLIC]: z.boolean().default(false),\n});\nexport type TRemoteAgentsPermissions = z.infer<typeof remoteAgentsPermissionsSchema>;\n\nexport const skillPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n  [Permissions.CREATE]: z.boolean().default(true),\n  [Permissions.SHARE]: z.boolean().default(false),\n  [Permissions.SHARE_PUBLIC]: z.boolean().default(false),\n});\nexport type TSkillPermissions = z.infer<typeof skillPermissionsSchema>;\n\nexport const schedulesPermissionsSchema = z.object({\n  [Permissions.USE]: z.boolean().default(true),\n  [Permissions.CREATE]: z.boolean().default(true),\n});\nexport type TSchedulesPermissions = z.infer<typeof schedulesPermissionsSchema>;\n\nexport const sharedLinksPermissionsSchema = z.object({\n  [Permissions.CREATE]: z.boolean().default(true),\n  [Permissions.SHARE]: z.boolean().default(true),\n  [Permissions.SHARE_PUBLIC]: z.boolean().default(false),\n});\nexport type TSharedLinksPermissions = z.infer<typeof sharedLinksPermissionsSchema>;\n\n// Define a single permissions schema that holds all permission types.\nexport const permissionsSchema = z.object({\n  [PermissionTypes.PROMPTS]: promptPermissionsSchema,\n  [PermissionTypes.BOOKMARKS]: bookmarkPermissionsSchema,\n  [PermissionTypes.MEMORIES]: memoryPermissionsSchema,\n  [PermissionTypes.AGENTS]: agentPermissionsSchema,\n  [PermissionTypes.MULTI_CONVO]: multiConvoPermissionsSchema,\n  [PermissionTypes.TEMPORARY_CHAT]: temporaryChatPermissionsSchema,\n  [PermissionTypes.RUN_CODE]: runCodePermissionsSchema,\n  [PermissionTypes.WEB_SEARCH]: webSearchPermissionsSchema,\n  [PermissionTypes.PEOPLE_PICKER]: peoplePickerPermissionsSchema,\n  [PermissionTypes.MARKETPLACE]: marketplacePermissionsSchema,\n  [PermissionTypes.FILE_SEARCH]: fileSearchPermissionsSchema,\n  [PermissionTypes.FILE_CITATIONS]: fileCitationsPermissionsSchema,\n  [PermissionTypes.MCP_SERVERS]: mcpServersPermissionsSchema,\n  [PermissionTypes.REMOTE_AGENTS]: remoteAgentsPermissionsSchema,\n  [PermissionTypes.SKILLS]: skillPermissionsSchema,\n  [PermissionTypes.SHARED_LINKS]: sharedLinksPermissionsSchema,\n  [PermissionTypes.SCHEDULES]: schedulesPermissionsSchema,\n});\n","import { z } from 'zod';\nimport {\n  Permissions,\n  PermissionTypes,\n  permissionsSchema,\n  agentPermissionsSchema,\n  promptPermissionsSchema,\n  skillPermissionsSchema,\n  memoryPermissionsSchema,\n  runCodePermissionsSchema,\n  bookmarkPermissionsSchema,\n  webSearchPermissionsSchema,\n  fileSearchPermissionsSchema,\n  multiConvoPermissionsSchema,\n  mcpServersPermissionsSchema,\n  schedulesPermissionsSchema,\n  sharedLinksPermissionsSchema,\n  peoplePickerPermissionsSchema,\n  remoteAgentsPermissionsSchema,\n  temporaryChatPermissionsSchema,\n  fileCitationsPermissionsSchema,\n} from './permissions';\n\n/**\n * Enum for System Defined Roles\n */\nexport enum SystemRoles {\n  /**\n   * The Admin role\n   */\n  ADMIN = 'ADMIN',\n  /**\n   * The default user role\n   */\n  USER = 'USER',\n}\n\nexport const roleSchema = z.object({\n  name: z.string(),\n  permissions: permissionsSchema,\n});\n\nexport type TRole = z.infer<typeof roleSchema>;\n\nconst defaultRolesSchema = z.object({\n  [SystemRoles.ADMIN]: roleSchema.extend({\n    name: z.literal(SystemRoles.ADMIN),\n    permissions: permissionsSchema.extend({\n      [PermissionTypes.PROMPTS]: promptPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.SHARE]: z.boolean().default(true),\n        [Permissions.SHARE_PUBLIC]: z.boolean().default(true),\n      }),\n      [PermissionTypes.BOOKMARKS]: bookmarkPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.MEMORIES]: memoryPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.UPDATE]: z.boolean().default(true),\n        [Permissions.READ]: z.boolean().default(true),\n        [Permissions.OPT_OUT]: z.boolean().default(true),\n      }),\n      [PermissionTypes.AGENTS]: agentPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.SHARE]: z.boolean().default(true),\n        [Permissions.SHARE_PUBLIC]: z.boolean().default(true),\n      }),\n      [PermissionTypes.MULTI_CONVO]: multiConvoPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.TEMPORARY_CHAT]: temporaryChatPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.RUN_CODE]: runCodePermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.WEB_SEARCH]: webSearchPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.PEOPLE_PICKER]: peoplePickerPermissionsSchema.extend({\n        [Permissions.VIEW_USERS]: z.boolean().default(true),\n        [Permissions.VIEW_GROUPS]: z.boolean().default(true),\n        [Permissions.VIEW_ROLES]: z.boolean().default(true),\n      }),\n      [PermissionTypes.MARKETPLACE]: z.object({\n        [Permissions.USE]: z.boolean().default(false),\n      }),\n      [PermissionTypes.FILE_SEARCH]: fileSearchPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.FILE_CITATIONS]: fileCitationsPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n      }),\n      [PermissionTypes.MCP_SERVERS]: mcpServersPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.SHARE]: z.boolean().default(true),\n        [Permissions.SHARE_PUBLIC]: z.boolean().default(true),\n        [Permissions.CONFIGURE_OBO]: z.boolean().default(true),\n      }),\n      [PermissionTypes.REMOTE_AGENTS]: remoteAgentsPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.SHARE]: z.boolean().default(true),\n        [Permissions.SHARE_PUBLIC]: z.boolean().default(true),\n      }),\n      [PermissionTypes.SKILLS]: skillPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.SHARE]: z.boolean().default(true),\n        [Permissions.SHARE_PUBLIC]: z.boolean().default(true),\n      }),\n      [PermissionTypes.SHARED_LINKS]: sharedLinksPermissionsSchema.extend({\n        [Permissions.CREATE]: z.boolean().default(true),\n        [Permissions.SHARE]: z.boolean().default(true),\n        [Permissions.SHARE_PUBLIC]: z.boolean().default(true),\n      }),\n      [PermissionTypes.SCHEDULES]: schedulesPermissionsSchema.extend({\n        [Permissions.USE]: z.boolean().default(true),\n        [Permissions.CREATE]: z.boolean().default(true),\n      }),\n    }),\n  }),\n  [SystemRoles.USER]: roleSchema.extend({\n    name: z.literal(SystemRoles.USER),\n    permissions: permissionsSchema,\n  }),\n});\n\nconst systemRoleSet = new Set(Object.values(SystemRoles).map((r) => r.toUpperCase()));\n\n/** Case-insensitive check for reserved system role names. */\nexport function isSystemRoleName(name: string | undefined | null): boolean {\n  if (!name) {\n    return false;\n  }\n  return systemRoleSet.has(name.toUpperCase());\n}\n\nexport const roleDefaults = defaultRolesSchema.parse({\n  [SystemRoles.ADMIN]: {\n    name: SystemRoles.ADMIN,\n    permissions: {\n      [PermissionTypes.PROMPTS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n      },\n      [PermissionTypes.BOOKMARKS]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.MEMORIES]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.UPDATE]: true,\n        [Permissions.READ]: true,\n        [Permissions.OPT_OUT]: true,\n      },\n      [PermissionTypes.AGENTS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n      },\n      [PermissionTypes.MULTI_CONVO]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.TEMPORARY_CHAT]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.RUN_CODE]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.WEB_SEARCH]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.PEOPLE_PICKER]: {\n        [Permissions.VIEW_USERS]: true,\n        [Permissions.VIEW_GROUPS]: true,\n        [Permissions.VIEW_ROLES]: true,\n      },\n      [PermissionTypes.MARKETPLACE]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.FILE_SEARCH]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.FILE_CITATIONS]: {\n        [Permissions.USE]: true,\n      },\n      [PermissionTypes.MCP_SERVERS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n        [Permissions.CONFIGURE_OBO]: true,\n      },\n      [PermissionTypes.REMOTE_AGENTS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n      },\n      [PermissionTypes.SKILLS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n      },\n      [PermissionTypes.SHARED_LINKS]: {\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n      },\n      [PermissionTypes.SCHEDULES]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n      },\n    },\n  },\n  [SystemRoles.USER]: {\n    name: SystemRoles.USER,\n    permissions: {\n      [PermissionTypes.PROMPTS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: false,\n        [Permissions.SHARE_PUBLIC]: false,\n      },\n      [PermissionTypes.BOOKMARKS]: {},\n      [PermissionTypes.MEMORIES]: {},\n      [PermissionTypes.AGENTS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: false,\n        [Permissions.SHARE_PUBLIC]: false,\n      },\n      [PermissionTypes.MULTI_CONVO]: {},\n      [PermissionTypes.TEMPORARY_CHAT]: {},\n      [PermissionTypes.RUN_CODE]: {},\n      [PermissionTypes.WEB_SEARCH]: {},\n      [PermissionTypes.PEOPLE_PICKER]: {\n        [Permissions.VIEW_USERS]: false,\n        [Permissions.VIEW_GROUPS]: false,\n        [Permissions.VIEW_ROLES]: false,\n      },\n      [PermissionTypes.MARKETPLACE]: {\n        [Permissions.USE]: false,\n      },\n      [PermissionTypes.FILE_SEARCH]: {},\n      [PermissionTypes.FILE_CITATIONS]: {},\n      [PermissionTypes.MCP_SERVERS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: false,\n        [Permissions.SHARE]: false,\n        [Permissions.SHARE_PUBLIC]: false,\n        [Permissions.CONFIGURE_OBO]: false,\n      },\n      [PermissionTypes.REMOTE_AGENTS]: {\n        [Permissions.USE]: false,\n        [Permissions.CREATE]: false,\n        [Permissions.SHARE]: false,\n        [Permissions.SHARE_PUBLIC]: false,\n      },\n      [PermissionTypes.SKILLS]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: false,\n        [Permissions.SHARE_PUBLIC]: false,\n      },\n      [PermissionTypes.SHARED_LINKS]: {\n        [Permissions.CREATE]: true,\n        [Permissions.SHARE]: true,\n        [Permissions.SHARE_PUBLIC]: true,\n      },\n      [PermissionTypes.SCHEDULES]: {\n        [Permissions.USE]: true,\n        [Permissions.CREATE]: true,\n      },\n    },\n  },\n});\n","import type { InfiniteData } from '@tanstack/react-query';\nimport type {\n  TConversationTag,\n  EModelEndpoint,\n  TConversation,\n  TSharedLink,\n  TAttachment,\n  TMessage,\n  TBanner,\n  ReasoningResponseKey,\n  ReasoningParameterFormat,\n} from './schemas';\nimport type {\n  CodeWorkspaceDescriptor,\n  CodeEnvironmentMode,\n  CodeWorkspaceOperation,\n  CodeWorkspaceSelection,\n} from './code/workspace';\nimport type {\n  CodeEnvironmentUserConfigSchema,\n  CodeEnvironmentUserSettings,\n  TAgentsEndpoint,\n} from './config';\nimport type { Agent, EToolResources, StatefulCodeEnvironment } from './types/assistants';\nimport type { CodeApprovalMode } from './code/approval';\nimport type { RefillIntervalUnit } from './balance';\nimport type { SettingDefinition } from './generate';\nimport type { TMinimalFeedback } from './feedback';\nimport type { ContentTypes } from './types/runs';\nimport type { ProviderId } from './providers';\n\nexport * from './schemas';\nexport * from './types/subagents';\n\nexport type TMessages = TMessage[];\n\n/* TODO: Cleanup EndpointOption types */\nexport type TEndpointOption = Pick<\n  TConversation,\n  // Core conversation fields\n  | 'endpoint'\n  | 'endpointType'\n  | 'model'\n  | 'modelLabel'\n  | 'chatGptLabel'\n  | 'promptPrefix'\n  | 'temperature'\n  | 'topP'\n  | 'topK'\n  | 'top_p'\n  | 'frequency_penalty'\n  | 'presence_penalty'\n  | 'maxOutputTokens'\n  | 'maxContextTokens'\n  | 'max_tokens'\n  | 'maxTokens'\n  | 'resendFiles'\n  | 'imageDetail'\n  | 'reasoning_effort'\n  | 'verbosity'\n  | 'instructions'\n  | 'additional_instructions'\n  | 'append_current_datetime'\n  | 'tools'\n  | 'stop'\n  | 'region'\n  | 'additionalModelRequestFields'\n  // Anthropic-specific\n  | 'promptCache'\n  | 'promptCacheTtl'\n  | 'thinking'\n  | 'thinkingBudget'\n  | 'thinkingLevel'\n  | 'effort'\n  | 'thinkingDisplay'\n  // Assistant/Agent fields\n  | 'assistant_id'\n  | 'agent_id'\n  // UI/Display fields\n  | 'iconURL'\n  | 'greeting'\n  | 'spec'\n  // Artifacts\n  | 'artifacts'\n  // Files\n  | 'file_ids'\n  // System field\n  | 'system'\n  | 'chatProjectId'\n  // Google examples\n  | 'examples'\n  // Context\n  | 'context'\n> & {\n  // Fields specific to endpoint options that don't exist on TConversation\n  modelDisplayLabel?: string;\n  key?: string | null;\n  /** @deprecated Assistants API */\n  thread_id?: string;\n  // Conversation identifiers for multi-response streams\n  overrideConvoId?: string;\n  overrideUserMessageId?: string;\n  // Model parameters (used by different endpoints)\n  modelOptions?: Record<string, unknown>;\n  model_parameters?: Record<string, unknown>;\n  // Configuration data (added by middleware)\n  modelsConfig?: TModelsConfig;\n  // File attachments (processed by middleware)\n  attachments?: TAttachment[];\n  // Generated prompts\n  artifactsPrompt?: string;\n  // Agent-specific fields\n  agent?: Promise<Agent>;\n  // Client-specific options\n  clientOptions?: Record<string, unknown>;\n};\n\nexport type TEphemeralAgent = {\n  mcp?: string[];\n  web_search?: boolean;\n  file_search?: boolean;\n  execute_code?: boolean;\n  artifacts?: string;\n  skills?: boolean;\n  memory?: boolean;\n  /** Equip the ephemeral agent with the `ask_user_question` HITL tool. */\n  ask_user_question?: boolean;\n  /**\n   * Let the model dispatch this ephemeral agent's eligible tool calls in the\n   * background (poll results via `check_background_task`). Requires the\n   * `run_in_background` agent capability to be enabled by the admin.\n   */\n  run_in_background?: boolean;\n  /**\n   * Inject the `intent` label param into this ephemeral agent's eligible\n   * tools so each call streams a live status label. Requires the\n   * `tool_intents` agent capability to be enabled by the admin.\n   */\n  describe_intent?: boolean;\n};\n\nexport type TPayload = Partial<TMessage> &\n  Partial<TEndpointOption> & {\n    isContinued: boolean;\n    isRegenerate?: boolean;\n    /** Manual context compaction: summarize the branch up to `parentMessageId`\n     *  and end without a reply. No user message is created. */\n    compact?: boolean;\n    conversationId: string | null;\n    messages?: TMessages;\n    isTemporary: boolean;\n    ephemeralAgent?: TEphemeralAgent | null;\n    editedContent?: TEditedContent | null;\n    /** Added conversation for multi-convo feature */\n    addedConvo?: TConversation;\n    /**\n     * Skills the user selected via the `$` popover for this turn. Names, not IDs\n     * — the backend resolves them against the user's ACL-accessible skill set,\n     * loads each SKILL.md body, and prepends one meta user message per skill\n     * before the LLM turn runs.\n     */\n    manualSkills?: string[];\n    /** Conversation-scoped preference for code tool approval behavior. */\n    codeApprovalMode?: CodeApprovalMode;\n    /** Immutable conversation choice for attached code execution. */\n    codeEnvironmentMode?: CodeEnvironmentMode;\n    /** Conversation-selected workspaces, with at most one binding per environment. */\n    codeWorkspaces?: CodeWorkspaceSelection[];\n    /** Browser IANA timezone (e.g. `America/New_York`) used to resolve local-time prompt variables server-side. */\n    timezone?: string;\n    /**\n     * Stable per-submission idempotency key (uuid) generated once per `ask()`. Identical\n     * across the client's start-generation network retries, unique per user action (including\n     * regenerate). The server dedups retried start requests on it so a lost/reset response\n     * cannot trigger a second billed generation.\n     */\n    clientRequestId?: string;\n    /** Parked steer source consumed only after this new turn's user message is\n     * durably saved. Separate from `clientRequestId`, which identifies one\n     * generation attempt and must rotate after a failed recovery. */\n    recoverySteerId?: string;\n    /** Optional optimistic-serialization fence for a queued follow-up. The\n     * server may create only if this observed predecessor is still current or\n     * the conversation is still idle after its cleanup. */\n    expectedPredecessorCreatedAt?: number;\n  };\n\nexport type TEditedContent =\n  | {\n      index: number;\n      type: ContentTypes.THINK;\n      [ContentTypes.THINK]: string;\n    }\n  | {\n      index: number;\n      type: ContentTypes.TEXT;\n      [ContentTypes.TEXT]: string;\n    };\n\nexport type TSubmission = {\n  userMessage: TMessage;\n  isEdited?: boolean;\n  isContinued?: boolean;\n  isTemporary: boolean;\n  messages: TMessage[];\n  /** Client-only full message context used to restore branch siblings after scoped regenerate. */\n  regenerateMessages?: TMessage[];\n  isRegenerate?: boolean;\n  /** Manual context compaction; shaped like a regenerate on the client (no new\n   *  user bubble) and sent to the server as a summarize-only turn. */\n  compact?: boolean;\n  initialResponse?: TMessage;\n  conversation: Partial<TConversation>;\n  endpointOption: TEndpointOption;\n  clientTimestamp?: string;\n  ephemeralAgent?: TEphemeralAgent | null;\n  editedContent?: TEditedContent | null;\n  /**\n   * Length of the retained content prefix for an edited resubmission, captured\n   * when the submission is built.\n   *\n   * The server indexes only NEW content, so the client offsets incoming\n   * indices by the prefix it kept. `initialResponse.content` cannot be used\n   * for that after a reconnect: the resume sync overwrites it with the\n   * server's completion-local snapshot, whose length is unrelated to the\n   * prefix. Recording the length up front keeps the offset stable across\n   * resumes for run steps and activity labels alike.\n   */\n  editPrefixLength?: number;\n  /** True once server index 0 text/reasoning actually merged into the retained tail. */\n  editPrefixFirstPartFolded?: boolean;\n  /**\n   * Set once a resume SYNC has replaced the response's retained prefix with\n   * the server's completion-local snapshot. From that point the prefix is\n   * gone from the rendered message and server indices are absolute in the\n   * new space, so {@link editPrefixLength} must NOT be applied — by run\n   * steps or by activity labels. Both event paths read this flag so a\n   * batch's tool cards and its header always land in one index space.\n   *\n   * Stamped per event by the resumable transport, which owns the SYNC\n   * boundary; the non-resumable path never sets it.\n   */\n  editPrefixCleared?: boolean;\n  /** Added conversation for multi-convo feature */\n  addedConvo?: TConversation;\n  /** Skills the user invoked via the `$` popover for this submission. */\n  manualSkills?: string[];\n  /** Conversation-scoped preference for code tool approval behavior. */\n  codeApprovalMode?: CodeApprovalMode;\n  /** Immutable conversation choice for attached code execution. */\n  codeEnvironmentMode?: CodeEnvironmentMode;\n  /** Conversation-selected workspaces, with at most one binding per environment. */\n  codeWorkspaces?: CodeWorkspaceSelection[];\n  /** Stable per-submission idempotency key (uuid) forwarded to the server to dedup retried start-generation requests. */\n  clientRequestId?: string;\n  /** Client-only carry-through for a receipt-bound queued recovery. */\n  recoverySteerId?: string;\n  expectedPredecessorCreatedAt?: number;\n  /** Opaque client-only queue restoration metadata; intentionally omitted by\n   * `createPayload`. */\n  queuedMessageOrigin?: unknown;\n};\n\nexport type EventSubmission = Omit<TSubmission, 'initialResponse'> & { initialResponse: TMessage };\n\nexport type TPluginAction = {\n  pluginKey: string;\n  action: 'install' | 'uninstall';\n  auth?: Partial<Record<string, string>> | null;\n  isEntityTool?: boolean;\n};\n\nexport type GroupedConversations = [key: string, TConversation[]][];\n\nexport type TUpdateUserPlugins = {\n  isEntityTool?: boolean;\n  pluginKey: string;\n  action: string;\n  auth?: Partial<Record<string, string | null>> | null;\n};\n\n// TODO `label` needs to be changed to the proper `TranslationKeys`\nexport type TCategory = {\n  id?: string;\n  value: string;\n  label: string;\n  description?: string;\n  custom?: boolean;\n};\n\nexport type TMarketplaceCategory = TCategory & {\n  count: number;\n};\n\nexport type TError = {\n  message: string;\n  code?: number | string;\n  file_id?: string;\n  tool_resource?: EToolResources;\n  response?: {\n    data?: {\n      message?: string;\n    };\n    status?: number;\n  };\n};\n\nexport type TBackupCode = {\n  codeHash: string;\n  used: boolean;\n  usedAt: Date | null;\n};\n\nexport type TUser = {\n  id: string;\n  username: string;\n  email: string;\n  name: string;\n  avatar: string;\n  role: string;\n  provider: string;\n  tenantId?: string;\n  plugins?: string[];\n  twoFactorEnabled?: boolean;\n  backupCodes?: TBackupCode[];\n  personalization?: {\n    memories?: boolean;\n    statefulCodeEnvironment?: StatefulCodeEnvironment;\n  };\n  createdAt: string;\n  updatedAt: string;\n};\n\nexport type TUpdateUserPreferencesRequest = {\n  statefulCodeEnvironment: StatefulCodeEnvironment;\n};\n\nexport type TUpdateUserPreferencesResponse = {\n  updated: boolean;\n  preferences: TUpdateUserPreferencesRequest;\n};\n\nexport type TGetConversationsResponse = {\n  conversations: TConversation[];\n  pageNumber: string;\n  pageSize: string | number;\n  pages: string | number;\n};\n\nexport type TUpdateMessageRequest = {\n  conversationId: string;\n  messageId: string;\n  model: string;\n  text: string;\n};\n\nexport type TUpdateMessageContent = {\n  conversationId: string;\n  messageId: string;\n  index: number;\n  text: string;\n};\n\nexport type TUpdateUserKeyRequest = {\n  name: string;\n  value: string;\n  expiresAt: string;\n};\n\nexport type TAgentApiKeyCreateRequest = {\n  name: string;\n  expiresAt?: string | null;\n};\n\nexport type TAgentApiKeyCreateResponse = {\n  id: string;\n  name: string;\n  key: string;\n  keyPrefix: string;\n  createdAt: string;\n  expiresAt?: string;\n};\n\nexport type TAgentApiKeyListItem = {\n  id: string;\n  name: string;\n  keyPrefix: string;\n  lastUsedAt?: string;\n  expiresAt?: string;\n  createdAt: string;\n};\n\nexport type TAgentApiKeyListResponse = {\n  keys: TAgentApiKeyListItem[];\n};\n\nexport type TUpdateConversationRequest = {\n  conversationId: string;\n  title: string;\n};\n\nexport type TUpdateConversationResponse = TConversation;\n\nexport type TChatProject = {\n  _id: string;\n  name: string;\n  description?: string;\n  user?: string;\n  conversationCount: number;\n  lastConversationAt?: string | null;\n  lastConversationId?: string | null;\n  createdAt: string;\n  updatedAt: string;\n};\n\nexport type TCreateChatProjectRequest = {\n  name: string;\n  description?: string;\n};\n\nexport type TUpdateChatProjectRequest = Partial<TCreateChatProjectRequest> & {\n  projectId: string;\n};\n\nexport type TDeleteChatProjectResponse = {\n  deletedCount: number;\n  modifiedCount: number;\n};\n\nexport type TAssignConversationToProjectRequest = {\n  conversationId: string;\n  projectId: string | null;\n};\n\nexport type TAssignConversationToProjectResponse = {\n  conversation: TConversation;\n  previousProjectId: string | null;\n  projectId: string | null;\n};\n\nexport type TDeleteConversationRequest = {\n  conversationId?: string;\n  thread_id?: string;\n  endpoint?: string;\n  source?: string;\n};\n\nexport type TDeleteConversationResponse = {\n  acknowledged: boolean;\n  deletedCount: number;\n  messages: {\n    acknowledged: boolean;\n    deletedCount: number;\n  };\n};\n\nexport type TArchiveConversationRequest = {\n  conversationId: string;\n  isArchived: boolean;\n};\n\nexport type TArchiveConversationResponse = TConversation;\n\nexport type TArchiveAllConversationsResponse = {\n  archivedCount: number;\n};\n\nexport type TPinConversationRequest = {\n  conversationId: string;\n  pinned: boolean;\n};\n\nexport type TPinConversationResponse = TConversation;\n\nexport type TSharedMessagesResponse = Omit<TSharedLink, 'messages'> & {\n  messages: TMessage[];\n  langfuseSessionUrl?: string;\n};\n\nexport type TCreateShareLinkRequest = Pick<TConversation, 'conversationId'>;\n\nexport type TUpdateShareLinkRequest = Pick<TSharedLink, 'shareId' | 'targetMessageId'>;\n\nexport type TSharedLinkResponse = Pick<TSharedLink, 'shareId'> &\n  Pick<TSharedLink, 'targetMessageId'> &\n  Pick<TConversation, 'conversationId'> & {\n    _id?: string;\n  };\n\nexport type TSharedLinkGetResponse = Omit<TSharedLinkResponse, 'shareId'> & {\n  shareId: string | null;\n  success: boolean;\n  /** Per-link \"share files\" choice; absent on legacy links (treated as enabled). */\n  snapshotFiles?: boolean;\n};\n\n// type for getting conversation tags\nexport type TConversationTagsResponse = TConversationTag[];\n// type for creating conversation tag\nexport type TConversationTagRequest = Partial<\n  Omit<TConversationTag, 'createdAt' | 'updatedAt' | 'count' | 'user'>\n> & {\n  conversationId?: string;\n  addToConversation?: boolean;\n};\n\nexport type TConversationTagResponse = TConversationTag;\n\nexport type TTagConversationRequest = {\n  tags: string[];\n  tag: string;\n};\n\nexport type TTagConversationResponse = string[];\n\nexport type TDuplicateConvoRequest = {\n  conversationId?: string;\n};\n\nexport type TDuplicateConvoResponse = {\n  conversation: TConversation;\n  messages: TMessage[];\n};\n\nexport type TForkConvoRequest = {\n  messageId: string;\n  conversationId: string;\n  option?: string;\n  splitAtTarget?: boolean;\n  latestMessageId?: string;\n};\n\nexport type TForkConvoResponse = {\n  conversation: TConversation;\n  messages: TMessage[];\n};\n\nexport type TForkSharedConvoRequest = {\n  shareId: string;\n  /** Index of the viewer's active message within the shared payload; reduces the\n   *  fork to that branch. An index is used because shared ids are re-anonymized\n   *  per request and `createdAt` can collide, while the payload order is stable. */\n  targetMessageIndex?: number;\n  /** `updatedAt` of the shared payload being forked. The shareId survives an\n   *  owner update, so the server rejects a fork whose payload has since moved\n   *  instead of resolving the index against different messages. */\n  shareRevision?: string;\n};\n\nexport type TSearchResults = {\n  conversations: TConversation[];\n  messages: TMessage[];\n  pageNumber: string;\n  pageSize: string | number;\n  pages: string | number;\n  filter: object;\n};\n\nexport type TPublicCodeEnvironment = {\n  id: string;\n  name: string;\n  type: 'managed' | 'attached';\n  default?: boolean;\n  pairingAvailable?: boolean;\n  configSchema?: CodeEnvironmentUserConfigSchema;\n  settings?: CodeEnvironmentUserSettings;\n};\n\nexport type TCodeEnvironmentSummary = {\n  resourceId: string;\n  id: string;\n  name: string;\n  type: 'managed' | 'attached';\n  canEdit?: boolean;\n  canDelete: boolean;\n  configSchema?: CodeEnvironmentUserConfigSchema;\n  settings?: CodeEnvironmentUserSettings;\n};\n\nexport type TCodeControlPlane = {\n  id: string;\n  name: string;\n  configSchema?: CodeEnvironmentUserConfigSchema;\n};\n\nexport type TCodeEnvironmentsResponse = {\n  environments: TCodeEnvironmentSummary[];\n  controlPlanes: TCodeControlPlane[];\n};\n\nexport type TCodeEnvironmentPairingResponse = {\n  environment: TCodeEnvironmentSummary;\n  pairing: {\n    workerId: string;\n    code: string;\n    expiresAt: string;\n    endpoint: string;\n  };\n};\n\nexport type TCodeEnvironmentStatusResponse = {\n  environmentId: string;\n  status: 'offline' | 'starting' | 'ready';\n  statefulWorkspace?: boolean;\n  leaseExpiresInMs?: number;\n  sandboxProfile?: string;\n  runtimes?: string[];\n  operations?: CodeWorkspaceOperation[];\n  workspaces?: CodeWorkspaceDescriptor[];\n};\n\nexport type TConfig = {\n  order: number;\n  type?: EModelEndpoint;\n  azure?: boolean;\n  availableTools?: [];\n  availableRegions?: string[];\n  allowedProviders?: (string | EModelEndpoint)[];\n  plugins?: Record<string, string>;\n  name?: string;\n  iconURL?: string;\n  /** Canonical provider identity resolved at config load, used for branding. */\n  providerId?: ProviderId;\n  version?: string;\n  modelDisplayLabel?: string;\n  userProvide?: boolean | null;\n  userProvideURL?: boolean | null;\n  userProvideAccessKeyId?: boolean;\n  userProvideSecretAccessKey?: boolean;\n  userProvideSessionToken?: boolean;\n  userProvideBearerToken?: boolean;\n  disableBuilder?: boolean;\n  retrievalModels?: string[];\n  capabilities?: string[];\n  statefulCodeSessions?: {\n    allowedEnvironments: StatefulCodeEnvironment[];\n    environments?: TPublicCodeEnvironment[];\n    approvalsEnabled?: boolean;\n    /** Approval modes the endpoint policy permits the client to offer. */\n    approvalModes?: CodeApprovalMode[];\n  };\n  /** Effective subagents-per-agent cap served from `endpoints.agents.maxSubagents`. */\n  maxSubagents?: number;\n  fileSharing?: TAgentsEndpoint['fileSharing'];\n  /** Concurrent Code API uploads allowed per route and authenticated principal. */\n  codeApiUploadConcurrency?: number;\n  /** Milliseconds one operation may spend waiting on Code API rate limits. */\n  codeApiMaxRetryWaitMs?: number;\n  customParams?: {\n    defaultParamsEndpoint?: string;\n    reasoningFormat?: ReasoningParameterFormat;\n    reasoningKey?: ReasoningResponseKey;\n    includeReasoningContent?: boolean;\n    includeReasoningHistory?: boolean;\n    paramDefinitions?: Partial<SettingDefinition>[];\n  };\n};\n\nexport type TEndpointsConfig =\n  | Record<EModelEndpoint | string, TConfig | null | undefined>\n  | undefined;\n\nexport type TModelsConfig = Record<string, string[]>;\n\n/** Server-resolved context window and pricing for one model. Rates are USD per 1M tokens. */\nexport type TModelTokenomics = {\n  context?: number;\n  prompt?: number;\n  completion?: number;\n  cacheWrite?: number;\n  cacheRead?: number;\n};\n\n/** endpoint → model → resolved tokenomics, from GET /api/endpoints/token-config */\nexport type TTokenConfigMap = Record<string, Record<string, TModelTokenomics>>;\n\nexport type TUpdateTokenCountResponse = {\n  count: number;\n};\n\nexport type TMessageTreeNode = object;\n\nexport type TSearchMessage = object;\n\nexport type TSearchMessageTreeNode = object;\n\nexport type TRegisterUserResponse = {\n  message: string;\n};\n\nexport type TRegisterUser = {\n  name: string;\n  email: string;\n  username: string;\n  password: string;\n  confirm_password?: string;\n  token?: string;\n};\n\nexport type TLoginUser = {\n  email: string;\n  password: string;\n  token?: string;\n  backupCode?: string;\n};\n\nexport type TLoginResponse = {\n  token?: string;\n  user?: TUser;\n  twoFAPending?: boolean;\n  tempToken?: string;\n};\n\n/** Shared payload for any operation that requires OTP or backup-code verification. */\nexport type TOTPVerificationPayload = {\n  token?: string;\n  backupCode?: string;\n};\n\nexport type TEnable2FARequest = TOTPVerificationPayload;\n\nexport type TEnable2FAResponse = {\n  otpauthUrl: string;\n  backupCodes: string[];\n  message?: string;\n};\n\nexport type TVerify2FARequest = TOTPVerificationPayload;\n\nexport type TVerify2FAResponse = {\n  message: string;\n};\n\n/** For verifying 2FA during login with a temporary token. */\nexport type TVerify2FATempRequest = TOTPVerificationPayload & {\n  tempToken: string;\n};\n\nexport type TVerify2FATempResponse = {\n  token?: string;\n  user?: TUser;\n  message?: string;\n};\n\nexport type TDisable2FARequest = TOTPVerificationPayload;\n\nexport type TDisable2FAResponse = {\n  message: string;\n};\n\nexport type TRegenerateBackupCodesRequest = TOTPVerificationPayload;\n\nexport type TRegenerateBackupCodesResponse = {\n  message?: string;\n  backupCodes: string[];\n  backupCodesHash: TBackupCode[];\n};\n\nexport type TDeleteUserRequest = TOTPVerificationPayload;\n\nexport type TRequestPasswordReset = {\n  email: string;\n};\n\nexport type TResetPassword = {\n  userId: string;\n  token: string;\n  password: string;\n  confirm_password?: string;\n};\n\nexport type VerifyEmailResponse = { message: string };\n\nexport type TVerifyEmail = {\n  email: string;\n  token: string;\n};\n\nexport type TResendVerificationEmail = Omit<TVerifyEmail, 'token'>;\n\nexport type TRefreshTokenResponse = {\n  token: string;\n  user: TUser;\n};\n\nexport type TCheckUserKeyResponse = {\n  expiresAt: string;\n};\n\nexport type TRequestPasswordResetResponse = {\n  link?: string;\n  message?: string;\n};\n\n/**\n * Represents the response from the import endpoint.\n */\nexport type TImportResponse = {\n  /**\n   * The message associated with the response.\n   */\n  message: string;\n};\n\n/** Prompts */\n\nexport type TPrompt = {\n  groupId: string;\n  author: string;\n  prompt: string;\n  type: 'text' | 'chat';\n  createdAt: string;\n  updatedAt: string;\n  _id?: string;\n};\n\nexport type TPromptGroup = {\n  name: string;\n  numberOfGenerations?: number;\n  command?: string;\n  oneliner?: string;\n  category?: string;\n  productionId?: string | null;\n  productionPrompt?: Pick<TPrompt, 'prompt'> | null;\n  author: string;\n  authorName: string;\n  isPublic?: boolean;\n  createdAt?: Date;\n  updatedAt?: Date;\n  _id?: string;\n};\n\nexport type TCreatePrompt = {\n  prompt: Pick<TPrompt, 'prompt' | 'type'> & { groupId?: string };\n  group?: { name: string; category?: string; oneliner?: string; command?: string };\n};\n\nexport type TCreatePromptRecord = TCreatePrompt & Pick<TPromptGroup, 'author' | 'authorName'>;\n\nexport type TPromptsWithFilterRequest = {\n  groupId: string;\n  tags?: string[];\n  projectId?: string;\n  version?: number;\n};\n\nexport type TPromptGroupsWithFilterRequest = {\n  category: string;\n  pageNumber?: string; // Made optional for cursor-based pagination\n  pageSize?: string | number;\n  limit?: string | number; // For cursor-based pagination\n  cursor?: string; // For cursor-based pagination\n  before?: string | null;\n  after?: string | null;\n  order?: 'asc' | 'desc';\n  name?: string;\n  author?: string;\n};\n\nexport type PromptGroupListResponse = {\n  promptGroups: TPromptGroup[];\n  pageNumber: string;\n  pageSize: string | number;\n  pages: string | number;\n  has_more: boolean; // Added for cursor-based pagination\n  after: string | null; // Added for cursor-based pagination\n};\n\nexport type PromptGroupListData = InfiniteData<PromptGroupListResponse>;\n\nexport type TCreatePromptResponse = {\n  prompt: TPrompt;\n  group?: TPromptGroup;\n};\n\nexport type TUpdatePromptGroupPayload = Partial<TPromptGroup>;\n\nexport type TUpdatePromptGroupVariables = {\n  id: string;\n  payload: TUpdatePromptGroupPayload;\n};\n\nexport type TUpdatePromptGroupResponse = TPromptGroup;\n\nexport type TDeletePromptResponse = {\n  prompt: string;\n  promptGroup?: { message: string; id: string };\n};\n\nexport type TDeletePromptVariables = {\n  _id: string;\n  groupId: string;\n};\n\nexport type TMakePromptProductionResponse = {\n  message: string;\n};\n\nexport type TMakePromptProductionRequest = {\n  id: string;\n  groupId: string;\n  productionPrompt: Pick<TPrompt, 'prompt'>;\n};\n\nexport type TUpdatePromptLabelsRequest = {\n  id: string;\n  payload: {\n    labels: string[];\n  };\n};\n\nexport type TUpdatePromptLabelsResponse = {\n  message: string;\n};\n\nexport type TDeletePromptGroupResponse = TUpdatePromptLabelsResponse;\n\nexport type TDeletePromptGroupRequest = {\n  id: string;\n};\n\nexport type TGetCategoriesResponse = TCategory[];\n\nexport type TGetRandomPromptsResponse = {\n  prompts: TPromptGroup[];\n};\n\nexport type TGetRandomPromptsRequest = {\n  limit: number;\n  skip: number;\n};\n\nexport type TCustomConfigSpeechResponse = { [key: string]: string };\n\nexport type TUserTermsResponse = {\n  termsAccepted: boolean;\n  termsAcceptedAt: Date | string | null;\n};\n\nexport type TAcceptTermsResponse = {\n  message: string;\n  termsAcceptedAt: Date | string;\n};\n\nexport type TBannerResponse = TBanner | null;\n\nexport type TUpdateFeedbackRequest = {\n  feedback?: TMinimalFeedback;\n};\n\nexport type TUpdateFeedbackResponse = {\n  messageId: string;\n  conversationId: string;\n  feedback?: TMinimalFeedback;\n};\n\nexport type TBalanceResponse = {\n  tokenCredits: number;\n  // Automatic refill settings\n  autoRefillEnabled: boolean;\n  refillIntervalValue?: number;\n  refillIntervalUnit?: RefillIntervalUnit;\n  lastRefill?: Date | string;\n  refillAmount?: number;\n};\n\n/* -------------------------------------------------------------------------- */\n/* Skill UI extensions (not yet persisted — phase 2 backend will fill these)  */\n/* -------------------------------------------------------------------------- */\n\n/**\n * @deprecated Superseded by the persisted `userInvocable` /\n * `disableModelInvocation` pair derived from frontmatter. Retained for the\n * transition window so older UI forms and tests still type-check; the\n * backend no longer reads or writes it.\n */\nexport enum InvocationMode {\n  auto = 'auto',\n  manual = 'manual',\n  both = 'both',\n}\n\n/**\n * Node in the filesystem-style skill tree view. Phase 1 derives these from\n * the flat `TSkillFile[]` list; phase 2 will have the backend serve them\n * directly from a persisted folder hierarchy. Kept in the shared types so\n * tree UI helpers can be imported from both client and server.\n */\nexport type TSkillNode = {\n  _id: string;\n  skillId: string;\n  parentId: string | null;\n  type: 'file' | 'folder';\n  name: string;\n  fileId?: string;\n  order: number;\n  author: string;\n  createdAt: string;\n  updatedAt: string;\n};\n\nexport type TSkillTreeResponse = {\n  nodes: TSkillNode[];\n};\n\nexport type TCreateSkillNodeRequest = {\n  type: 'file' | 'folder';\n  name: string;\n  parentId?: string | null;\n  order?: number;\n};\n\nexport type TUpdateSkillNodeRequest = {\n  name?: string;\n  parentId?: string | null;\n  order?: number;\n};\n\nexport type TLangfuseConnectionStatus = {\n  configured: boolean;\n  enabled: boolean;\n  destinations: TLangfuseDestinationOption[];\n  destination?: string;\n  publicKey?: string;\n  secretKeyPreview?: string;\n  updatedAt?: string;\n};\n\nexport type TLangfuseDestinationOption = {\n  key: string;\n  baseUrl: string;\n};\n\nexport type TUpdateLangfuseConnectionRequest = {\n  enabled: boolean;\n  destination: string;\n  publicKey: string;\n  secretKey?: string;\n};\n\nexport type TLangfuseConnectionTestRequest = {\n  destination: string;\n  publicKey: string;\n  secretKey?: string;\n};\n\nexport type TLangfuseConnectionTestErrorCode =\n  | 'invalid_credentials'\n  | 'access_denied'\n  | 'rate_limited'\n  | 'server_error'\n  | 'timeout'\n  | 'unreachable'\n  | 'missing_secret'\n  | 'stored_secret_unavailable'\n  | 'unexpected_response';\n\nexport type TLangfuseConnectionTestResponse =\n  | { success: true }\n  | { success: false; errorCode: TLangfuseConnectionTestErrorCode };\n\nexport type TLangfuseSessionLinkResponse = {\n  url: string | null;\n  /** Opaque identity of the project `url` opens, so a caller can tell whether it holds what it showed. */\n  destinationId?: string;\n};\n","import { z } from 'zod';\n\n/** Cadences the dialog builds from structured pickers (hour, minute, weekday). */\nexport const scheduleStructuredFrequencies = ['hourly', 'daily', 'weekdays', 'weekly'] as const;\nexport type ScheduleStructuredFrequency = (typeof scheduleStructuredFrequencies)[number];\n\nexport const scheduleFrequencies = [...scheduleStructuredFrequencies, 'cron'] as const;\nexport type ScheduleFrequency = (typeof scheduleFrequencies)[number];\n\n/** Bounds a stored expression. Generous for five fields, because each one can hold a\n *  list: an every-minute-of-the-hour cadence spelled out runs past two hundred chars. */\nexport const SCHEDULE_CRON_MAX_LENGTH = 256;\n\nexport const scheduleTargets = ['new'] as const;\nexport type ScheduleTarget = (typeof scheduleTargets)[number];\n\nexport type ScheduleDisabledReason =\n  | 'mcp_reauth_required'\n  | 'mcp_configuration_missing'\n  | 'mcp_permission_denied'\n  | 'too_many_failures'\n  | 'agent_deleted'\n  | 'invalid_schedule'\n  | 'permission_revoked'\n  | 'insufficient_balance'\n  | 'project_deleted'\n  | 'project_required';\n\nexport type ScheduleRunStatus =\n  | 'started'\n  | 'requires_action'\n  | 'success'\n  | 'error'\n  | 'interrupted'\n  | 'skipped_overlap'\n  | 'skipped_balance';\n\nexport const structuredCadenceSchema = z.object({\n  frequency: z.enum(scheduleStructuredFrequencies),\n  hour: z.number().int().min(0).max(23),\n  minute: z.number().int().min(0).max(59),\n  daysOfWeek: z\n    .array(z.number().int().min(0).max(6))\n    .min(1)\n    .max(7)\n    .transform((days) => Array.from(new Set(days)))\n    .optional(),\n});\nexport type TStructuredCadence = z.infer<typeof structuredCadenceSchema>;\n\n/**\n * A raw cron expression carries its own hour and minute, so it cannot share the\n * structured shape: there is no single `hour` for `0 9,17 * * 1-5`. Syntax is\n * validated server-side by croner, the same parser the engine fires from, rather\n * than by a regex that would accept patterns croner then rejects at fire time.\n */\nexport const cronCadenceSchema = z.object({\n  frequency: z.literal('cron'),\n  expression: z.string().trim().min(1).max(SCHEDULE_CRON_MAX_LENGTH),\n});\nexport type TCronCadence = z.infer<typeof cronCadenceSchema>;\n\nexport const scheduleCadenceSchema = z.discriminatedUnion('frequency', [\n  structuredCadenceSchema,\n  cronCadenceSchema,\n]);\nexport type TScheduleCadence = z.infer<typeof scheduleCadenceSchema>;\n\nexport const isCronCadence = (cadence: TScheduleCadence): cadence is TCronCadence =>\n  cadence.frequency === 'cron';\n\nexport const createSchedulePayloadSchema = z.object({\n  name: z.string().trim().min(1).max(256),\n  prompt: z.string().trim().min(1).max(32000),\n  agent_id: z.string().trim().min(1),\n  cadence: scheduleCadenceSchema,\n  timezone: z.string().min(1),\n  target: z.enum(scheduleTargets).default('new'),\n  file_ids: z\n    .array(z.string())\n    .max(10)\n    .transform((ids) => Array.from(new Set(ids)))\n    .optional(),\n  /**\n   * Chat project each run's conversation is filed under. `null` clears the scope.\n   * Ownership is checked server-side at write time and again at every fire, so a\n   * deleted project disables the schedule instead of silently filing runs loose.\n   */\n  chatProjectId: z.string().trim().min(1).nullable().optional(),\n  enabled: z.boolean().default(true),\n  /**\n   * Client-generated key making creation idempotent across retries. Creation commits\n   * the row and arms it in two writes, so a failure between them leaves the client\n   * unable to tell whether anything persisted; retrying blind can produce two recurring\n   * schedules. A retry carrying the same key resolves to the original row instead.\n   * REQUIRED: an optional key preserves the keyless duplicate path for any client\n   * that omits it, which is exactly the failure the key exists to close.\n   */\n  clientRequestId: z.string().trim().min(1).max(128),\n});\nexport type TCreateSchedule = z.infer<typeof createSchedulePayloadSchema>;\n\n/** Idempotency is a property of the CREATE attempt, not of the schedule's config. */\nexport const updateSchedulePayloadSchema = createSchedulePayloadSchema\n  .omit({ clientRequestId: true })\n  .partial()\n  .extend({\n    /**\n     * The configRevision the client's edit was computed from (captured when the\n     * dialog opened). The server fences the update on it, so a concurrent edit\n     * from another tab answers 409 instead of being silently overwritten by a\n     * payload rebuilt from a stale snapshot (cadence is sent whole, so the\n     * server-side fresh-read fence alone cannot detect this).\n     */\n    expectedConfigRevision: z.number().int().min(0).optional(),\n  });\nexport type TUpdateSchedule = z.infer<typeof updateSchedulePayloadSchema>;\n\nexport type TScheduleLastRun = {\n  conversationId?: string;\n  status: ScheduleRunStatus;\n  error?: string;\n  mcp?: ScheduleMCPOutcome[];\n  firedAt: string;\n};\n\nexport type TSchedule = {\n  id: string;\n  user: string;\n  name: string;\n  prompt: string;\n  agent_id: string;\n  cadence: TScheduleCadence;\n  timezone: string;\n  target: ScheduleTarget;\n  file_ids?: string[];\n  chatProjectId?: string | null;\n  enabled: boolean;\n  disabledReason?: ScheduleDisabledReason;\n  nextRunAt?: string;\n  lastRun?: TScheduleLastRun;\n  /**\n   * The occurrences generating right now. Read from their own run rows, not from\n   * `lastRun`, which is projected only when a run settles, pauses or skips and is\n   * deliberately withheld from a run whose schedule was edited mid-flight. This is\n   * the signal a client has that a chat is on its way, and the id to fetch it by.\n   * A run parked on an approval is not here: its chat was listed long ago, and the\n   * rows can accumulate for as long as approvals wait.\n   */\n  inFlight?: Array<{ conversationId: string }>;\n  runCount: number;\n  failureCount: number;\n  configRevision?: number;\n  createdAt: string;\n  updatedAt: string;\n};\n\nexport type TScheduleRun = {\n  mcp?: ScheduleMCPOutcome[];\n  scheduleId: string;\n  scheduledFor: string;\n  firedAt?: string;\n  conversationId?: string;\n  status: ScheduleRunStatus;\n  error?: string;\n  droppedFileIds?: string[];\n  durationMs?: number;\n};\n\n/** Server-resolved policy the dialog must mirror. Sourced from the same\n *  per-principal `interface.schedules` resolution the write handlers and the fire\n *  path enforce, so the form can never offer a choice the server would refuse. */\nexport type TScheduleLimits = {\n  maxPerUser: number;\n  /** Served with the list so the dialog can refuse a cadence the floor would reject\n   *  rather than surfacing it as a 400 after submit. */\n  minIntervalMinutes: number;\n  /** Every schedule must be filed under a chat project. */\n  requireProject: boolean;\n  /** Operator-pinned destination project; when set it is the ONLY destination and\n   *  the client must not offer a picker. */\n  projectId?: string;\n};\n\nexport type TSchedulesResponse = {\n  schedules: TSchedule[];\n  limits: TScheduleLimits;\n};\n\nexport type TScheduleRunNowResponse = {\n  scheduleId: string;\n  conversationId: string;\n  status: 'started';\n};\n\n/** Only structured schedule preflight failures may request immediate suspension. */\nexport function getScheduleMCPDisabledReason(\n  outcomes?: ScheduleMCPOutcome[],\n): 'mcp_reauth_required' | 'mcp_configuration_missing' | 'mcp_permission_denied' | undefined {\n  const statuses = new Set(outcomes?.map((outcome) => outcome.status));\n  if (statuses.has('mcp_permission_denied')) return 'mcp_permission_denied';\n  if (statuses.has('mcp_configuration_missing')) return 'mcp_configuration_missing';\n  if (statuses.has('mcp_reauth_required')) return 'mcp_reauth_required';\n  return undefined;\n}\n\nexport const scheduleMCPOutcomeSchema = z.object({\n  server: z.string(),\n  /** Agent whose selected tool requires this server. Used to open the correct\n   * recovery chat when the requirement belongs to a handoff or subagent. */\n  agentId: z.string().optional(),\n  status: z.enum([\n    'ready',\n    'mcp_reauth_required',\n    'mcp_configuration_missing',\n    'mcp_permission_denied',\n    'mcp_unavailable',\n  ]),\n});\nexport type ScheduleMCPOutcome = z.infer<typeof scheduleMCPOutcomeSchema>;\nexport type ScheduleMCPStatus = ScheduleMCPOutcome['status'];\n\nexport function readScheduleMCPOutcomes(error?: string): ScheduleMCPOutcome[] {\n  if (\n    !error ||\n    !/^mcp_(reauth_required|configuration_missing|permission_denied|unavailable): \\[/.test(error)\n  )\n    return [];\n  try {\n    const result = scheduleMCPOutcomeSchema\n      .array()\n      .safeParse(JSON.parse(error.slice(error.indexOf(': ') + 2)));\n    return result.success ? result.data : [];\n  } catch {\n    return [];\n  }\n}\n","import { Cron } from 'croner';\nimport type { TScheduleCadence } from './types/schedules';\nimport { isCronCadence, SCHEDULE_CRON_MAX_LENGTH } from './types/schedules';\n\n/** Mirrors the server default when a weekly cadence omits `daysOfWeek`. */\nconst WEEKLY_DEFAULT_DAY = 1;\n\n/**\n * Minute, hour, day of month, month, day of week. croner also reads a six-field form\n * carrying seconds and a seven-field form that pins a year, and both are refused.\n * Seconds would promise a precision the runtime does not keep: the engine polls on a\n * thirty-second tick and offsets each schedule by up to two minutes of jitter. A pinned\n * year makes a cadence that runs out, and every caller here treats \"no next occurrence\"\n * as a cadence it cannot read.\n */\nconst CRON_FIELD_COUNT = 5;\n\n/**\n * Spring-forward compresses consecutive wall-clock occurrences, so the ENFORCEABLE\n * minimum for day-and-longer gaps is the nominal gap minus the largest real-world\n * transition: two hours (Antarctica/Troll; every other zone shifts at most one).\n * A floor set exactly at the nominal value would otherwise admit a schedule that\n * genuinely violates it once a year. Hourly gaps are unaffected (the skipped hours\n * lengthen, never shorten, the gap between occurrences).\n */\nconst DST_COMPRESSION_MINUTES = 120;\n\n/**\n * Occurrences sampled when measuring a cron expression's tightest gap. The floor\n * exists to reject expressions that fire too OFTEN, and a dense pattern reveals\n * its short gap within the first few occurrences, so a small window answers the\n * question this guards. Known limit: this is a bounded probe, not the exhaustive\n * proof the structured formulas give. An expression that is sparse for the next\n * `CRON_PROBE_OCCURRENCES` runs and dense later would pass here and be caught by\n * the fire-time recheck instead.\n */\nconst CRON_PROBE_OCCURRENCES = 32;\n\n/** Enough to span four nominal gaps from an anchor two gaps before a transition,\n *  which is what guarantees the straddling pair falls inside the window. */\nconst TRANSITION_PROBE_OCCURRENCES = 5;\n\n/**\n * Compiles a cadence to the cron expression the engine fires from. Shared rather\n * than server-owned because the dialog previews the next runs, validates the\n * interval floor, and disables its own submit from these same functions: a second\n * client-side implementation would drift and either show run times the schedule\n * does not keep or accept a cadence the server then rejects.\n */\nexport function cadenceToCron(cadence: TScheduleCadence): string {\n  if (cadence.frequency === 'cron') {\n    return cadence.expression;\n  }\n  const { frequency, hour, minute } = cadence;\n  if (frequency === 'hourly') {\n    return `${minute} * * * *`;\n  }\n  if (frequency === 'daily') {\n    return `${minute} ${hour} * * *`;\n  }\n  if (frequency === 'weekdays') {\n    return `${minute} ${hour} * * 1-5`;\n  }\n  const days = cadence.daysOfWeek?.length ? cadence.daysOfWeek : [WEEKLY_DEFAULT_DAY];\n  return `${minute} ${hour} * * ${[...days].sort((a, b) => a - b).join(',')}`;\n}\n\n/**\n * Everything `cronCadenceSchema` will accept: exactly five fields, within the length\n * the schema stores, and actually matching at some point. croner accepts syntactically\n * valid patterns that can never match (`0 0 30 2 *`), and those would arm a schedule\n * that never fires. Validated with croner rather than a regex, because a regex would\n * accept patterns croner then rejects at fire time.\n *\n * A five-field expression that matches at all matches forever, which is what lets every\n * caller keep reading \"no next occurrence\" as \"this cadence is unreadable\".\n */\nexport function isValidCronExpression(expression: string, timezone?: string): boolean {\n  const trimmed = expression.trim();\n  if (trimmed.length > SCHEDULE_CRON_MAX_LENGTH) {\n    return false;\n  }\n  if (trimmed.split(/\\s+/).length !== CRON_FIELD_COUNT) {\n    return false;\n  }\n  try {\n    return new Cron(trimmed, { timezone, paused: true }).nextRun() != null;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * The next occurrences the engine would fire. Server-side jitter (up to two\n * minutes) is deliberately not modelled: it is keyed off a schedule id that does\n * not exist yet at create time, and showing 9:01 for a 9:00 schedule reads as a bug.\n */\nexport function nextRunInstants(\n  cadence: TScheduleCadence,\n  timezone: string,\n  count: number,\n): Date[] {\n  try {\n    const runs = new Cron(cadenceToCron(cadence), { timezone, paused: true }).nextRuns(count);\n    // At spring-forward croner folds the skipped wall-clock occurrences onto the\n    // first valid instant, so consecutive entries can repeat (`0 2,3 * * *` in a US\n    // zone yields 03:00 twice on the transition day). Those are one firing, which is\n    // also how the engine's unique-occurrence index counts them; previewing the same\n    // run twice reads as a bug.\n    return runs.filter((run, index) => index === 0 || run.getTime() !== runs[index - 1].getTime());\n  } catch {\n    return [];\n  }\n}\n\nconst MINUTE_MS = 60_000;\nconst DAY_MS = 24 * 60 * MINUTE_MS;\n\n/** A year and a bit, so a zone with a single yearly transition always shows one. */\nconst TRANSITION_SEARCH_DAYS = 400;\n\nconst offsetFormatters = new Map<string, Intl.DateTimeFormat>();\n\n/** Minutes east of UTC in `zone` at `instant`, read back from the wall clock the\n *  zone renders. The only way to observe a zone's offset without a tz database. */\nfunction zoneOffsetMinutes(zone: string, instant: Date): number {\n  let formatter = offsetFormatters.get(zone);\n  if (formatter == null) {\n    formatter = new Intl.DateTimeFormat('en-US', {\n      timeZone: zone,\n      hourCycle: 'h23',\n      year: 'numeric',\n      month: '2-digit',\n      day: '2-digit',\n      hour: '2-digit',\n      minute: '2-digit',\n      second: '2-digit',\n    });\n    offsetFormatters.set(zone, formatter);\n  }\n  const parts: Record<string, string> = {};\n  for (const part of formatter.formatToParts(instant)) {\n    parts[part.type] = part.value;\n  }\n  const wallClock = Date.UTC(\n    Number(parts.year),\n    Number(parts.month) - 1,\n    Number(parts.day),\n    Number(parts.hour),\n    Number(parts.minute),\n    Number(parts.second),\n  );\n  return Math.round((wallClock - instant.getTime()) / MINUTE_MS);\n}\n\n/** Zone transitions are asked for once per fire, and the scan below costs ~10ms.\n *  Keyed by day because that is how far the answer stays put as the window slides,\n *  and cleared wholesale at the cap so a long-lived worker cannot accumulate an\n *  entry per zone per day forever. */\nconst transitionCache = new Map<string, Date[]>();\nconst TRANSITION_CACHE_MAX = 512;\n\n/**\n * Every instant `zone` changes its UTC offset within the search window; empty for a\n * fixed-offset zone. Both directions matter and only one of them shortens anything,\n * so taking just the next one would usually find the harmless fall-back and miss the\n * spring-forward six months behind it. Bracketed a day at a time, bisected to the\n * minute.\n */\nfunction offsetChanges(zone: string, from: Date): Date[] {\n  // Scanned from the keyed DAY BOUNDARY, not from `from` itself. The key already\n  // discards everything below the day, so scanning from the exact instant let one\n  // caller cache a list that omits a transition earlier the same day, and the next\n  // caller that starts before it silently reused it and measured the nominal gap.\n  const day = Math.floor(from.getTime() / DAY_MS);\n  const cacheKey = `${zone}:${day}`;\n  const cached = transitionCache.get(cacheKey);\n  if (cached != null) {\n    return cached;\n  }\n  const changes: Date[] = [];\n  // Starts a day BEFORE the keyed one. Rounding forward to the anchor's own UTC day\n  // excluded a transition on the preceding UTC date, which is where a southern-\n  // hemisphere spring-forward lands: Australia/Sydney turns over at 16:00 UTC the day\n  // before the local date it belongs to, so the gap it compressed went unmeasured.\n  const start = new Date((day - 1) * DAY_MS);\n  let low = start.getTime();\n  let baseOffset = zoneOffsetMinutes(zone, start);\n  const end = low + TRANSITION_SEARCH_DAYS * DAY_MS;\n  for (let probe = low + DAY_MS; probe <= end; probe += DAY_MS) {\n    const offset = zoneOffsetMinutes(zone, new Date(probe));\n    if (offset !== baseOffset) {\n      let high = probe;\n      let bracket = low;\n      while (high - bracket > MINUTE_MS) {\n        const mid = bracket + Math.floor((high - bracket) / 2);\n        if (zoneOffsetMinutes(zone, new Date(mid)) === baseOffset) {\n          bracket = mid;\n        } else {\n          high = mid;\n        }\n      }\n      changes.push(new Date(high));\n      baseOffset = offset;\n    }\n    low = probe;\n  }\n  if (transitionCache.size >= TRANSITION_CACHE_MAX) {\n    transitionCache.clear();\n  }\n  transitionCache.set(cacheKey, changes);\n  return changes;\n}\n\nfunction runsAfter(\n  expression: string,\n  from: Date,\n  zone: string,\n  occurrences: number = CRON_PROBE_OCCURRENCES,\n): Date[] {\n  return new Cron(expression, { timezone: zone, paused: true }).nextRuns(occurrences, from);\n}\n\n/** Tightest gap, in minutes, across `runs`; null when there is no pair to measure. */\nfunction minGapMinutes(runs: Date[]): number | null {\n  if (runs.length < 2) {\n    return null;\n  }\n  let minGapMs = Number.MAX_SAFE_INTEGER;\n  for (let i = 1; i < runs.length; i++) {\n    const gapMs = runs[i].getTime() - runs[i - 1].getTime();\n    // At spring-forward croner folds the wall-clock hours that do not exist onto the\n    // one that replaced them, so the sequence can repeat an instant or step backwards\n    // (Antarctica/Troll skips two hours and reported a gap of -60). Those are one\n    // firing, which is also how the engine's unique-occurrence index counts them;\n    // treating them as gaps reported every hourly cron in a DST zone as unschedulable.\n    // Only non-positive gaps are dropped: a sub-minute gap is real and still floors to 0.\n    if (gapMs <= 0) {\n      continue;\n    }\n    minGapMs = Math.min(minGapMs, gapMs);\n  }\n  if (minGapMs === Number.MAX_SAFE_INTEGER) {\n    return null;\n  }\n  return Math.floor(minGapMs / MINUTE_MS);\n}\n\nfunction probeMinGapMinutes(\n  expression: string,\n  zone: string,\n  from: Date,\n  occurrences: number = CRON_PROBE_OCCURRENCES,\n): number | null {\n  return minGapMinutes(runsAfter(expression, from, zone, occurrences));\n}\n\n/**\n * Smallest gap in minutes between occurrences. Returns 0 for an unparseable or\n * never-matching expression so every floor rejects it, failing closed rather than\n * admitting an expression the engine cannot fire.\n *\n * Measured twice, and the smaller wins:\n *\n * 1. Nominal, probed in UTC, then discounted by the same worst-case DST allowance\n *    the structured branches assume. This keeps `0 9 * * *` reporting exactly what\n *    the Daily preset reports, so the same schedule cannot be admitted in one form\n *    and rejected in the other.\n * 2. Real elapsed time in the schedule's own zone, across each of that zone's\n *    transitions. Spring-forward compresses a gap that straddles one\n *    (`0 0,12 * * *` in America/New_York is 11 hours that day, not 12), and step 1\n *    only discounts gaps of a day or more, so a subdaily gap needs measuring rather\n *    than estimating. Anchoring at the transition is what makes a bounded probe see\n *    it at all: from today it is usually months outside any reasonable window.\n */\nfunction cronIntervalMinutes(expression: string, timezone?: string): number {\n  try {\n    const now = new Date();\n    const nominal = probeMinGapMinutes(expression, 'UTC', now);\n    if (nominal == null) {\n      // The expression can never match at all, so it must fail every floor.\n      return 0;\n    }\n    // Spring-forward can only compress a gap that spans the transition, so the\n    // blanket allowance applies from a day up. Taking it off an hourly gap too\n    // would reject `0 * * * *` against a 60-minute floor while Hourly passed.\n    const estimate = nominal < 24 * 60 ? nominal : Math.max(0, nominal - DST_COMPRESSION_MINUTES);\n    if (timezone == null || estimate === 0) {\n      return estimate;\n    }\n    // Sized off the nominal gap rather than fixed: starting two gaps before the\n    // transition and taking five occurrences spans at least four of them, so the\n    // straddling pair is always inside the window. A fixed one-day anchor with 32\n    // occurrences both overshot a sparse expression and, for a dense one, never\n    // reached the transition at all (32 minutes in, for `* * * * *`).\n    const anchorBackMs = 2 * Math.max(nominal, 1) * MINUTE_MS;\n    let smallest = estimate;\n    for (const transition of offsetChanges(timezone, now)) {\n      const measured = probeMinGapMinutes(\n        expression,\n        timezone,\n        // Clamped forward: the pair straddling a future transition still falls inside\n        // the window, while occurrences already behind the caller stay out of it.\n        new Date(Math.max(now.getTime(), transition.getTime() - anchorBackMs)),\n        TRANSITION_PROBE_OCCURRENCES,\n      );\n      if (measured != null) {\n        smallest = Math.min(smallest, measured);\n      }\n    }\n    return smallest;\n  } catch {\n    return 0;\n  }\n}\n\n/**\n * Minimum minutes between occurrences, for the admin interval floor. `timezone` is\n * the schedule's own; passing it lets the cron branch measure a DST-compressed gap\n * instead of estimating one. The structured branches are zone-independent: their\n * formulas already carry the worst-case allowance.\n */\nexport function cadenceIntervalMinutes(cadence: TScheduleCadence, timezone?: string): number {\n  if (isCronCadence(cadence)) {\n    return cronIntervalMinutes(cadence.expression, timezone);\n  }\n  if (cadence.frequency === 'hourly') {\n    return 60;\n  }\n  if (cadence.frequency === 'daily' || cadence.frequency === 'weekdays') {\n    return 24 * 60 - DST_COMPRESSION_MINUTES;\n  }\n  // Deduped defensively: the payload schema normalizes new writes, but a legacy\n  // stored [1, 1] would otherwise read as a zero-day gap and fail every floor.\n  const days = cadence.daysOfWeek?.length\n    ? Array.from(new Set(cadence.daysOfWeek))\n    : [WEEKLY_DEFAULT_DAY];\n  if (days.length <= 1) {\n    return 7 * 24 * 60 - DST_COMPRESSION_MINUTES;\n  }\n  // The interval floor must reflect the SHORTEST gap between selected days\n  // (incl. the week wrap-around), e.g. [Mon, Tue] fires 24h apart, so it must be\n  // rejected against a >1440-minute floor.\n  const sorted = [...days].sort((a, b) => a - b);\n  let minGapDays = 7;\n  for (let i = 0; i < sorted.length; i++) {\n    const gap = i + 1 < sorted.length ? sorted[i + 1] - sorted[i] : 7 - sorted[i] + sorted[0];\n    minGapDays = Math.min(minGapDays, gap);\n  }\n  return minGapDays * 24 * 60 - DST_COMPRESSION_MINUTES;\n}\n","import type { FileSources } from './files';\n\n/**\n * Shared skill validation constants — the single source of truth for name,\n * description, title, body, and file-path length limits. Mirrored by\n * `packages/data-schemas/src/methods/skill.ts`; whenever those constants\n * change, the DB-side validators MUST be updated to match.\n *\n * Exported from `librechat-data-provider` so both frontend form validators\n * and backend Mongoose pre-save hooks use the same literals.\n */\nexport const SKILL_NAME_MAX_LENGTH = 64;\nexport const SKILL_DESCRIPTION_MAX_LENGTH = 1024;\nexport const SKILL_DESCRIPTION_SHORT_THRESHOLD = 20;\nexport const SKILL_DISPLAY_TITLE_MAX_LENGTH = 128;\nexport const SKILL_BODY_MAX_LENGTH = 100_000;\n\n/**\n * Kebab-case identifier pattern: must start with a lowercase letter or digit,\n * and contain only lowercase letters, digits, and hyphens. Mirrors the\n * backend `SKILL_NAME_PATTERN` in `packages/data-schemas/src/methods/skill.ts`.\n */\nexport const SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\n/**\n * Source of a skill — where its canonical definition came from.\n * `inline` means the skill was authored directly in LibreChat.\n * `deployment` means the skill was loaded from the server's configured\n * deployment skill directory and is not persisted as a Skill document.\n * `github` is populated by admin-configured GitHub skill sync; `notion` is reserved.\n */\nexport type SkillSource = 'inline' | 'deployment' | 'github' | 'notion';\n\n/**\n * Category inferred from a skill file's top-level directory prefix.\n * `script` for `scripts/...`, `reference` for `references/...`, `asset` for `assets/...`,\n * everything else (including root-level files) is `other`.\n */\nexport type SkillFileCategory = 'script' | 'reference' | 'asset' | 'other';\n\n/** Nested object inside a structured frontmatter key. */\nexport type SkillFrontmatterObject = { [key: string]: SkillFrontmatterValue | undefined };\n\n/**\n * Allowed value types inside a skill's YAML frontmatter. Scalars cover the\n * documented keys; nested arrays and objects describe the structured ones\n * (`hooks`, `metadata`, `references`), which real `SKILL.md` files write as a\n * list, a list of objects, or a map.\n *\n * Still no `unknown` or `any`: the payload is JSON-safe by construction, and\n * the server bounds depth, string length and array size when validating it.\n */\nexport type SkillFrontmatterValue =\n  | string\n  | number\n  | boolean\n  | null\n  | SkillFrontmatterValue[]\n  | SkillFrontmatterObject;\n\n/**\n * Structured YAML frontmatter for a skill. All keys are optional on the wire\n * because not every skill document carries a complete frontmatter block —\n * `name` and `description` live as first-class columns on `TSkill` itself,\n * and frontmatter is an extension bag for additional fields like `when-to-use`,\n * `allowed-tools`, etc.\n */\nexport type SkillFrontmatter = {\n  name?: string;\n  description?: string;\n} & Record<string, SkillFrontmatterValue | undefined>;\n\n/**\n * Provenance metadata for skills that originated from an external source\n * (e.g. a GitHub commit SHA or a Notion page id).\n *\n * Populated by external sync workers with upstream identifiers such as source\n * ids, paths, and commit/blob SHAs.\n */\nexport type SkillSourceMetadata =\n  | Record<string, string | number | boolean>\n  | {\n      provider: 'github';\n      sourceId: string;\n      upstreamId: string;\n      owner: string;\n      repo: string;\n      ref: string;\n      skillPath: string;\n      commitSha?: string;\n      skillBlobSha?: string;\n      syncedAt?: string;\n      syncStatus?: 'synced' | 'failed';\n      error?: string;\n    };\n\n/**\n * A non-blocking coaching hint surfaced alongside a successful create/update\n * response. Unlike validation errors (which return 400 and block the write),\n * warnings ride on the 2xx response so the UI can show inline feedback\n * without rejecting the user's input. Example: \"description is too short,\n * Claude may undertrigger this skill\".\n */\nexport type TSkillWarning = {\n  field: string;\n  code: string;\n  message: string;\n  severity: 'warning';\n};\n\n/**\n * API shape for a full skill (returned by GET `/api/skills/:id`).\n *\n * Field semantics:\n * - `name` is the machine-readable kebab-case identifier Claude sees in its\n *   skill manifest. It's what drives triggering and must be stable across\n *   edits. Unique per author+tenant.\n * - `displayTitle` is the human-readable UI label only. NOT sent to Claude,\n *   NOT part of the trigger path — purely cosmetic.\n * - `description` is the \"when to use this skill\" sentence. Highest-leverage\n *   field for trigger accuracy; a short/vague one causes undertriggering.\n * - `frontmatter` is the structured YAML bag minus `name`/`description`\n *   (those live as top-level columns). Known keys receive value validation;\n *   unknown keys are retained and reported as non-blocking warnings.\n * - `source`/`sourceMetadata` identify whether the row is user-authored,\n *   deployment-provided, or mirrored from an external source such as GitHub.\n */\nexport type TSkill = {\n  _id: string;\n  name: string;\n  displayTitle?: string;\n  description: string;\n  body: string;\n  frontmatter?: SkillFrontmatter;\n  category?: string;\n  /**\n   * @deprecated Replaced by the persisted `userInvocable` /\n   * `disableModelInvocation` pair derived from frontmatter. Retained\n   * temporarily so older form code that hasn't migrated still type-checks;\n   * the backend no longer reads or writes it.\n   */\n  invocationMode?: import('../types').InvocationMode;\n  /**\n   * Mirrors the `disable-model-invocation` frontmatter field. `true` means\n   * the model can no longer invoke this skill via the `skill` tool and the\n   * skill is excluded from the catalog injected into the system prompt.\n   * Manual `$` invocation is unaffected.\n   */\n  disableModelInvocation?: boolean;\n  /**\n   * Mirrors the `user-invocable` frontmatter field. `false` hides the skill\n   * from the `$` popover and rejects manual invocation. Defaults to `true`.\n   */\n  userInvocable?: boolean;\n  /**\n   * Skill-declared tool allowlist (mirrors the `allowed-tools` frontmatter\n   * field). When the skill is invoked, these tools are unioned into the\n   * agent's effective tool set for the turn. Tolerant of unknown names —\n   * the runtime intersects against the loaded tool registry, so skills\n   * referencing yet-to-be-implemented tools import without breaking.\n   */\n  allowedTools?: string[];\n  author: string;\n  authorName: string;\n  version: number;\n  source: SkillSource;\n  sourceMetadata?: SkillSourceMetadata;\n  fileCount: number;\n  /**\n   * When `true`, the skill auto-primes into every turn — no user `$` picks\n   * or model discretion required. Surfaced on the list view so the UI can\n   * show a pin badge on rows that apply ambiently.\n   */\n  alwaysApply?: boolean;\n  isPublic?: boolean;\n  tenantId?: string;\n  createdAt: string;\n  updatedAt: string;\n  /**\n   * Present on POST/PATCH responses when the server emitted non-blocking\n   * coaching warnings (e.g. description too short). Never present on GET\n   * responses.\n   */\n  warnings?: TSkillWarning[];\n};\n\n/**\n * Summary shape used in list endpoints — omits `body` and `frontmatter` to keep\n * list payloads small. Callers that need the full body/frontmatter must fetch\n * the detail via `GET /api/skills/:id`.\n */\nexport type TSkillSummary = Omit<TSkill, 'body' | 'frontmatter'>;\n\n/**\n * Metadata for a single file bundled inside a skill.\n * File content itself is fetched separately via the file download endpoint.\n */\nexport type TSkillFile = {\n  _id: string;\n  skillId: string;\n  relativePath: string;\n  file_id: string;\n  filename: string;\n  filepath: string;\n  storageKey?: string;\n  storageRegion?: string;\n  source: FileSources;\n  mimeType: string;\n  bytes: number;\n  category: SkillFileCategory;\n  isExecutable: boolean;\n  author: string;\n  tenantId?: string;\n  sourceMetadata?: Record<string, string | number | boolean>;\n  /** Lazily cached text content (≤ 512 KB). Excluded from list responses. */\n  content?: string;\n  /** Set on first read. `true` prevents repeated storage reads for non-text files. */\n  isBinary?: boolean;\n  createdAt: string;\n  updatedAt: string;\n};\n\nexport type TGitHubSkillSyncCredentialSummary = {\n  provider: 'github';\n  credentialKey: string;\n  credentialPresent: boolean;\n  tokenFingerprint?: string;\n  updatedAt?: string;\n  createdAt?: string;\n};\n\n/** One upstream skill a sync run dropped, with the reason it was dropped. */\nexport type TGitHubSkillSyncSkippedSkill = {\n  path: string;\n  name?: string;\n  errorCode: string;\n  errorMessage: string;\n};\n\n/** One upstream file a sync run published a skill without, and why. */\nexport type TGitHubSkillSyncSkippedFile = {\n  path: string;\n  skillPath: string;\n  errorCode: string;\n  errorMessage: string;\n};\n\nexport type TGitHubSkillSyncSourceStatus = {\n  provider: 'github';\n  sourceId: string;\n  tenantId?: string;\n  /** `partial`: some skills published, others were skipped (see `skippedSkills`). */\n  status: 'idle' | 'running' | 'succeeded' | 'partial' | 'failed' | 'skipped';\n  credentialKey?: string;\n  credentialPresent: boolean;\n  owner?: string;\n  repo?: string;\n  ref?: string;\n  paths?: string[];\n  startedAt?: string;\n  finishedAt?: string;\n  lastSuccessAt?: string;\n  lastFailureAt?: string;\n  errorCode?: string;\n  errorMessage?: string;\n  syncedSkillCount: number;\n  syncedFileCount: number;\n  deletedSkillCount: number;\n  deletedFileCount: number;\n  skippedSkillCount: number;\n  skippedSkills?: TGitHubSkillSyncSkippedSkill[];\n  skippedFileCount: number;\n  skippedFiles?: TGitHubSkillSyncSkippedFile[];\n  updatedAt?: string;\n  createdAt?: string;\n};\n\nexport type TGitHubSkillSyncStatusResponse = {\n  enabled: boolean;\n  intervalMinutes: number;\n  runOnStartup: boolean;\n  sources: TGitHubSkillSyncSourceStatus[];\n  credentials: TGitHubSkillSyncCredentialSummary[];\n  fineGrainedTokenRecommendation: string;\n};\n\nexport type TGitHubSkillSyncCredentialUpdateRequest = {\n  token: string;\n};\n\nexport type TGitHubSkillSyncManualRunResponse = {\n  status: 'started' | 'skipped' | 'completed' | 'failed';\n  message?: string;\n  sources?: TGitHubSkillSyncSourceStatus[];\n};\n\n/** Request body for POST `/api/skills`. */\nexport type TCreateSkill = {\n  name: string;\n  displayTitle?: string;\n  description: string;\n  body: string;\n  frontmatter?: Partial<SkillFrontmatter>;\n  category?: string;\n  /** When `true`, the skill auto-primes into every turn (mirrors always-apply frontmatter). */\n  alwaysApply?: boolean;\n};\n\n/** Partial payload for PATCH `/api/skills/:id` — all fields optional. */\nexport type TUpdateSkillPayload = {\n  name?: string;\n  displayTitle?: string;\n  description?: string;\n  body?: string;\n  frontmatter?: Partial<SkillFrontmatter>;\n  category?: string;\n  alwaysApply?: boolean;\n};\n\n/** Variables passed into the update mutation: id + expectedVersion + partial payload. */\nexport type TUpdateSkillVariables = {\n  id: string;\n  expectedVersion: number;\n  payload: TUpdateSkillPayload;\n};\n\n/** Response from a successful PATCH — includes the bumped version. */\nexport type TUpdateSkillResponse = TSkill;\n\n/** Response from a 409 concurrency conflict — includes the current authoritative state. */\nexport type TSkillConflictResponse = {\n  error: 'skill_version_conflict';\n  current: TSkill;\n};\n\n/** Query params for GET `/api/skills` (list). */\nexport type TSkillListRequest = {\n  category?: string;\n  search?: string;\n  limit?: number;\n  cursor?: string;\n};\n\n/** Paginated list response. `after` is the cursor to pass for the next page. */\nexport type TSkillListResponse = {\n  skills: TSkillSummary[];\n  has_more: boolean;\n  after: string | null;\n};\n\n/** Response from DELETE `/api/skills/:id`. */\nexport type TDeleteSkillResponse = {\n  id: string;\n  deleted: true;\n};\n\n/** Response from GET `/api/skills/:id/files`. */\nexport type TListSkillFilesResponse = {\n  files: TSkillFile[];\n};\n\n/**\n * Upload body for POST `/api/skills/:id/files`.\n * In phase 1 the backend responds with 501; the client contract is still defined here\n * so hooks are stable when the upload pipeline is wired up in phase 2.\n */\nexport type TUploadSkillFilePayload = {\n  relativePath: string;\n};\n\n/** Response from DELETE `/api/skills/:id/files/:relativePath`. */\nexport type TDeleteSkillFileResponse = {\n  skillId: string;\n  relativePath: string;\n  deleted: true;\n};\n\n/** Response from GET `/api/skills/:id/files/:relativePath` (JSON mode). */\nexport type TSkillFileContentResponse = {\n  content?: string;\n  mimeType: string;\n  isBinary: boolean;\n  relativePath: string;\n  filename: string;\n  bytes: number;\n};\n\n/** Variables passed into the skill file upload mutation. */\nexport type TUploadSkillFileVariables = {\n  skillId: string;\n  formData: FormData;\n};\n\n/** Variables passed into the skill file delete mutation. */\nexport type TDeleteSkillFileVariables = {\n  skillId: string;\n  relativePath: string;\n};\n\n/**\n * Per-user skill active/inactive overrides (GET response and POST body payload).\n * Key = skill ObjectId string, value = explicit active state.\n * Skills absent from the map use the ownership-based default:\n * owned = active, shared = `defaultActiveOnShare` from config.\n */\nexport type TSkillStatesResponse = Record<string, boolean>;\n","import type { Logger as WinstonLogger } from 'winston';\nimport type { z } from 'zod';\nimport type { webSearchSchema } from '../config';\n\nexport type SearchRefType = 'search' | 'image' | 'news' | 'video' | 'ref';\n\nexport enum DATE_RANGE {\n  PAST_HOUR = 'h',\n  PAST_24_HOURS = 'd',\n  PAST_WEEK = 'w',\n  PAST_MONTH = 'm',\n  PAST_YEAR = 'y',\n}\n\nexport type SearchProvider = 'serper' | 'searxng' | 'tavily' | 'keenable';\nexport type ScraperProvider = 'firecrawl' | 'serper' | 'tavily' | 'keenable';\nexport type RerankerType = 'infinity' | 'jina' | 'cohere' | 'none';\n\nexport interface Highlight {\n  score: number;\n  text: string;\n  references?: UsedReferences;\n}\n\nexport type ProcessedSource = {\n  content?: string;\n  attribution?: string;\n  references?: References;\n  highlights?: Highlight[];\n  processed?: boolean;\n};\n\nexport type ProcessedOrganic = OrganicResult & ProcessedSource;\nexport type ProcessedTopStory = TopStoryResult & ProcessedSource;\nexport type ValidSource = ProcessedOrganic | ProcessedTopStory;\n\nexport type ResultReference = {\n  link: string;\n  type: 'link' | 'image' | 'video' | 'file';\n  title?: string;\n  attribution?: string;\n};\nexport interface SearchResultData {\n  turn?: number;\n  organic?: ProcessedOrganic[];\n  topStories?: ProcessedTopStory[];\n  images?: ImageResult[];\n  videos?: VideoResult[];\n  places?: PlaceResult[];\n  news?: NewsResult[];\n  shopping?: ShoppingResult[];\n  knowledgeGraph?: KnowledgeGraphResult;\n  answerBox?: AnswerBoxResult;\n  peopleAlsoAsk?: PeopleAlsoAskResult[];\n  relatedSearches?: Array<{ query: string }>;\n  references?: ResultReference[];\n  error?: string;\n}\n\nexport interface SearchResult {\n  data?: SearchResultData;\n  error?: string;\n  success: boolean;\n}\n\nexport interface Source {\n  link: string;\n  html?: string;\n  title?: string;\n  snippet?: string;\n  date?: string;\n}\n\nexport interface SearchConfig {\n  searchProvider?: SearchProvider;\n  serperApiKey?: string;\n  searxngInstanceUrl?: string;\n  searxngApiKey?: string;\n  searxngSearchOptions?: z.infer<typeof webSearchSchema>['searxngSearchOptions'];\n  tavilyApiKey?: string;\n  tavilySearchUrl?: string;\n  tavilySearchOptions?: TavilyConfig['tavilySearchOptions'];\n  keenableApiKey?: string;\n  keenableApiUrl?: string;\n  keenableSearchOptions?: KeenableConfig['keenableSearchOptions'];\n}\n\nexport type References = {\n  links: MediaReference[];\n  images: MediaReference[];\n  videos: MediaReference[];\n};\nexport interface ScrapeResult {\n  url: string;\n  error?: boolean;\n  content: string;\n  attribution?: string;\n  references?: References;\n  highlights?: Highlight[];\n}\n\nexport interface ProcessSourcesConfig {\n  topResults?: number;\n  strategies?: string[];\n  filterContent?: boolean;\n  reranker?: unknown;\n  logger?: Logger;\n}\n\nexport interface FirecrawlConfig {\n  firecrawlApiKey?: string;\n  firecrawlApiUrl?: string;\n  firecrawlOptions?: {\n    formats?: string[];\n    includeTags?: string[];\n    excludeTags?: string[];\n    headers?: Record<string, string>;\n    waitFor?: number;\n    timeout?: number;\n    maxAge?: number;\n    mobile?: boolean;\n    skipTlsVerification?: boolean;\n    blockAds?: boolean;\n    removeBase64Images?: boolean;\n    parsePDF?: boolean;\n    storeInCache?: boolean;\n    zeroDataRetention?: boolean;\n    location?: {\n      country?: string;\n      languages?: string[];\n    };\n    onlyMainContent?: boolean;\n    changeTrackingOptions?: {\n      modes?: string[];\n      schema?: Record<string, unknown>;\n      prompt?: string;\n      tag?: string | null;\n    };\n  };\n}\n\nexport interface TavilyConfig {\n  tavilyApiKey?: string;\n  tavilySearchUrl?: string;\n  tavilyExtractUrl?: string;\n  tavilySearchOptions?: z.infer<typeof webSearchSchema>['tavilySearchOptions'];\n  tavilyScraperOptions?: z.infer<typeof webSearchSchema>['tavilyScraperOptions'];\n}\n\nexport interface KeenableConfig {\n  keenableApiKey?: string;\n  keenableApiUrl?: string;\n  keenableSearchOptions?: z.infer<typeof webSearchSchema>['keenableSearchOptions'];\n  keenableScraperOptions?: z.infer<typeof webSearchSchema>['keenableScraperOptions'];\n}\n\nexport interface ScraperContentResult {\n  content: string;\n}\n\nexport interface ScraperExtractionResult {\n  no_extraction: ScraperContentResult;\n}\n\nexport interface JinaRerankerResult {\n  index: number;\n  relevance_score: number;\n  document?: string | { text: string };\n}\n\nexport interface JinaRerankerResponse {\n  model: string;\n  usage: {\n    total_tokens: number;\n  };\n  results: JinaRerankerResult[];\n}\n\nexport interface CohereRerankerResult {\n  index: number;\n  relevance_score: number;\n}\n\nexport interface CohereRerankerResponse {\n  results: CohereRerankerResult[];\n  id: string;\n  meta: {\n    api_version: {\n      version: string;\n      is_experimental: boolean;\n    };\n    billed_units: {\n      search_units: number;\n    };\n  };\n}\n\nexport type SafeSearchLevel = 0 | 1 | 2;\n\nexport type Logger = WinstonLogger;\nexport interface MediaReference {\n  originalUrl: string;\n  title?: string;\n  text?: string;\n}\n\nexport type UsedReferences = {\n  type: 'link' | 'image' | 'video';\n  originalIndex: number;\n  reference: MediaReference;\n}[];\n\n/** Firecrawl */\n\nexport interface FirecrawlScrapeOptions {\n  formats?: string[];\n  includeTags?: string[];\n  excludeTags?: string[];\n  headers?: Record<string, string>;\n  waitFor?: number;\n  timeout?: number;\n}\n\nexport interface ScrapeMetadata {\n  // Core source information\n  sourceURL?: string;\n  url?: string;\n  scrapeId?: string;\n  statusCode?: number;\n  // Basic metadata\n  title?: string;\n  description?: string;\n  language?: string;\n  favicon?: string;\n  viewport?: string;\n  robots?: string;\n  'theme-color'?: string;\n  // Open Graph metadata\n  'og:url'?: string;\n  'og:title'?: string;\n  'og:description'?: string;\n  'og:type'?: string;\n  'og:image'?: string;\n  'og:image:width'?: string;\n  'og:image:height'?: string;\n  'og:site_name'?: string;\n  ogUrl?: string;\n  ogTitle?: string;\n  ogDescription?: string;\n  ogImage?: string;\n  ogSiteName?: string;\n  // Article metadata\n  'article:author'?: string;\n  'article:published_time'?: string;\n  'article:modified_time'?: string;\n  'article:section'?: string;\n  'article:tag'?: string;\n  'article:publisher'?: string;\n  publishedTime?: string;\n  modifiedTime?: string;\n  // Twitter metadata\n  'twitter:site'?: string | boolean | number | null;\n  'twitter:creator'?: string;\n  'twitter:card'?: string;\n  'twitter:image'?: string;\n  'twitter:dnt'?: string;\n  'twitter:app:name:iphone'?: string;\n  'twitter:app:id:iphone'?: string;\n  'twitter:app:url:iphone'?: string;\n  'twitter:app:name:ipad'?: string;\n  'twitter:app:id:ipad'?: string;\n  'twitter:app:url:ipad'?: string;\n  'twitter:app:name:googleplay'?: string;\n  'twitter:app:id:googleplay'?: string;\n  'twitter:app:url:googleplay'?: string;\n  // Facebook metadata\n  'fb:app_id'?: string;\n  // App links\n  'al:ios:url'?: string;\n  'al:ios:app_name'?: string;\n  'al:ios:app_store_id'?: string;\n  // Allow for additional properties that might be present\n  [key: string]: string | number | boolean | null | undefined;\n}\n\nexport interface FirecrawlScrapeResponse {\n  success: boolean;\n  data?: {\n    markdown?: string;\n    html?: string;\n    rawHtml?: string;\n    screenshot?: string;\n    links?: string[];\n    metadata?: ScrapeMetadata;\n  };\n  error?: string;\n}\n\nexport interface FirecrawlScraperConfig {\n  apiKey?: string;\n  apiUrl?: string;\n  formats?: string[];\n  timeout?: number;\n  logger?: Logger;\n}\n\n/** Serper API */\nexport interface VideoResult {\n  title?: string;\n  link?: string;\n  snippet?: string;\n  imageUrl?: string;\n  duration?: string;\n  source?: string;\n  channel?: string;\n  date?: string;\n  position?: number;\n}\n\nexport interface PlaceResult {\n  position?: number;\n  name?: string;\n  address?: string;\n  latitude?: number;\n  longitude?: number;\n  rating?: number;\n  ratingCount?: number;\n  category?: string;\n  identifier?: string;\n}\n\nexport interface NewsResult {\n  title?: string;\n  link?: string;\n  snippet?: string;\n  date?: string;\n  source?: string;\n  imageUrl?: string;\n  position?: number;\n}\n\nexport interface ShoppingResult {\n  title?: string;\n  source?: string;\n  link?: string;\n  price?: string;\n  delivery?: string;\n  imageUrl?: string;\n  rating?: number;\n  ratingCount?: number;\n  offers?: string;\n  productId?: string;\n  position?: number;\n}\n\nexport interface ScholarResult {\n  title?: string;\n  link?: string;\n  publicationInfo?: string;\n  snippet?: string;\n  year?: number;\n  citedBy?: number;\n}\n\nexport interface ImageResult {\n  title?: string;\n  imageUrl?: string;\n  imageWidth?: number;\n  imageHeight?: number;\n  thumbnailUrl?: string;\n  thumbnailWidth?: number;\n  thumbnailHeight?: number;\n  source?: string;\n  domain?: string;\n  link?: string;\n  googleUrl?: string;\n  position?: number;\n}\n\nexport interface SerperSearchPayload extends SerperSearchInput {\n  /**\n   * Search type/vertical\n   * Options: \"search\" (web), \"images\", \"news\", \"places\", \"videos\"\n   */\n  type?: 'search' | 'images' | 'news' | 'places' | 'videos';\n\n  /**\n   * Starting index for search results pagination (used instead of page)\n   */\n  start?: number;\n\n  /**\n   * Filtering for safe search\n   * Options: \"off\", \"moderate\", \"active\"\n   */\n  safe?: 'off' | 'moderate' | 'active';\n}\n\nexport type SerperSearchParameters = Pick<SerperSearchPayload, 'q' | 'type'> & {\n  engine: 'google';\n};\n\nexport interface OrganicResult {\n  position?: number;\n  title?: string;\n  link: string;\n  snippet?: string;\n  date?: string;\n  sitelinks?: Array<{\n    title: string;\n    link: string;\n  }>;\n}\n\nexport interface TopStoryResult {\n  title?: string;\n  link: string;\n  source?: string;\n  date?: string;\n  imageUrl?: string;\n}\nexport interface KnowledgeGraphResult {\n  title?: string;\n  type?: string;\n  imageUrl?: string;\n  description?: string;\n  descriptionSource?: string;\n  descriptionLink?: string;\n  attributes?: Record<string, string>;\n  website?: string;\n}\n\nexport interface AnswerBoxResult {\n  title?: string;\n  snippet?: string;\n  snippetHighlighted?: string[];\n  link?: string;\n  date?: string;\n}\n\nexport interface PeopleAlsoAskResult {\n  question?: string;\n  snippet?: string;\n  title?: string;\n  link?: string;\n}\n\nexport type RelatedSearches = Array<{ query: string }>;\n\nexport interface SerperSearchInput {\n  /**\n   * The search query string\n   */\n  q: string;\n\n  /**\n   * Country code for localized results\n   * Examples: \"us\", \"uk\", \"ca\", \"de\", etc.\n   */\n  gl?: string;\n\n  /**\n   * Interface language\n   * Examples: \"en\", \"fr\", \"de\", etc.\n   */\n  hl?: string;\n\n  /**\n   * Number of results to return (up to 100)\n   */\n  num?: number;\n  /**\n   * Specific location for contextual results\n   * Example: \"New York, NY\"\n   */\n  location?: string;\n\n  /**\n   * Search autocorrection setting\n   */\n  autocorrect?: boolean;\n  page?: number;\n  /**\n   * Date range for search results\n   * Options: \"h\" (past hour), \"d\" (past 24 hours), \"w\" (past week),\n   * \"m\" (past month), \"y\" (past year)\n   * `qdr:${DATE_RANGE}`\n   */\n  tbs?: string;\n}\n\nexport type SerperResultData = {\n  searchParameters: SerperSearchPayload;\n  organic?: OrganicResult[];\n  topStories?: TopStoryResult[];\n  images?: ImageResult[];\n  videos?: VideoResult[];\n  places?: PlaceResult[];\n  news?: NewsResult[];\n  shopping?: ShoppingResult[];\n  peopleAlsoAsk?: PeopleAlsoAskResult[];\n  relatedSearches?: RelatedSearches;\n  knowledgeGraph?: KnowledgeGraphResult;\n  answerBox?: AnswerBoxResult;\n  credits?: number;\n};\n\n/** SearXNG */\n\nexport interface SearxNGSearchPayload {\n  /**\n   * The search query string\n   * Supports syntax specific to different search engines\n   * Example: \"site:github.com SearXNG\"\n   */\n  q: string;\n\n  /**\n   * Comma-separated list of search categories\n   * Example: \"general,images,news\"\n   */\n  categories?: string;\n\n  /**\n   * Comma-separated list of search engines to use\n   * Example: \"google,bing,duckduckgo\"\n   */\n  engines?: string;\n\n  /**\n   * Code of the language for search results\n   * Example: \"en\", \"fr\", \"de\", \"es\"\n   */\n  language?: string;\n\n  /**\n   * Search page number\n   * Default: 1\n   */\n  pageno?: number;\n\n  /**\n   * Time range filter for search results\n   * Options: \"day\", \"month\", \"year\"\n   */\n  time_range?: 'day' | 'month' | 'year';\n\n  /**\n   * Output format of results\n   * Options: \"json\", \"csv\", \"rss\"\n   */\n  format?: 'json' | 'csv' | 'rss';\n\n  /**\n   * Open search results on new tab\n   * Options: `0` (off), `1` (on)\n   */\n  results_on_new_tab?: 0 | 1;\n\n  /**\n   * Proxy image results through SearxNG\n   * Options: true, false\n   */\n  image_proxy?: boolean;\n\n  /**\n   * Service for autocomplete suggestions\n   * Options: \"google\", \"dbpedia\", \"duckduckgo\", \"mwmbl\",\n   *          \"startpage\", \"wikipedia\", \"stract\", \"swisscows\", \"qwant\"\n   */\n  autocomplete?: string;\n\n  /**\n   * Safe search filtering level\n   * Options: \"0\" (off), \"1\" (moderate), \"2\" (strict)\n   */\n  safesearch?: 0 | 1 | 2;\n\n  /**\n   * Theme to use for results page\n   * Default: \"simple\" (other themes may be available per instance)\n   */\n  theme?: string;\n\n  /**\n   * List of enabled plugins\n   * Default: \"Hash_plugin,Self_Information,Tracker_URL_remover,Ahmia_blacklist\"\n   */\n  enabled_plugins?: string;\n\n  /**\n   * List of disabled plugins\n   */\n  disabled_plugins?: string;\n\n  /**\n   * List of enabled engines\n   */\n  enabled_engines?: string;\n\n  /**\n   * List of disabled engines\n   */\n  disabled_engines?: string;\n}\n\nexport interface SearXNGResult {\n  title?: string;\n  url?: string;\n  content?: string;\n  publishedDate?: string;\n  img_src?: string;\n}\n","export type InsightsRange = '24h' | '7d' | '30d' | 'custom';\n\nexport const INSIGHTS_MAX_RANGE_DAYS = 30;\nexport const INSIGHTS_SEARCH_MIN_LENGTH = 3;\nexport const INSIGHTS_SEARCH_MAX_LENGTH = 200;\nexport const INSIGHTS_AGENT_ID_MAX_LENGTH = 256;\nexport type TInsightsParams = {\n  range?: InsightsRange;\n  fromTimestamp?: string;\n  toTimestamp?: string;\n  timeZone?: string;\n  search?: string;\n  agentIds?: string[];\n  page?: number;\n  pageSize?: number;\n};\n\nexport type TInsightsAgent = {\n  id: string;\n  name: string;\n};\n\nexport type TInsightsDailyPoint = {\n  date: string;\n  conversations: number;\n  users: number;\n  messages: number;\n  totalTokens: number;\n};\n\nexport type TInsightsUser = {\n  userId: string;\n  name: string;\n  email: string;\n  conversations: number;\n  messages: number;\n};\n\nexport type TInsightsChurnedUser = TInsightsUser & {\n  firstSeen: string;\n  lastSeen: string;\n};\n\nexport type TInsightsConversation = {\n  conversationId: string;\n  agentId: string;\n  agentName: string;\n  date: string;\n  userId: string;\n  name: string;\n  email: string;\n  firstMessage: string;\n  messages: number;\n  totalTokens: number;\n};\n\nexport type TInsightsSummary = {\n  totalUsers: number;\n  totalConversations: number;\n  totalMessages: number;\n  totalTokens: number;\n};\n\nexport type TInsightsResponse = {\n  agents: TInsightsAgent[];\n  summary: TInsightsSummary;\n  daily: TInsightsDailyPoint[];\n  topUsers: TInsightsUser[];\n  churnedUsers: TInsightsChurnedUser[];\n  latest: {\n    conversations: TInsightsConversation[];\n    page: number;\n    pageSize: number;\n    pages: number;\n  };\n};\n\nexport type TInsightsAccessResponse = {\n  access: boolean;\n};\n","/**\n * Provider-neutral conversation trace contract. The server maps whatever its\n * tracing backend stores into these shapes, so the client never sees a\n * backend's field names, credentials, URL structure or API version.\n */\n\nexport type TTraceRecordKind = 'agent' | 'generation' | 'tool' | 'span' | 'event';\n\n/** `running` marks a record with no end time yet; it has a start but no duration. */\nexport type TTraceStatus = 'ok' | 'warning' | 'error' | 'running';\n\nexport type TTraceUsage = {\n  input?: number;\n  output?: number;\n  total?: number;\n  reasoning?: number;\n  cacheRead?: number;\n  cacheWrite?: number;\n};\n\nexport type TTraceRecord = {\n  id: string;\n  traceId: string;\n  /** The response message whose turn produced this record; groups records into turns. */\n  messageId: string;\n  /** `null` for a root; may name a record that is not loaded (or does not exist). */\n  parentId: string | null;\n  kind: TTraceRecordKind;\n  name: string;\n  model?: string;\n  /** ISO-8601 timestamps. */\n  startTime: string;\n  endTime?: string;\n  /** First streamed token of a generation; splits its span into TTFT and decoding. */\n  completionStartTime?: string;\n  status: TTraceStatus;\n  statusMessage?: string;\n  usage?: TTraceUsage;\n  /** Total cost in USD, when the backend priced the record. */\n  cost?: number;\n};\n\nexport type TTraceErrorCode =\n  | 'disabled'\n  | 'not_found'\n  | 'invalid_request'\n  | 'rate_limited'\n  | 'timeout'\n  | 'unauthorized'\n  | 'unsupported'\n  | 'upstream_error';\n\nexport type TTraceErrorResponse = {\n  error: string;\n  errorCode: TTraceErrorCode;\n};\n\nexport type TTraceAvailability = {\n  available: boolean;\n  /** Set when the backend cannot decide yet; ask again after this many milliseconds. */\n  retryAfterMs?: number;\n};\n\nexport type TTracePageParams = {\n  conversationId: string;\n  cursor?: string;\n};\n\nexport type TTraceRecordParams = {\n  conversationId: string;\n  recordId: string;\n  /** The turn the list attributed the record to; its traces are what authorize the read. */\n  messageId: string;\n  /** The `sourceId` of the page that listed the record, so its detail reads the same project. */\n  sourceId?: string;\n};\n\n/**\n * Newest turns first; `nextCursor` loads the next older page. A turn's records\n * may continue on the following page, and their order within a turn is not\n * defined, so a client groups records by turn and orders them by time.\n */\nexport type TTracePage = {\n  records: TTraceRecord[];\n  nextCursor?: string;\n  /** Opaque identity of the backend project that served the page. */\n  sourceId?: string;\n};\n\nexport type TTraceContent = {\n  value: string;\n  truncated: boolean;\n};\n\nexport type TTraceRecordDetail = {\n  record: TTraceRecord;\n  /** False when the deployment withholds input, output and metadata. */\n  contentAvailable: boolean;\n  input?: TTraceContent;\n  output?: TTraceContent;\n  metadata?: TTraceContent;\n};\n\nexport const TRACE_CURSOR_MAX_LENGTH = 4096;\nexport const TRACE_SOURCE_ID_MAX_LENGTH = 128;\nexport const TRACE_RECORD_ID_MAX_LENGTH = 256;\n","import { z } from 'zod';\n\nexport const agentQueuedTurnStatuses = [\n  'queued',\n  'claimed',\n  'admitted',\n  'cancelled',\n  'dead',\n] as const;\n\nexport const agentQueuedTurnDurability = ['process_local', 'durable'] as const;\n\nexport const agentQueuedTurnFileRefSchema = z.object({\n  file_id: z.string().trim().min(1),\n  type: z.string().optional(),\n  filepath: z.string().optional(),\n  filename: z.string().optional(),\n  height: z.number().optional(),\n  width: z.number().optional(),\n  bytes: z.number().nonnegative().optional(),\n});\nexport type TAgentQueuedTurnFileRef = z.infer<typeof agentQueuedTurnFileRefSchema>;\n\nexport const enqueueAgentQueuedTurnSchema = z.object({\n  conversationId: z.string().trim().min(1),\n  parentMessageId: z.string().trim().min(1),\n  clientRequestId: z.string().trim().min(1).max(128),\n  text: z.string(),\n  files: z.array(agentQueuedTurnFileRefSchema).optional(),\n  quotes: z.array(z.string()).optional(),\n  manualSkills: z.array(z.string().trim().min(1)).optional(),\n  priority: z.boolean().optional(),\n  expectedPredecessorCreatedAt: z.number().int().nonnegative().optional(),\n});\nexport type TEnqueueAgentQueuedTurnRequest = z.infer<typeof enqueueAgentQueuedTurnSchema>;\n\nexport const listAgentQueuedTurnsSchema = z.object({\n  conversationId: z.string().trim().min(1),\n  clientRequestIds: z\n    .array(z.string().trim().min(1).max(128))\n    .max(100)\n    .transform((ids) => Array.from(new Set(ids)))\n    .optional(),\n});\nexport type TListAgentQueuedTurnsRequest = z.infer<typeof listAgentQueuedTurnsSchema>;\n\nexport const cancelAgentQueuedTurnSchema = z.object({\n  queuedTurnId: z.string().trim().min(1),\n});\nexport type TCancelAgentQueuedTurnRequest = z.infer<typeof cancelAgentQueuedTurnSchema>;\n\nexport const agentQueuedTurnReceiptSchema = enqueueAgentQueuedTurnSchema.extend({\n  queuedTurnId: z.string().trim().min(1),\n  status: z.enum(agentQueuedTurnStatuses),\n  /** Effective generation boundary consumed by an admitted turn. This can\n   * advance beyond the originally captured root as queued turns chain. */\n  effectivePredecessorCreatedAt: z.number().int().nonnegative().optional(),\n  /** Explicitly proves that this admission consumed no predecessor boundary. */\n  rootPredecessor: z.literal(true).optional(),\n  position: z.number().int().nonnegative().optional(),\n  /** Immutable queue sequence retained as `revision` for wire compatibility. */\n  revision: z.number().int().nonnegative(),\n  failure: z\n    .object({\n      code: z.string().trim().min(1).max(128),\n      message: z.string().max(2048).optional(),\n    })\n    .optional(),\n  createdAt: z.string(),\n  updatedAt: z.string(),\n});\nexport type TAgentQueuedTurnReceipt = z.infer<typeof agentQueuedTurnReceiptSchema>;\n\nexport const agentQueuedTurnCapabilitySchema = z.discriminatedUnion('supported', [\n  z.object({ supported: z.literal(false) }),\n  z.object({\n    supported: z.literal(true),\n    durability: z.enum(agentQueuedTurnDurability),\n  }),\n]);\nexport type TAgentQueuedTurnCapability = z.infer<typeof agentQueuedTurnCapabilitySchema>;\n\nexport const enqueueAgentQueuedTurnResponseSchema = z.object({\n  receipt: agentQueuedTurnReceiptSchema,\n  capability: agentQueuedTurnCapabilitySchema,\n});\nexport type TEnqueueAgentQueuedTurnResponse = z.infer<typeof enqueueAgentQueuedTurnResponseSchema>;\n\nexport const listAgentQueuedTurnsResponseSchema = z.object({\n  queuedTurns: z.array(agentQueuedTurnReceiptSchema),\n  capability: agentQueuedTurnCapabilitySchema,\n  revision: z.number().int().nonnegative(),\n});\nexport type TListAgentQueuedTurnsResponse = z.infer<typeof listAgentQueuedTurnsResponseSchema>;\n\nexport const cancelAgentQueuedTurnResponseSchema = z.object({\n  receipt: agentQueuedTurnReceiptSchema,\n});\nexport type TCancelAgentQueuedTurnResponse = z.infer<typeof cancelAgentQueuedTurnResponseSchema>;\n","import { EModelEndpoint, Providers } from './schemas';\nimport { KnownEndpoints } from './config';\n\n/** Canonical provider identity used for branding across client and server. */\nexport enum ProviderId {\n  openai = 'openai',\n  anthropic = 'anthropic',\n  google = 'google',\n  azure = 'azure',\n  bedrock = 'bedrock',\n  xai = 'xai',\n  moonshot = 'moonshot',\n  anyscale = 'anyscale',\n  apipie = 'apipie',\n  cohere = 'cohere',\n  deepseek = 'deepseek',\n  fireworks = 'fireworks',\n  groq = 'groq',\n  helicone = 'helicone',\n  huggingface = 'huggingface',\n  lemonade = 'lemonade',\n  mistral = 'mistral',\n  mlx = 'mlx',\n  ollama = 'ollama',\n  openrouter = 'openrouter',\n  perplexity = 'perplexity',\n  qwen = 'qwen',\n  shuttleai = 'shuttleai',\n  together = 'together',\n  unify = 'unify',\n  vercel = 'vercel',\n}\n\nexport const endpointToProvider: Partial<Record<EModelEndpoint, ProviderId>> = {\n  [EModelEndpoint.openAI]: ProviderId.openai,\n  [EModelEndpoint.azureOpenAI]: ProviderId.azure,\n  [EModelEndpoint.anthropic]: ProviderId.anthropic,\n  [EModelEndpoint.google]: ProviderId.google,\n  [EModelEndpoint.bedrock]: ProviderId.bedrock,\n};\n\nexport const knownEndpointToProvider: Record<KnownEndpoints, ProviderId> = {\n  [KnownEndpoints.anyscale]: ProviderId.anyscale,\n  [KnownEndpoints.apipie]: ProviderId.apipie,\n  [KnownEndpoints.cohere]: ProviderId.cohere,\n  [KnownEndpoints.fireworks]: ProviderId.fireworks,\n  [KnownEndpoints.deepseek]: ProviderId.deepseek,\n  [KnownEndpoints.moonshot]: ProviderId.moonshot,\n  [KnownEndpoints.groq]: ProviderId.groq,\n  [KnownEndpoints.helicone]: ProviderId.helicone,\n  [KnownEndpoints.huggingface]: ProviderId.huggingface,\n  [KnownEndpoints.lemonade]: ProviderId.lemonade,\n  [KnownEndpoints.mistral]: ProviderId.mistral,\n  [KnownEndpoints.mlx]: ProviderId.mlx,\n  [KnownEndpoints.ollama]: ProviderId.ollama,\n  [KnownEndpoints.openrouter]: ProviderId.openrouter,\n  [KnownEndpoints.perplexity]: ProviderId.perplexity,\n  [KnownEndpoints.shuttleai]: ProviderId.shuttleai,\n  [KnownEndpoints['together.ai']]: ProviderId.together,\n  [KnownEndpoints.unify]: ProviderId.unify,\n  [KnownEndpoints.vercel]: ProviderId.vercel,\n  [KnownEndpoints.xai]: ProviderId.xai,\n};\n\nconst providerAliases: Record<string, ProviderId> = {\n  chatgpt: ProviderId.openai,\n  gpt: ProviderId.openai,\n  azureopenai: ProviderId.azure,\n  claude: ProviderId.anthropic,\n  gemini: ProviderId.google,\n  gemma: ProviderId.google,\n  vertex: ProviderId.google,\n  vertexai: ProviderId.google,\n  palm: ProviderId.google,\n  awsbedrock: ProviderId.bedrock,\n  grok: ProviderId.xai,\n  kimi: ProviderId.moonshot,\n  moonshotai: ProviderId.moonshot,\n  amdlemonade: ProviderId.lemonade,\n  lemonadeserver: ProviderId.lemonade,\n  mistralai: ProviderId.mistral,\n  togetherai: ProviderId.together,\n};\n\nconst modelCatalogAliases: Partial<Record<string, string>> = {\n  [Providers.VERTEXAI]: EModelEndpoint.google,\n};\n\nconst normalize = (input: string): string => input.toLowerCase().replace(/[\\s._-]/g, '');\n\nconst providerByNormalizedId = Object.values(ProviderId).reduce<Record<string, ProviderId>>(\n  (acc, id) => {\n    acc[normalize(id)] = id;\n    return acc;\n  },\n  {},\n);\n\n/** Resolves free-form provider text to a canonical id, ignoring case and separators. */\nexport function resolveProviderId(input?: string | null): ProviderId | null {\n  if (!input) {\n    return null;\n  }\n  const key = normalize(input);\n  return providerByNormalizedId[key] ?? providerAliases[key] ?? null;\n}\n\n/** Resolves a runtime provider to its model catalog, using a native alias only when needed. */\nexport function resolveModelCatalogKey<T>(\n  provider?: string | null,\n  catalogs?: Partial<Record<string, T>>,\n): string {\n  const key = provider ?? '';\n  return catalogs?.[key] != null ? key : (modelCatalogAliases[key] ?? key);\n}\n","/**\n * DOMPurify policy for user-provided SVG icons, shared by the browser uploader and\n * the server trust boundary so a preview and the persisted icon cannot disagree.\n * `use` is re-added for self-contained `<defs>` references (targets restricted by\n * `restrictSvgReferences`); every SMIL element is forbidden so a stored icon\n * cannot animate forever wherever it renders.\n */\nexport const SVG_SANITIZE_CONFIG = {\n  USE_PROFILES: { svg: true, svgFilters: true },\n  ADD_TAGS: ['use'],\n  ADD_ATTR: ['fr'],\n  FORBID_TAGS: [\n    'script',\n    'foreignObject',\n    'style',\n    'a',\n    'image',\n    'animate',\n    'animateColor',\n    'animateMotion',\n    'animateTransform',\n    'mpath',\n    'set',\n  ],\n  FORBID_ATTR: ['style'],\n};\n\n/** Element surface shared by the browser DOM and the server's jsdom. */\nexport interface SvgAttributeHost {\n  attributes: ArrayLike<{ name: string }>;\n  getAttribute(name: string): string | null;\n  removeAttribute(name: string): void;\n}\n\nconst URL_TOKEN_PREFIX = /url\\(\\s*['\"]?\\s*/gi;\n\n/**\n * True when every `url()` token targets a fragment. Backslashes reject the value\n * outright: CSS unescapes idents before tokenizing, so `u\\72l(...)` is a `url()`.\n */\nfunction referencesOnlyFragments(value: string): boolean {\n  if (value.includes('\\\\')) {\n    return false;\n  }\n  if (!value.toLowerCase().includes('url(')) {\n    return true;\n  }\n  URL_TOKEN_PREFIX.lastIndex = 0;\n  while (URL_TOKEN_PREFIX.exec(value) !== null) {\n    if (value[URL_TOKEN_PREFIX.lastIndex] !== '#') {\n      return false;\n    }\n  }\n  return true;\n}\n\n/** DOMPurify hook that drops every attribute referencing outside the document. */\nexport function restrictSvgReferences(node: SvgAttributeHost): void {\n  const names: string[] = [];\n  for (let i = 0; i < node.attributes.length; i += 1) {\n    names.push(node.attributes[i].name);\n  }\n  for (const name of names) {\n    const value = node.getAttribute(name)?.trim();\n    if (value == null) {\n      continue;\n    }\n    if (name === 'href' || name === 'xlink:href') {\n      if (!value.startsWith('#')) {\n        node.removeAttribute(name);\n      }\n      continue;\n    }\n    if (!referencesOnlyFragments(value)) {\n      node.removeAttribute(name);\n    }\n  }\n}\n\n/** SVG names the HTML parser lowercases and its adjustment table does not restore. */\nconst UNADJUSTED_SVG_TAGS: Array<[RegExp, string]> = [[/(<\\/?)fedropshadow\\b/gi, '$1feDropShadow']];\n\nconst SVG_ROOT_TAG = /<svg(\\s[^>]*)?>/i;\n\n/**\n * Makes HTML-mode sanitizer output valid as a standalone `image/svg+xml`\n * document: restores camelCase element names the HTML parser lowercased and\n * declares the SVG namespace on the root, without which an XML parser puts the\n * root in no namespace and the icon renders blank.\n */\nexport function finalizeSvgMarkup(markup: string): string {\n  let restored = markup;\n  for (const [pattern, canonical] of UNADJUSTED_SVG_TAGS) {\n    restored = restored.replace(pattern, canonical);\n  }\n  return restored.replace(SVG_ROOT_TAG, (tag, attributes: string | undefined) =>\n    attributes != null && /\\sxmlns\\s*=/i.test(attributes)\n      ? tag\n      : `<svg xmlns=\"http://www.w3.org/2000/svg\"${attributes ?? ''}>`,\n  );\n}\n","import { z } from 'zod';\nimport { URL } from 'url';\nimport _axios from 'axios';\nimport crypto from 'crypto';\nimport { load } from 'js-yaml';\nimport type { OpenAPIV3 } from 'openapi-types';\nimport type { ActionMetadata, ActionMetadataRuntime } from './types/agents';\nimport type { FunctionTool, Schema, Reference } from './types/assistants';\nimport { AuthTypeEnum, AuthorizationTypeEnum } from './types/agents';\nimport { Tools } from './types/assistants';\n\nexport type ParametersSchema = {\n  type: string;\n  properties: Record<string, Reference | Schema>;\n  required: string[];\n  additionalProperties?: boolean;\n};\n\nexport type OpenAPISchema = OpenAPIV3.SchemaObject &\n  ParametersSchema & {\n    items?: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject;\n  };\n\nexport type ApiKeyCredentials = {\n  api_key: string;\n  custom_auth_header?: string;\n  authorization_type?: AuthorizationTypeEnum;\n};\n\nexport type OAuthCredentials = {\n  tokenUrl: string;\n  clientId: string;\n  clientSecret: string;\n  scope: string;\n};\n\nexport type Credentials = ApiKeyCredentials | OAuthCredentials;\n\ntype MediaTypeObject =\n  | undefined\n  | {\n      [media: string]: OpenAPIV3.MediaTypeObject | undefined;\n    };\n\ntype RequestBodyObject = Omit<OpenAPIV3.RequestBodyObject, 'content'> & {\n  content: MediaTypeObject;\n};\n\nexport function sha1(input: string) {\n  return crypto.createHash('sha1').update(input).digest('hex');\n}\n\nexport function createURL(domain: string, path: string) {\n  const cleanDomain = domain.replace(/\\/$/, '');\n  const cleanPath = path.replace(/^\\//, '');\n  const fullURL = `${cleanDomain}/${cleanPath}`;\n  return new URL(fullURL).toString();\n}\n\nconst schemaTypeHandlers: Record<string, (schema: OpenAPISchema) => z.ZodTypeAny> = {\n  string: (schema) => {\n    if (schema.enum) {\n      return z.enum(schema.enum as [string, ...string[]]);\n    }\n\n    let stringSchema = z.string();\n    if (schema.minLength !== undefined) {\n      stringSchema = stringSchema.min(schema.minLength);\n    }\n    if (schema.maxLength !== undefined) {\n      stringSchema = stringSchema.max(schema.maxLength);\n    }\n    return stringSchema;\n  },\n  number: (schema) => {\n    let numberSchema = z.number();\n    if (schema.minimum !== undefined) {\n      numberSchema = numberSchema.min(schema.minimum);\n    }\n    if (schema.maximum !== undefined) {\n      numberSchema = numberSchema.max(schema.maximum);\n    }\n    return numberSchema;\n  },\n  integer: (schema) => (schemaTypeHandlers.number(schema) as z.ZodNumber).int(),\n  boolean: () => z.boolean(),\n  array: (schema) => {\n    if (schema.items) {\n      const zodSchema = openAPISchemaToZod(schema.items as OpenAPISchema);\n      if (zodSchema) {\n        return z.array(zodSchema);\n      }\n\n      return z.array(z.unknown());\n    }\n    return z.array(z.unknown());\n  },\n  object: (schema) => {\n    const shape: { [key: string]: z.ZodTypeAny } = {};\n    if (schema.properties) {\n      Object.entries(schema.properties).forEach(([key, value]) => {\n        const zodSchema = openAPISchemaToZod(value as OpenAPISchema);\n        shape[key] = zodSchema || z.unknown();\n        if (schema.required && schema.required.includes(key)) {\n          shape[key] = shape[key].describe(value.description || '');\n        } else {\n          shape[key] = shape[key].optional().describe(value.description || '');\n        }\n      });\n    }\n    return z.object(shape);\n  },\n};\n\nfunction openAPISchemaToZod(schema: OpenAPISchema): z.ZodTypeAny | undefined {\n  if (schema.type === 'object' && Object.keys(schema.properties || {}).length === 0) {\n    return undefined;\n  }\n\n  const handler = schemaTypeHandlers[schema.type as string] || (() => z.unknown());\n  return handler(schema);\n}\n\n/**\n * Class representing a function signature.\n */\nexport class FunctionSignature {\n  name: string;\n  description: string;\n  parameters: ParametersSchema;\n  strict: boolean;\n\n  constructor(name: string, description: string, parameters: ParametersSchema, strict?: boolean) {\n    this.name = name;\n    this.description = description;\n    this.parameters = parameters;\n    this.strict = strict ?? false;\n  }\n\n  toObjectTool(): FunctionTool {\n    const parameters = {\n      ...this.parameters,\n      additionalProperties: this.strict ? false : undefined,\n    };\n\n    return {\n      type: Tools.function,\n      function: {\n        name: this.name,\n        description: this.description,\n        parameters,\n        ...(this.strict ? { strict: this.strict } : {}),\n      },\n    };\n  }\n}\n\nclass RequestConfig {\n  constructor(\n    readonly domain: string,\n    readonly basePath: string,\n    readonly method: string,\n    readonly operation: string,\n    readonly isConsequential: boolean,\n    readonly contentType: string,\n    readonly parameterLocations?: Record<string, 'query' | 'path' | 'header' | 'body'>,\n  ) {}\n}\n\nclass RequestExecutor {\n  path: string;\n  params?: Record<string, unknown>;\n  private operationHash?: string;\n  private authHeaders: Record<string, string> = {};\n  private authToken?: string;\n\n  constructor(private config: RequestConfig) {\n    this.path = config.basePath;\n  }\n\n  setParams(params: Record<string, unknown>) {\n    this.operationHash = sha1(JSON.stringify(params));\n    this.params = { ...params } as Record<string, unknown>;\n    if (this.config.parameterLocations) {\n      //Substituting “Path” Parameters:\n      for (const [key, value] of Object.entries(params)) {\n        if (this.config.parameterLocations[key] === 'path') {\n          const paramPattern = `{${key}}`;\n          if (this.path.includes(paramPattern)) {\n            this.path = this.path.replace(paramPattern, encodeURIComponent(String(value)));\n            delete this.params[key];\n          }\n        }\n      }\n    } else {\n      // Fallback: if no locations are defined, perform path substitution for all keys.\n      for (const [key, value] of Object.entries(params)) {\n        const paramPattern = `{${key}}`;\n        if (this.path.includes(paramPattern)) {\n          this.path = this.path.replace(paramPattern, encodeURIComponent(String(value)));\n          delete this.params[key];\n        }\n      }\n    }\n    return this;\n  }\n\n  async setAuth(metadata: ActionMetadataRuntime) {\n    if (!metadata.auth) {\n      return this;\n    }\n\n    const {\n      type,\n      /* API Key */\n      authorization_type,\n      custom_auth_header,\n      /* OAuth */\n      authorization_url,\n      client_url,\n      scope,\n      token_exchange_method,\n    } = metadata.auth;\n\n    const {\n      /* API Key */\n      api_key,\n      /* OAuth */\n      oauth_client_id,\n      oauth_client_secret,\n      oauth_token_expires_at,\n      oauth_access_token = '',\n    } = metadata;\n\n    const isApiKey = api_key != null && api_key.length > 0 && type === AuthTypeEnum.ServiceHttp;\n    const isOAuth = !!(\n      oauth_client_id != null &&\n      oauth_client_id &&\n      oauth_client_secret != null &&\n      oauth_client_secret &&\n      type === AuthTypeEnum.OAuth &&\n      authorization_url != null &&\n      authorization_url &&\n      client_url != null &&\n      client_url &&\n      scope != null &&\n      scope &&\n      token_exchange_method\n    );\n\n    if (isApiKey && authorization_type === AuthorizationTypeEnum.Basic) {\n      const basicToken = Buffer.from(api_key).toString('base64');\n      this.authHeaders['Authorization'] = `Basic ${basicToken}`;\n    } else if (isApiKey && authorization_type === AuthorizationTypeEnum.Bearer) {\n      this.authHeaders['Authorization'] = `Bearer ${api_key}`;\n    } else if (\n      isApiKey &&\n      authorization_type === AuthorizationTypeEnum.Custom &&\n      custom_auth_header != null &&\n      custom_auth_header\n    ) {\n      this.authHeaders[custom_auth_header] = api_key;\n    } else if (isOAuth) {\n      // TODO: maybe doing it in a different way later on. but we want that the user needs to folllow the oauth flow.\n      // If we do not have a valid token, bail or ask user to sign in\n      const now = new Date();\n\n      // 1. Check if token is set\n      if (!oauth_access_token) {\n        throw new Error('No access token found. Please log in first.');\n      }\n\n      // 2. Check if token is expired\n      if (oauth_token_expires_at && now >= new Date(oauth_token_expires_at)) {\n        // Optionally check refresh_token logic, or just prompt user to re-login\n        throw new Error('Access token is expired. Please re-login.');\n      }\n\n      // If valid, use it\n      this.authToken = oauth_access_token;\n      this.authHeaders['Authorization'] = `Bearer ${this.authToken}`;\n    }\n    return this;\n  }\n\n  async execute(options?: { httpAgent?: unknown; httpsAgent?: unknown }) {\n    const url = createURL(this.config.domain, this.path);\n    const headers: Record<string, string> = {\n      ...this.authHeaders,\n      ...(this.config.contentType ? { 'Content-Type': this.config.contentType } : {}),\n    };\n    const method = this.config.method.toLowerCase();\n\n    /**\n     * SECURITY: Disable automatic redirects to prevent SSRF bypass.\n     * Attackers could use redirects to access internal services:\n     *   1. Set action URL to allowed external domain\n     *   2. External domain redirects to internal service (e.g., 127.0.0.1, rag_api)\n     *   3. Without this protection, axios would follow the redirect\n     *\n     * By setting maxRedirects: 0, we prevent this attack vector.\n     * The action will receive the redirect response (3xx) instead of following it.\n     *\n     * SECURITY: When httpAgent/httpsAgent are provided (SSRF-safe agents), they validate\n     * the DNS-resolved IP at TCP connect time, preventing TOCTOU DNS rebinding attacks.\n     */\n    const axios = _axios.create({\n      maxRedirects: 0,\n      validateStatus: (status) => status >= 200 && status < 400,\n      ...(options?.httpAgent != null ? { httpAgent: options.httpAgent } : {}),\n      ...(options?.httpsAgent != null ? { httpsAgent: options.httpsAgent } : {}),\n    });\n\n    // Initialize separate containers for query and body parameters.\n    const queryParams: Record<string, unknown> = {};\n    const bodyParams: Record<string, unknown> = {};\n\n    if (this.config.parameterLocations && this.params) {\n      for (const key of Object.keys(this.params)) {\n        // Determine parameter placement; default to \"query\" for GET and \"body\" for others.\n        const loc: 'query' | 'path' | 'header' | 'body' =\n          this.config.parameterLocations[key] || (method === 'get' ? 'query' : 'body');\n\n        const val = this.params[key];\n        if (loc === 'query') {\n          queryParams[key] = val;\n        } else if (loc === 'header') {\n          headers[key] = String(val);\n        } else if (loc === 'body') {\n          bodyParams[key] = val;\n        }\n      }\n    } else if (this.params) {\n      Object.assign(queryParams, this.params);\n      Object.assign(bodyParams, this.params);\n    }\n\n    if (method === 'get') {\n      return axios.get(url, { headers, params: queryParams });\n    } else if (method === 'post') {\n      return axios.post(url, bodyParams, { headers, params: queryParams });\n    } else if (method === 'put') {\n      return axios.put(url, bodyParams, { headers, params: queryParams });\n    } else if (method === 'delete') {\n      return axios.delete(url, { headers, data: bodyParams, params: queryParams });\n    } else if (method === 'patch') {\n      return axios.patch(url, bodyParams, { headers, params: queryParams });\n    } else {\n      throw new Error(`Unsupported HTTP method: ${method}`);\n    }\n  }\n\n  getConfig() {\n    return this.config;\n  }\n}\n\nexport class ActionRequest {\n  private config: RequestConfig;\n\n  constructor(\n    domain: string,\n    path: string,\n    method: string,\n    operation: string,\n    isConsequential: boolean,\n    contentType: string,\n    parameterLocations?: Record<string, 'query' | 'path' | 'header' | 'body'>,\n  ) {\n    this.config = new RequestConfig(\n      domain,\n      path,\n      method,\n      operation,\n      isConsequential,\n      contentType,\n      parameterLocations,\n    );\n  }\n\n  // Add getters to maintain backward compatibility\n  get domain() {\n    return this.config.domain;\n  }\n  get path() {\n    return this.config.basePath;\n  }\n  get method() {\n    return this.config.method;\n  }\n  get operation() {\n    return this.config.operation;\n  }\n  get isConsequential() {\n    return this.config.isConsequential;\n  }\n  get contentType() {\n    return this.config.contentType;\n  }\n\n  createExecutor() {\n    return new RequestExecutor(this.config);\n  }\n\n  // Maintain backward compatibility by delegating to a new executor\n  setParams(params: Record<string, unknown>) {\n    const executor = this.createExecutor();\n    executor.setParams(params);\n    return executor;\n  }\n\n  async setAuth(metadata: ActionMetadata) {\n    const executor = this.createExecutor();\n    return executor.setAuth(metadata);\n  }\n\n  async execute() {\n    const executor = this.createExecutor();\n    return executor.execute();\n  }\n}\n\nexport function resolveRef<\n  T extends\n    | OpenAPIV3.ReferenceObject\n    | OpenAPIV3.SchemaObject\n    | OpenAPIV3.ParameterObject\n    | OpenAPIV3.RequestBodyObject,\n>(obj: T, components?: OpenAPIV3.ComponentsObject): Exclude<T, OpenAPIV3.ReferenceObject> {\n  if ('$ref' in obj && components) {\n    const refPath = obj.$ref.replace(/^#\\/components\\//, '').split('/');\n\n    let resolved: unknown = components as Record<string, unknown>;\n    for (const segment of refPath) {\n      if (typeof resolved === 'object' && resolved !== null && segment in resolved) {\n        resolved = (resolved as Record<string, unknown>)[segment];\n      } else {\n        throw new Error(`Could not resolve reference: ${obj.$ref}`);\n      }\n    }\n\n    return resolveRef(resolved as typeof obj, components) as Exclude<T, OpenAPIV3.ReferenceObject>;\n  }\n\n  return obj as Exclude<T, OpenAPIV3.ReferenceObject>;\n}\n\nfunction sanitizeOperationId(input: string) {\n  return input.replace(/[^a-zA-Z0-9_-]/g, '');\n}\n\n/**\n * Converts an OpenAPI spec to function signatures and request builders.\n */\nexport function openapiToFunction(\n  openapiSpec: OpenAPIV3.Document,\n  generateZodSchemas = false,\n): {\n  functionSignatures: FunctionSignature[];\n  requestBuilders: Record<string, ActionRequest>;\n  zodSchemas?: Record<string, z.ZodTypeAny>;\n} {\n  const functionSignatures: FunctionSignature[] = [];\n  const requestBuilders: Record<string, ActionRequest> = {};\n  const zodSchemas: Record<string, z.ZodTypeAny> = {};\n  const baseUrl = openapiSpec.servers?.[0]?.url ?? '';\n\n  // Iterate over each path and method in the OpenAPI spec\n  for (const [path, methods] of Object.entries(openapiSpec.paths)) {\n    for (const [method, operation] of Object.entries(methods as OpenAPIV3.PathsObject)) {\n      const paramLocations: Record<string, 'query' | 'path' | 'header' | 'body'> = {};\n      const operationObj = operation as OpenAPIV3.OperationObject & {\n        'x-openai-isConsequential'?: boolean;\n      } & {\n        'x-strict'?: boolean;\n      };\n\n      // Operation ID is used as the function name\n      const defaultOperationId = `${method}_${path}`;\n      const operationId = operationObj.operationId || sanitizeOperationId(defaultOperationId);\n      const description = operationObj.summary || operationObj.description || '';\n      const isStrict = operationObj['x-strict'] ?? false;\n\n      const parametersSchema: OpenAPISchema = {\n        type: 'object',\n        properties: {},\n        required: [],\n      };\n\n      if (operationObj.parameters) {\n        for (const param of operationObj.parameters ?? []) {\n          const resolvedParam = resolveRef(\n            param,\n            openapiSpec.components,\n          ) as OpenAPIV3.ParameterObject;\n\n          const paramName = resolvedParam.name;\n          if (!paramName || !resolvedParam.schema) {\n            continue;\n          }\n\n          const paramSchema = resolveRef(\n            resolvedParam.schema,\n            openapiSpec.components,\n          ) as OpenAPIV3.SchemaObject;\n\n          parametersSchema.properties[paramName] = paramSchema;\n          if (resolvedParam.required) {\n            parametersSchema.required.push(paramName);\n          }\n          // Record the parameter location from the OpenAPI \"in\" field.\n          paramLocations[paramName] =\n            resolvedParam.in === 'query' ||\n            resolvedParam.in === 'path' ||\n            resolvedParam.in === 'header' ||\n            resolvedParam.in === 'body'\n              ? resolvedParam.in\n              : 'query';\n        }\n      }\n\n      let contentType = '';\n      if (operationObj.requestBody) {\n        const requestBody = operationObj.requestBody as RequestBodyObject;\n        const content = requestBody.content;\n        contentType = Object.keys(content ?? {})[0];\n        const schema = content?.[contentType]?.schema;\n        const resolvedSchema = resolveRef(\n          schema as OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject,\n          openapiSpec.components,\n        );\n        parametersSchema.properties = {\n          ...parametersSchema.properties,\n          ...resolvedSchema.properties,\n        };\n        if (resolvedSchema.required) {\n          parametersSchema.required.push(...resolvedSchema.required);\n        }\n        // Mark requestBody properties as belonging to the \"body\"\n        if (resolvedSchema.properties) {\n          for (const key in resolvedSchema.properties) {\n            paramLocations[key] = 'body';\n          }\n        }\n\n        contentType = contentType ?? 'application/json';\n      }\n\n      const functionSignature = new FunctionSignature(\n        operationId,\n        description,\n        parametersSchema,\n        isStrict,\n      );\n      functionSignatures.push(functionSignature);\n\n      const actionRequest = new ActionRequest(\n        baseUrl,\n        path,\n        method,\n        operationId,\n        !!(operationObj['x-openai-isConsequential'] ?? false),\n        contentType,\n        paramLocations,\n      );\n\n      requestBuilders[operationId] = actionRequest;\n\n      if (generateZodSchemas && Object.keys(parametersSchema.properties).length > 0) {\n        const schema = openAPISchemaToZod(parametersSchema);\n        if (schema) {\n          zodSchemas[operationId] = schema;\n        }\n      }\n    }\n  }\n\n  return { functionSignatures, requestBuilders, zodSchemas };\n}\n\nexport type ValidationResult = {\n  status: boolean;\n  message: string;\n  spec?: OpenAPIV3.Document;\n  serverUrl?: string;\n};\n\n/**\n * Cross-platform IP validation (works in Node.js and browser).\n * @param input - String to check if it's an IP address\n * @returns 0 if not IP, 4 for IPv4, 6 for IPv6\n */\nfunction isIP(input: string): number {\n  // IPv4 regex - matches 0.0.0.0 to 255.255.255.255\n  const ipv4Regex =\n    /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;\n\n  if (ipv4Regex.test(input)) {\n    return 4;\n  }\n\n  // IPv6 regex - simplified but covers most cases\n  // Handles compressed (::), full, and mixed notations\n  const ipv6Regex =\n    /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\n\n  if (ipv6Regex.test(input)) {\n    return 6;\n  }\n\n  return 0;\n}\n\n/**\n * Extracts domain from URL (protocol + hostname).\n * @param url - URL to extract from\n * @returns Protocol and hostname (e.g., \"https://example.com\")\n */\nexport function extractDomainFromUrl(url: string): string {\n  try {\n    /** Parsed URL object */\n    const parsedUrl = new URL(url);\n    // Preserve brackets for IPv6 addresses using isIP\n    const ipVersion = isIP(parsedUrl.hostname);\n    const hostname = ipVersion === 6 ? `[${parsedUrl.hostname}]` : parsedUrl.hostname;\n    return `${parsedUrl.protocol}//${hostname}`;\n  } catch {\n    throw new Error(`Invalid URL format: ${url}`);\n  }\n}\n\nexport type DomainValidationResult = {\n  isValid: boolean;\n  message?: string;\n  normalizedSpecDomain?: string;\n  normalizedClientDomain?: string;\n};\n\nfunction getExplicitPort(value: string): string | null {\n  const normalizedValue = value.trim();\n  const protocolSeparatorIndex = normalizedValue.indexOf('://');\n  const hasProtocol = protocolSeparatorIndex !== -1;\n  const authorityAndPath = hasProtocol\n    ? normalizedValue.slice(protocolSeparatorIndex + 3)\n    : normalizedValue;\n\n  let port: string;\n  try {\n    const parsedUrl = new URL(hasProtocol ? normalizedValue : `https://${normalizedValue}`);\n    port = parsedUrl.port;\n\n    // WHATWG URL parsing removes explicit default ports, so parse the same authority with\n    // the alternate HTTP scheme to distinguish an explicit port from an omitted one.\n    if (!port && (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:')) {\n      const alternateProtocol = parsedUrl.protocol === 'http:' ? 'https:' : 'http:';\n      port = new URL(`${alternateProtocol}//${authorityAndPath}`).port;\n    }\n  } catch {\n    return null;\n  }\n\n  if (!port) {\n    return null;\n  }\n\n  const parsedPort = Number(port);\n  if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65535) {\n    throw new Error(`Invalid port in domain: ${value}`);\n  }\n\n  return String(parsedPort);\n}\n\nfunction getDefaultActionPort(protocol: string): string {\n  return protocol === 'https:' ? '443' : '80';\n}\n\n/**\n * Validates client domain matches OpenAPI spec server URL domain (SSRF prevention).\n * @param clientProvidedDomain - Domain from client (with/without protocol)\n * @param specServerUrl - Server URL from OpenAPI spec\n * @returns Validation result with normalized domains\n */\nexport function validateActionDomain(\n  clientProvidedDomain: string,\n  specServerUrl: string,\n): DomainValidationResult {\n  try {\n    /** Parsed spec URL */\n    const specUrl = new URL(specServerUrl);\n\n    if (specUrl.protocol !== 'http:' && specUrl.protocol !== 'https:') {\n      return {\n        isValid: false,\n        message: `Invalid protocol: Only HTTP and HTTPS are allowed, got ${specUrl.protocol}`,\n      };\n    }\n\n    /** Spec hostname only */\n    const specHostname = specUrl.hostname;\n    /** Spec domain with protocol (handle IPv6 brackets) */\n    const specIpVersion = isIP(specHostname);\n    const normalizedSpecDomain =\n      specIpVersion === 6\n        ? `${specUrl.protocol}//[${specHostname}]`\n        : `${specUrl.protocol}//${specHostname}`;\n\n    /** Extract hostname from client domain if it's a full URL */\n    let clientHostname = clientProvidedDomain;\n    let clientHasProtocol = false;\n    const clientExplicitPort = getExplicitPort(clientProvidedDomain);\n\n    // Check for any protocol in the client domain\n    if (clientProvidedDomain.includes('://')) {\n      if (\n        !clientProvidedDomain.startsWith('http://') &&\n        !clientProvidedDomain.startsWith('https://')\n      ) {\n        return {\n          isValid: false,\n          message: `Invalid protocol: Only HTTP and HTTPS are allowed in client domain`,\n        };\n      }\n      try {\n        const clientUrl = new URL(clientProvidedDomain);\n        clientHostname = clientUrl.hostname;\n        clientHasProtocol = true;\n      } catch {\n        // If parsing fails, treat as hostname\n        clientHasProtocol = false;\n      }\n    } else if (clientExplicitPort !== null) {\n      const clientUrl = new URL(`https://${clientProvidedDomain}`);\n      clientHostname = clientUrl.hostname;\n    }\n\n    /** Normalize IPv6 addresses by removing brackets for comparison */\n    const normalizedClientHostname = clientHostname.replace(/^\\[(.+)\\]$/, '$1');\n    const normalizedSpecHostname = specHostname.replace(/^\\[(.+)\\]$/, '$1');\n\n    /** Check if hostname is valid IP using cross-platform isIP */\n    const isIPAddress = isIP(normalizedClientHostname) !== 0;\n\n    /** Normalized client domain */\n    let normalizedClientDomain: string;\n    if (clientHasProtocol) {\n      normalizedClientDomain = extractDomainFromUrl(clientProvidedDomain);\n    } else {\n      // No protocol specified by client\n      if (isIPAddress) {\n        // IPs inherit protocol from spec (for legitimate internal services)\n        const ipVersion = isIP(normalizedClientHostname);\n        const hostname =\n          ipVersion === 6 && !clientHostname.startsWith('[')\n            ? `[${normalizedClientHostname}]`\n            : clientHostname;\n        normalizedClientDomain = `${specUrl.protocol}//${hostname}`;\n      } else {\n        // Domain names default to HTTPS for security (forces explicit protocol)\n        normalizedClientDomain = `https://${clientHostname}`;\n      }\n    }\n\n    const domainMatches =\n      normalizedSpecDomain === normalizedClientDomain ||\n      (!clientHasProtocol && isIPAddress && normalizedClientHostname === normalizedSpecHostname);\n\n    if (!domainMatches) {\n      return {\n        isValid: false,\n        message: `Domain mismatch: Client provided '${clientProvidedDomain}', but spec uses '${specHostname}'`,\n        normalizedSpecDomain,\n        normalizedClientDomain,\n      };\n    }\n\n    if (clientExplicitPort !== null) {\n      const specEffectivePort = specUrl.port || getDefaultActionPort(specUrl.protocol);\n      if (clientExplicitPort !== specEffectivePort) {\n        return {\n          isValid: false,\n          message: `Port mismatch: Client provided '${clientProvidedDomain}', but spec uses effective port '${specEffectivePort}'`,\n          normalizedSpecDomain,\n          normalizedClientDomain,\n        };\n      }\n    }\n\n    return {\n      isValid: true,\n      normalizedSpecDomain,\n      normalizedClientDomain,\n    };\n  } catch (error) {\n    return {\n      isValid: false,\n      message: `Failed to validate domain: ${error instanceof Error ? error.message : 'Unknown error'}`,\n    };\n  }\n}\n\n/**\n * Validates and parses an OpenAPI spec.\n */\nexport function validateAndParseOpenAPISpec(specString: string): ValidationResult {\n  try {\n    let parsedSpec;\n    try {\n      parsedSpec = JSON.parse(specString);\n    } catch {\n      parsedSpec = load(specString);\n    }\n\n    // Check for servers\n    if (\n      !parsedSpec.servers ||\n      !Array.isArray(parsedSpec.servers) ||\n      parsedSpec.servers.length === 0\n    ) {\n      return { status: false, message: 'Could not find a valid URL in `servers`' };\n    }\n\n    if (!parsedSpec.servers[0].url) {\n      return { status: false, message: 'Could not find a valid URL in `servers`' };\n    }\n\n    // Check for paths\n    const paths = parsedSpec.paths;\n    if (!paths || typeof paths !== 'object' || Object.keys(paths).length === 0) {\n      return { status: false, message: 'No paths found in the OpenAPI spec.' };\n    }\n\n    const components = parsedSpec.components?.schemas || {};\n    const messages = [];\n\n    for (const [path, methods] of Object.entries(paths)) {\n      for (const [httpMethod, operation] of Object.entries(methods as OpenAPIV3.PathItemObject)) {\n        // Ensure operation is a valid operation object\n        const { responses } = operation as OpenAPIV3.OperationObject | { responses: undefined };\n        if (typeof operation === 'object' && responses) {\n          for (const [statusCode, response] of Object.entries(responses)) {\n            const content = (response as OpenAPIV3.ResponseObject).content as MediaTypeObject;\n            if (content && content['application/json'] && content['application/json'].schema) {\n              const schema = content['application/json'].schema;\n              if ('$ref' in schema && typeof schema.$ref === 'string') {\n                const refName = schema.$ref.split('/').pop();\n                if (refName && !components[refName]) {\n                  messages.push(\n                    `In context=('paths', '${path}', '${httpMethod}', '${statusCode}', 'response', 'content', 'application/json', 'schema'), reference to unknown component ${refName}; using empty schema`,\n                  );\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n\n    return {\n      status: true,\n      message: messages.join('\\n') || 'OpenAPI spec is valid.',\n      spec: parsedSpec,\n      serverUrl: parsedSpec.servers[0].url,\n    };\n  } catch (error) {\n    console.error(error);\n    return { status: false, message: 'Error parsing OpenAPI spec.' };\n  }\n}\n","import type * as t from './types';\nimport { EndpointURLs } from './config';\nimport * as s from './schemas';\n\n/** Resolves the browser's IANA timezone so the server can localize prompt variables. */\nfunction getUserTimezone(): string | undefined {\n  try {\n    return Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nexport default function createPayload(submission: t.TSubmission) {\n  const {\n    isEdited,\n    addedConvo,\n    userMessage,\n    isContinued,\n    isTemporary,\n    isRegenerate,\n    compact,\n    conversation,\n    editedContent,\n    ephemeralAgent,\n    endpointOption,\n    manualSkills,\n    codeApprovalMode,\n    codeEnvironmentMode,\n    codeWorkspaces,\n    clientRequestId,\n    recoverySteerId,\n    expectedPredecessorCreatedAt,\n  } = submission;\n  const { conversationId } = s.tConvoUpdateSchema.parse(conversation);\n  const { endpoint: _e, endpointType } = endpointOption as {\n    endpoint: s.EModelEndpoint;\n    endpointType?: s.EModelEndpoint;\n  };\n\n  const endpoint = _e as s.EModelEndpoint;\n  /** Custom endpoint names are user-defined and may contain `/`, which would\n   * otherwise split into extra path segments and miss the `/:endpoint` route. */\n  let server = `${EndpointURLs[s.EModelEndpoint.agents]}/${encodeURIComponent(endpoint)}`;\n  if (s.isAssistantsEndpoint(endpoint)) {\n    server =\n      EndpointURLs[(endpointType ?? endpoint) as 'assistants' | 'azureAssistants'] +\n      (isEdited ? '/modify' : '');\n  }\n\n  const payload: t.TPayload = {\n    ...userMessage,\n    ...endpointOption,\n    endpoint,\n    addedConvo,\n    isTemporary,\n    /** A compaction borrows the regenerate shape client-side only: the server\n     *  must see it as a compaction, never as a regenerated user turn. */\n    isRegenerate: compact === true ? undefined : isRegenerate,\n    ...(compact === true && { compact: true }),\n    editedContent,\n    conversationId,\n    isContinued: !!(isEdited && isContinued),\n    ephemeralAgent: s.isAssistantsEndpoint(endpoint) ? undefined : ephemeralAgent,\n    manualSkills: s.isAssistantsEndpoint(endpoint) ? undefined : manualSkills,\n    codeApprovalMode: s.isAssistantsEndpoint(endpoint) ? undefined : codeApprovalMode,\n    codeEnvironmentMode: s.isAssistantsEndpoint(endpoint) ? undefined : codeEnvironmentMode,\n    codeWorkspaces: s.isAssistantsEndpoint(endpoint) ? undefined : codeWorkspaces,\n    timezone: getUserTimezone(),\n    clientRequestId,\n    recoverySteerId,\n    expectedPredecessorCreatedAt,\n  };\n\n  return { server, payload };\n}\n","import {\n  Verbosity,\n  ImageDetail,\n  ThinkingLevel,\n  ThinkingDisplay,\n  EModelEndpoint,\n  openAISettings,\n  googleSettings,\n  getGoogleThinkingBudgetBounds,\n  Providers,\n  ReasoningEffort,\n  AnthropicEffort,\n  ReasoningSummary,\n  ReasoningMode,\n  ReasoningContext,\n  BedrockProviders,\n  anthropicSettings,\n} from './types';\nimport { SettingDefinition, SettingsConfiguration } from './generate';\nimport { supportsPromptCache } from './bedrock';\n\n// Base definitions\nconst baseDefinitions: Record<string, SettingDefinition> = {\n  model: {\n    key: 'model',\n    label: 'com_ui_model',\n    labelCode: true,\n    type: 'string',\n    component: 'dropdown',\n    optionType: 'model',\n    selectPlaceholder: 'com_ui_select_model',\n    searchPlaceholder: 'com_ui_select_search_model',\n    searchPlaceholderCode: true,\n    selectPlaceholderCode: true,\n    columnSpan: 4,\n  },\n  temperature: {\n    key: 'temperature',\n    label: 'com_endpoint_temperature',\n    labelCode: true,\n    description: 'com_endpoint_openai_temp',\n    descriptionCode: true,\n    type: 'number',\n    component: 'slider',\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  topP: {\n    key: 'topP',\n    label: 'com_endpoint_top_p',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_topp',\n    descriptionCode: true,\n    type: 'number',\n    component: 'slider',\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  stop: {\n    key: 'stop',\n    label: 'com_endpoint_stop',\n    labelCode: true,\n    description: 'com_endpoint_openai_stop',\n    descriptionCode: true,\n    placeholder: 'com_endpoint_stop_placeholder',\n    placeholderCode: true,\n    type: 'array',\n    default: [],\n    component: 'tags',\n    optionType: 'conversation',\n    minTags: 0,\n    maxTags: 4,\n  },\n};\n\nconst createDefinition = (\n  base: Partial<SettingDefinition>,\n  overrides: Partial<SettingDefinition>,\n): SettingDefinition => {\n  return { ...base, ...overrides } as SettingDefinition;\n};\n\nexport const librechat = {\n  modelLabel: {\n    key: 'modelLabel',\n    label: 'com_endpoint_custom_name',\n    labelCode: true,\n    type: 'string',\n    default: '',\n    component: 'input',\n    placeholder: 'com_endpoint_openai_custom_name_placeholder',\n    placeholderCode: true,\n    optionType: 'conversation',\n  } as const,\n  maxContextTokens: {\n    key: 'maxContextTokens',\n    label: 'com_endpoint_context_tokens',\n    labelCode: true,\n    type: 'number',\n    component: 'input',\n    placeholder: 'com_endpoint_default',\n    placeholderCode: true,\n    description: 'com_endpoint_context_info',\n    descriptionCode: true,\n    optionType: 'model',\n    columnSpan: 2,\n  } as const,\n  resendFiles: {\n    key: 'resendFiles',\n    label: 'com_endpoint_plug_resend_files',\n    labelCode: true,\n    description: 'com_endpoint_openai_resend_files',\n    descriptionCode: true,\n    type: 'boolean',\n    default: true,\n    component: 'switch',\n    optionType: 'conversation',\n    showDefault: false,\n    columnSpan: 2,\n  } as const,\n  promptPrefix: {\n    key: 'promptPrefix',\n    label: 'com_endpoint_prompt_prefix',\n    labelCode: true,\n    type: 'string',\n    default: '',\n    component: 'textarea',\n    placeholder: 'com_endpoint_openai_prompt_prefix_placeholder',\n    placeholderCode: true,\n    optionType: 'model',\n  } as const,\n  /** Controls how LibreChat encodes image content blocks, not a provider request\n   * parameter — so it belongs to this group and is stripped from model options. */\n  imageDetail: {\n    key: 'imageDetail',\n    label: 'com_endpoint_plug_image_detail',\n    labelCode: true,\n    description: 'com_endpoint_openai_detail',\n    descriptionCode: true,\n    type: 'enum',\n    default: ImageDetail.auto,\n    component: 'slider',\n    options: [ImageDetail.low, ImageDetail.auto, ImageDetail.high],\n    enumMappings: {\n      [ImageDetail.low]: 'com_ui_low',\n      [ImageDetail.auto]: 'com_ui_auto',\n      [ImageDetail.high]: 'com_ui_high',\n    },\n    optionType: 'conversation',\n    columnSpan: 2,\n  } as SettingDefinition,\n  fileTokenLimit: {\n    key: 'fileTokenLimit',\n    label: 'com_ui_file_token_limit',\n    labelCode: true,\n    description: 'com_ui_file_token_limit_desc',\n    descriptionCode: true,\n    placeholder: 'com_endpoint_default',\n    placeholderCode: true,\n    type: 'number',\n    component: 'input',\n    columnSpan: 2,\n  } as const,\n};\n\nconst openAIParams: Record<string, SettingDefinition> = {\n  chatGptLabel: {\n    ...librechat.modelLabel,\n    key: 'chatGptLabel',\n  },\n  promptPrefix: librechat.promptPrefix,\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: openAISettings.temperature.default,\n    range: {\n      min: openAISettings.temperature.min,\n      max: openAISettings.temperature.max,\n      step: openAISettings.temperature.step,\n    },\n  }),\n  top_p: createDefinition(baseDefinitions.topP, {\n    key: 'top_p',\n    default: openAISettings.top_p.default,\n    range: {\n      min: openAISettings.top_p.min,\n      max: openAISettings.top_p.max,\n      step: openAISettings.top_p.step,\n    },\n  }),\n  frequency_penalty: {\n    key: 'frequency_penalty',\n    label: 'com_endpoint_frequency_penalty',\n    labelCode: true,\n    description: 'com_endpoint_openai_freq',\n    descriptionCode: true,\n    type: 'number',\n    default: openAISettings.frequency_penalty.default,\n    range: {\n      min: openAISettings.frequency_penalty.min,\n      max: openAISettings.frequency_penalty.max,\n      step: openAISettings.frequency_penalty.step,\n    },\n    component: 'slider',\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  presence_penalty: {\n    key: 'presence_penalty',\n    label: 'com_endpoint_presence_penalty',\n    labelCode: true,\n    description: 'com_endpoint_openai_pres',\n    descriptionCode: true,\n    type: 'number',\n    default: openAISettings.presence_penalty.default,\n    range: {\n      min: openAISettings.presence_penalty.min,\n      max: openAISettings.presence_penalty.max,\n      step: openAISettings.presence_penalty.step,\n    },\n    component: 'slider',\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  max_tokens: {\n    key: 'max_tokens',\n    label: 'com_endpoint_max_output_tokens',\n    labelCode: true,\n    type: 'number',\n    component: 'input',\n    description: 'com_endpoint_openai_max_tokens',\n    descriptionCode: true,\n    placeholder: 'com_endpoint_default',\n    placeholderCode: true,\n    optionType: 'model',\n    columnSpan: 2,\n  },\n  reasoning_effort: {\n    key: 'reasoning_effort',\n    label: 'com_endpoint_reasoning_effort',\n    labelCode: true,\n    description: 'com_endpoint_openai_reasoning_effort',\n    descriptionCode: true,\n    type: 'enum',\n    default: ReasoningEffort.unset,\n    component: 'slider',\n    options: [\n      ReasoningEffort.unset,\n      ReasoningEffort.none,\n      ReasoningEffort.minimal,\n      ReasoningEffort.low,\n      ReasoningEffort.medium,\n      ReasoningEffort.high,\n      ReasoningEffort.xhigh,\n      ReasoningEffort.max,\n    ],\n    enumMappings: {\n      [ReasoningEffort.unset]: 'com_ui_auto',\n      [ReasoningEffort.none]: 'com_ui_none',\n      [ReasoningEffort.minimal]: 'com_ui_minimal',\n      [ReasoningEffort.low]: 'com_ui_low',\n      [ReasoningEffort.medium]: 'com_ui_medium',\n      [ReasoningEffort.high]: 'com_ui_high',\n      [ReasoningEffort.xhigh]: 'com_ui_xhigh',\n      [ReasoningEffort.max]: 'com_ui_max',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  useResponsesApi: {\n    key: 'useResponsesApi',\n    label: 'com_endpoint_use_responses_api',\n    labelCode: true,\n    description: 'com_endpoint_openai_use_responses_api',\n    descriptionCode: true,\n    type: 'boolean',\n    default: false,\n    component: 'switch',\n    optionType: 'model',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  web_search: {\n    key: 'web_search',\n    label: 'com_ui_web_search',\n    labelCode: true,\n    description: 'com_endpoint_openai_use_web_search',\n    descriptionCode: true,\n    type: 'boolean',\n    default: false,\n    component: 'switch',\n    optionType: 'model',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  reasoning_summary: {\n    key: 'reasoning_summary',\n    label: 'com_endpoint_reasoning_summary',\n    labelCode: true,\n    description: 'com_endpoint_openai_reasoning_summary',\n    descriptionCode: true,\n    type: 'enum',\n    default: ReasoningSummary.none,\n    component: 'slider',\n    options: [\n      ReasoningSummary.none,\n      ReasoningSummary.auto,\n      ReasoningSummary.concise,\n      ReasoningSummary.detailed,\n    ],\n    enumMappings: {\n      [ReasoningSummary.none]: 'com_ui_unset',\n      [ReasoningSummary.auto]: 'com_ui_auto',\n      [ReasoningSummary.concise]: 'com_ui_concise',\n      [ReasoningSummary.detailed]: 'com_ui_detailed',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  reasoning_mode: {\n    key: 'reasoning_mode',\n    label: 'com_endpoint_reasoning_mode',\n    labelCode: true,\n    description: 'com_endpoint_openai_reasoning_mode',\n    descriptionCode: true,\n    type: 'enum',\n    default: ReasoningMode.unset,\n    component: 'slider',\n    options: [ReasoningMode.unset, ReasoningMode.standard, ReasoningMode.pro],\n    enumMappings: {\n      [ReasoningMode.unset]: 'com_ui_unset',\n      [ReasoningMode.standard]: 'com_ui_standard',\n      [ReasoningMode.pro]: 'com_ui_pro',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  reasoning_context: {\n    key: 'reasoning_context',\n    label: 'com_endpoint_reasoning_context',\n    labelCode: true,\n    description: 'com_endpoint_openai_reasoning_context',\n    descriptionCode: true,\n    type: 'enum',\n    default: ReasoningContext.unset,\n    component: 'slider',\n    options: [\n      ReasoningContext.unset,\n      ReasoningContext.auto,\n      ReasoningContext.current_turn,\n      ReasoningContext.all_turns,\n    ],\n    enumMappings: {\n      [ReasoningContext.unset]: 'com_ui_unset',\n      [ReasoningContext.auto]: 'com_ui_auto',\n      [ReasoningContext.current_turn]: 'com_ui_current_turn',\n      [ReasoningContext.all_turns]: 'com_ui_all_turns',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  verbosity: {\n    key: 'verbosity',\n    label: 'com_endpoint_verbosity',\n    labelCode: true,\n    description: 'com_endpoint_openai_verbosity',\n    descriptionCode: true,\n    type: 'enum',\n    default: Verbosity.none,\n    component: 'slider',\n    options: [Verbosity.none, Verbosity.low, Verbosity.medium, Verbosity.high],\n    enumMappings: {\n      [Verbosity.none]: 'com_ui_none',\n      [Verbosity.low]: 'com_ui_low',\n      [Verbosity.medium]: 'com_ui_medium',\n      [Verbosity.high]: 'com_ui_high',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  disableStreaming: {\n    key: 'disableStreaming',\n    label: 'com_endpoint_disable_streaming_label',\n    labelCode: true,\n    description: 'com_endpoint_disable_streaming',\n    descriptionCode: true,\n    type: 'boolean',\n    default: false,\n    component: 'switch',\n    optionType: 'model',\n    showDefault: false,\n    columnSpan: 2,\n  } as const,\n};\n\nconst anthropic: Record<string, SettingDefinition> = {\n  maxOutputTokens: {\n    key: 'maxOutputTokens',\n    label: 'com_endpoint_max_output_tokens',\n    labelCode: true,\n    type: 'number',\n    component: 'input',\n    description: 'com_endpoint_anthropic_maxoutputtokens',\n    descriptionCode: true,\n    placeholder: 'com_endpoint_default',\n    placeholderCode: true,\n    range: {\n      min: anthropicSettings.maxOutputTokens.min,\n      max: anthropicSettings.maxOutputTokens.max,\n      step: anthropicSettings.maxOutputTokens.step,\n    },\n    optionType: 'model',\n    columnSpan: 2,\n  },\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: anthropicSettings.temperature.default,\n    range: {\n      min: anthropicSettings.temperature.min,\n      max: anthropicSettings.temperature.max,\n      step: anthropicSettings.temperature.step,\n    },\n  }),\n  topP: createDefinition(baseDefinitions.topP, {\n    default: anthropicSettings.topP.default,\n    range: {\n      min: anthropicSettings.topP.min,\n      max: anthropicSettings.topP.max,\n      step: anthropicSettings.topP.step,\n    },\n  }),\n  topK: {\n    key: 'topK',\n    label: 'com_endpoint_top_k',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_topk',\n    descriptionCode: true,\n    type: 'number',\n    default: anthropicSettings.topK.default,\n    range: {\n      min: anthropicSettings.topK.min,\n      max: anthropicSettings.topK.max,\n      step: anthropicSettings.topK.step,\n    },\n    component: 'slider',\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  promptCache: {\n    key: 'promptCache',\n    label: 'com_endpoint_prompt_cache',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_prompt_cache',\n    descriptionCode: true,\n    type: 'boolean',\n    default: anthropicSettings.promptCache.default,\n    component: 'switch',\n    optionType: 'conversation',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  promptCacheTtl: {\n    key: 'promptCacheTtl',\n    label: 'com_endpoint_prompt_cache_ttl',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_prompt_cache_ttl',\n    descriptionCode: true,\n    type: 'enum',\n    default: anthropicSettings.promptCacheTtl.default,\n    options: ['5m', '1h'],\n    component: 'combobox',\n    optionType: 'conversation',\n    showDefault: false,\n    selectPlaceholder: 'com_endpoint_prompt_cache_ttl_default',\n    selectPlaceholderCode: true,\n    columnSpan: 2,\n  },\n  thinking: {\n    key: 'thinking',\n    label: 'com_endpoint_thinking',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_thinking',\n    descriptionCode: true,\n    type: 'boolean',\n    default: anthropicSettings.thinking.default,\n    component: 'switch',\n    optionType: 'conversation',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  thinkingBudget: {\n    key: 'thinkingBudget',\n    label: 'com_endpoint_thinking_budget',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_thinking_budget',\n    descriptionCode: true,\n    type: 'number',\n    component: 'input',\n    default: anthropicSettings.thinkingBudget.default,\n    range: {\n      min: anthropicSettings.thinkingBudget.min,\n      max: anthropicSettings.thinkingBudget.max,\n      step: anthropicSettings.thinkingBudget.step,\n    },\n    optionType: 'conversation',\n    columnSpan: 2,\n  },\n  web_search: {\n    key: 'web_search',\n    label: 'com_ui_web_search',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_use_web_search',\n    descriptionCode: true,\n    type: 'boolean',\n    default: anthropicSettings.web_search.default,\n    component: 'switch',\n    optionType: 'conversation',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  effort: {\n    key: 'effort',\n    label: 'com_endpoint_effort',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_effort',\n    descriptionCode: true,\n    type: 'enum',\n    default: anthropicSettings.effort.default,\n    component: 'slider',\n    options: anthropicSettings.effort.options,\n    enumMappings: {\n      [AnthropicEffort.unset]: 'com_ui_auto',\n      [AnthropicEffort.low]: 'com_ui_low',\n      [AnthropicEffort.medium]: 'com_ui_medium',\n      [AnthropicEffort.high]: 'com_ui_high',\n      [AnthropicEffort.xhigh]: 'com_ui_xhigh',\n      [AnthropicEffort.max]: 'com_ui_max',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  thinkingDisplay: {\n    key: 'thinkingDisplay',\n    label: 'com_endpoint_anthropic_thinking_display',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_thinking_display_desc',\n    descriptionCode: true,\n    type: 'enum',\n    default: anthropicSettings.thinkingDisplay.default,\n    component: 'slider',\n    options: anthropicSettings.thinkingDisplay.options,\n    enumMappings: {\n      [ThinkingDisplay.auto]: 'com_ui_auto',\n      [ThinkingDisplay.summarized]: 'com_ui_summarized',\n      [ThinkingDisplay.omitted]: 'com_ui_omitted',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n};\n\nconst bedrock: Record<string, SettingDefinition> = {\n  system: {\n    key: 'system',\n    label: 'com_endpoint_prompt_prefix',\n    labelCode: true,\n    type: 'string',\n    default: '',\n    component: 'textarea',\n    placeholder: 'com_endpoint_openai_prompt_prefix_placeholder',\n    placeholderCode: true,\n    optionType: 'model',\n  },\n  region: {\n    key: 'region',\n    type: 'string',\n    label: 'com_ui_region',\n    labelCode: true,\n    component: 'combobox',\n    optionType: 'conversation',\n    selectPlaceholder: 'com_ui_select_region',\n    searchPlaceholder: 'com_ui_select_search_region',\n    searchPlaceholderCode: true,\n    selectPlaceholderCode: true,\n    columnSpan: 2,\n  },\n  maxTokens: {\n    key: 'maxTokens',\n    label: 'com_endpoint_max_output_tokens',\n    labelCode: true,\n    type: 'number',\n    component: 'input',\n    description: 'com_endpoint_anthropic_maxoutputtokens',\n    descriptionCode: true,\n    placeholder: 'com_endpoint_default',\n    placeholderCode: true,\n    optionType: 'model',\n    columnSpan: 2,\n  },\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: 1,\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n  topK: createDefinition(anthropic.topK, {\n    range: { min: 0, max: 500, step: 1 },\n  }),\n  topP: createDefinition(baseDefinitions.topP, {\n    default: 0.999,\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n  promptCache: {\n    key: 'promptCache',\n    label: 'com_endpoint_prompt_cache',\n    labelCode: true,\n    type: 'boolean',\n    description: 'com_endpoint_anthropic_prompt_cache',\n    descriptionCode: true,\n    default: true,\n    component: 'switch',\n    optionType: 'conversation',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  promptCacheTtl: {\n    key: 'promptCacheTtl',\n    label: 'com_endpoint_prompt_cache_ttl',\n    labelCode: true,\n    description: 'com_endpoint_anthropic_prompt_cache_ttl',\n    descriptionCode: true,\n    type: 'enum',\n    default: undefined,\n    options: ['5m', '1h'],\n    component: 'combobox',\n    optionType: 'conversation',\n    showDefault: false,\n    selectPlaceholder: 'com_endpoint_prompt_cache_ttl_default',\n    selectPlaceholderCode: true,\n    columnSpan: 2,\n  },\n  reasoning_effort: {\n    key: 'reasoning_effort',\n    label: 'com_endpoint_reasoning_effort',\n    labelCode: true,\n    description: 'com_endpoint_bedrock_reasoning_effort',\n    descriptionCode: true,\n    type: 'enum',\n    default: ReasoningEffort.unset,\n    component: 'slider',\n    options: [\n      ReasoningEffort.unset,\n      ReasoningEffort.low,\n      ReasoningEffort.medium,\n      ReasoningEffort.high,\n    ],\n    enumMappings: {\n      [ReasoningEffort.unset]: 'com_ui_off',\n      [ReasoningEffort.low]: 'com_ui_low',\n      [ReasoningEffort.medium]: 'com_ui_medium',\n      [ReasoningEffort.high]: 'com_ui_high',\n    },\n    optionType: 'model',\n    columnSpan: 4,\n  },\n};\n\nconst mistral: Record<string, SettingDefinition> = {\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: 0.7,\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n  topP: createDefinition(baseDefinitions.topP, {\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n};\n\nconst cohere: Record<string, SettingDefinition> = {\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: 0.3,\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n  topP: createDefinition(baseDefinitions.topP, {\n    default: 0.75,\n    range: { min: 0.01, max: 0.99, step: 0.01 },\n  }),\n};\n\nconst meta: Record<string, SettingDefinition> = {\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: 0.5,\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n  topP: createDefinition(baseDefinitions.topP, {\n    default: 0.9,\n    range: { min: 0, max: 1, step: 0.01 },\n  }),\n};\n\nconst google: Record<string, SettingDefinition> = {\n  /** Bounds the hand-rolled editor enforced through InputNumber, and they stay\n   *  scoped to this endpoint: the shared definition is rendered by every other\n   *  endpoint, whose own context windows may fall outside them. */\n  maxContextTokens: createDefinition(librechat.maxContextTokens, {\n    range: {\n      min: googleSettings.maxContextTokens.min,\n      max: googleSettings.maxContextTokens.max,\n      step: googleSettings.maxContextTokens.step,\n    },\n  }),\n  temperature: createDefinition(baseDefinitions.temperature, {\n    default: googleSettings.temperature.default,\n    range: {\n      min: googleSettings.temperature.min,\n      max: googleSettings.temperature.max,\n      step: googleSettings.temperature.step,\n    },\n  }),\n  topP: createDefinition(baseDefinitions.topP, {\n    default: googleSettings.topP.default,\n    range: {\n      min: googleSettings.topP.min,\n      max: googleSettings.topP.max,\n      step: googleSettings.topP.step,\n    },\n  }),\n  topK: {\n    key: 'topK',\n    label: 'com_endpoint_top_k',\n    labelCode: true,\n    description: 'com_endpoint_google_topk',\n    descriptionCode: true,\n    type: 'number',\n    default: googleSettings.topK.default,\n    range: {\n      min: googleSettings.topK.min,\n      max: googleSettings.topK.max,\n      step: googleSettings.topK.step,\n    },\n    component: 'slider',\n    optionType: 'model',\n    columnSpan: 4,\n  },\n  maxOutputTokens: {\n    key: 'maxOutputTokens',\n    label: 'com_endpoint_max_output_tokens',\n    labelCode: true,\n    type: 'number',\n    component: 'input',\n    description: 'com_endpoint_google_maxoutputtokens',\n    descriptionCode: true,\n    placeholder: 'com_endpoint_default',\n    placeholderCode: true,\n    default: googleSettings.maxOutputTokens.default,\n    range: {\n      min: googleSettings.maxOutputTokens.min,\n      max: googleSettings.maxOutputTokens.max,\n      step: googleSettings.maxOutputTokens.step,\n    },\n    optionType: 'model',\n    columnSpan: 2,\n  },\n  thinking: {\n    key: 'thinking',\n    label: 'com_endpoint_thinking',\n    labelCode: true,\n    description: 'com_endpoint_google_thinking',\n    descriptionCode: true,\n    type: 'boolean',\n    default: googleSettings.thinking.default,\n    component: 'switch',\n    optionType: 'conversation',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  thinkingBudget: {\n    key: 'thinkingBudget',\n    label: 'com_endpoint_thinking_budget',\n    labelCode: true,\n    description: 'com_endpoint_google_thinking_budget',\n    descriptionCode: true,\n    placeholder: 'com_ui_auto',\n    placeholderCode: true,\n    type: 'number',\n    component: 'input',\n    range: {\n      min: googleSettings.thinkingBudget.min,\n      max: googleSettings.thinkingBudget.max,\n      step: googleSettings.thinkingBudget.step,\n    },\n    optionType: 'conversation',\n    columnSpan: 2,\n  },\n  thinkingLevel: {\n    key: 'thinkingLevel',\n    label: 'com_endpoint_thinking_level',\n    labelCode: true,\n    description: 'com_endpoint_google_thinking_level',\n    descriptionCode: true,\n    type: 'enum',\n    default: ThinkingLevel.unset,\n    component: 'slider',\n    options: [\n      ThinkingLevel.unset,\n      ThinkingLevel.minimal,\n      ThinkingLevel.low,\n      ThinkingLevel.medium,\n      ThinkingLevel.high,\n    ],\n    enumMappings: {\n      [ThinkingLevel.unset]: 'com_ui_auto',\n      [ThinkingLevel.minimal]: 'com_ui_minimal',\n      [ThinkingLevel.low]: 'com_ui_low',\n      [ThinkingLevel.medium]: 'com_ui_medium',\n      [ThinkingLevel.high]: 'com_ui_high',\n    },\n    optionType: 'conversation',\n    columnSpan: 4,\n  },\n  web_search: {\n    key: 'web_search',\n    label: 'com_endpoint_use_search_grounding',\n    labelCode: true,\n    description: 'com_endpoint_google_use_search_grounding',\n    descriptionCode: true,\n    type: 'boolean',\n    default: false,\n    component: 'switch',\n    optionType: 'model',\n    showDefault: false,\n    columnSpan: 2,\n  },\n  url_context: {\n    key: 'url_context',\n    label: 'com_endpoint_use_url_context',\n    labelCode: true,\n    description: 'com_endpoint_google_use_url_context',\n    descriptionCode: true,\n    type: 'boolean',\n    default: false,\n    component: 'switch',\n    optionType: 'model',\n    showDefault: false,\n    columnSpan: 2,\n  },\n};\n\nconst googleConfig: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  google.maxContextTokens,\n  google.maxOutputTokens,\n  google.temperature,\n  google.topP,\n  google.topK,\n  librechat.resendFiles,\n  google.thinking,\n  google.thinkingBudget,\n  google.thinkingLevel,\n  google.web_search,\n  google.url_context,\n  librechat.fileTokenLimit,\n];\n\nconst googleCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst googleCol2: SettingsConfiguration = [\n  google.maxContextTokens,\n  google.maxOutputTokens,\n  google.temperature,\n  google.topP,\n  google.topK,\n  librechat.resendFiles,\n  google.thinking,\n  google.thinkingBudget,\n  google.thinkingLevel,\n  google.web_search,\n  google.url_context,\n  librechat.fileTokenLimit,\n];\n\nconst openAI: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  librechat.maxContextTokens,\n  openAIParams.max_tokens,\n  openAIParams.temperature,\n  openAIParams.top_p,\n  openAIParams.frequency_penalty,\n  openAIParams.presence_penalty,\n  baseDefinitions.stop,\n  librechat.resendFiles,\n  librechat.imageDetail,\n  openAIParams.web_search,\n  openAIParams.reasoning_effort,\n  openAIParams.useResponsesApi,\n  openAIParams.reasoning_summary,\n  openAIParams.reasoning_mode,\n  openAIParams.reasoning_context,\n  openAIParams.verbosity,\n  openAIParams.disableStreaming,\n  librechat.fileTokenLimit,\n];\n\nconst openRouter: SettingsConfiguration = [\n  ...openAI,\n  anthropic.promptCache,\n  anthropic.promptCacheTtl,\n];\n\nconst openAICol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst openAICol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  openAIParams.max_tokens,\n  openAIParams.temperature,\n  openAIParams.top_p,\n  openAIParams.frequency_penalty,\n  openAIParams.presence_penalty,\n  baseDefinitions.stop,\n  librechat.resendFiles,\n  librechat.imageDetail,\n  openAIParams.reasoning_effort,\n  openAIParams.reasoning_summary,\n  openAIParams.reasoning_mode,\n  openAIParams.reasoning_context,\n  openAIParams.verbosity,\n  openAIParams.useResponsesApi,\n  openAIParams.web_search,\n  openAIParams.disableStreaming,\n  librechat.fileTokenLimit,\n];\n\nconst anthropicConfig: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  librechat.maxContextTokens,\n  anthropic.maxOutputTokens,\n  anthropic.temperature,\n  anthropic.topP,\n  anthropic.topK,\n  librechat.resendFiles,\n  anthropic.promptCache,\n  anthropic.promptCacheTtl,\n  anthropic.thinking,\n  anthropic.thinkingBudget,\n  anthropic.effort,\n  anthropic.thinkingDisplay,\n  anthropic.web_search,\n  librechat.fileTokenLimit,\n];\n\nconst anthropicCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst anthropicCol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  anthropic.maxOutputTokens,\n  anthropic.temperature,\n  anthropic.topP,\n  anthropic.topK,\n  librechat.resendFiles,\n  anthropic.promptCache,\n  anthropic.promptCacheTtl,\n  anthropic.thinking,\n  anthropic.thinkingBudget,\n  anthropic.effort,\n  anthropic.thinkingDisplay,\n  anthropic.web_search,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockAnthropic: SettingsConfiguration = [\n  librechat.modelLabel,\n  bedrock.system,\n  librechat.maxContextTokens,\n  bedrock.maxTokens,\n  bedrock.temperature,\n  bedrock.topP,\n  bedrock.topK,\n  baseDefinitions.stop,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.promptCache,\n  bedrock.promptCacheTtl,\n  anthropic.thinking,\n  anthropic.thinkingBudget,\n  anthropic.effort,\n  anthropic.thinkingDisplay,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockMistral: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  librechat.maxContextTokens,\n  bedrock.maxTokens,\n  mistral.temperature,\n  mistral.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockCohere: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  librechat.maxContextTokens,\n  bedrock.maxTokens,\n  cohere.temperature,\n  cohere.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockGeneral: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  librechat.maxContextTokens,\n  meta.temperature,\n  meta.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.promptCache,\n  bedrock.promptCacheTtl,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockAnthropicCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  bedrock.system,\n  baseDefinitions.stop,\n];\n\nconst bedrockAnthropicCol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  bedrock.maxTokens,\n  bedrock.temperature,\n  bedrock.topP,\n  bedrock.topK,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.promptCache,\n  bedrock.promptCacheTtl,\n  anthropic.thinking,\n  anthropic.thinkingBudget,\n  anthropic.effort,\n  anthropic.thinkingDisplay,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockMistralCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst bedrockMistralCol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  bedrock.maxTokens,\n  mistral.temperature,\n  mistral.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockCohereCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst bedrockCohereCol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  bedrock.maxTokens,\n  cohere.temperature,\n  cohere.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockGeneralCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst bedrockGeneralCol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  meta.temperature,\n  meta.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.promptCache,\n  bedrock.promptCacheTtl,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockZAI: SettingsConfiguration = [\n  librechat.modelLabel,\n  librechat.promptPrefix,\n  librechat.maxContextTokens,\n  meta.temperature,\n  meta.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.reasoning_effort,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockZAICol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  librechat.promptPrefix,\n];\n\nconst bedrockZAICol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  meta.temperature,\n  meta.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.reasoning_effort,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockMoonshot: SettingsConfiguration = [\n  librechat.modelLabel,\n  bedrock.system,\n  librechat.maxContextTokens,\n  createDefinition(bedrock.maxTokens, {\n    default: 16384,\n  }),\n  bedrock.temperature,\n  bedrock.topP,\n  baseDefinitions.stop,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.reasoning_effort,\n  librechat.fileTokenLimit,\n];\n\nconst bedrockMoonshotCol1: SettingsConfiguration = [\n  baseDefinitions.model as SettingDefinition,\n  librechat.modelLabel,\n  bedrock.system,\n  baseDefinitions.stop,\n];\n\nconst bedrockMoonshotCol2: SettingsConfiguration = [\n  librechat.maxContextTokens,\n  createDefinition(bedrock.maxTokens, {\n    default: 16384,\n  }),\n  bedrock.temperature,\n  bedrock.topP,\n  librechat.resendFiles,\n  bedrock.region,\n  bedrock.reasoning_effort,\n  librechat.fileTokenLimit,\n];\n\nexport const paramSettings: Record<string, SettingsConfiguration | undefined> = {\n  [EModelEndpoint.openAI]: openAI,\n  [EModelEndpoint.azureOpenAI]: openAI,\n  [EModelEndpoint.custom]: openAI,\n  [Providers.OPENROUTER]: openRouter,\n  [EModelEndpoint.anthropic]: anthropicConfig,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Anthropic}`]: bedrockAnthropic,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.MistralAI}`]: bedrockMistral,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Cohere}`]: bedrockCohere,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Meta}`]: bedrockGeneral,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.AI21}`]: bedrockGeneral,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Amazon}`]: bedrockGeneral,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.DeepSeek}`]: bedrockGeneral,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Moonshot}`]: bedrockMoonshot,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.MoonshotAI}`]: bedrockMoonshot,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.OpenAI}`]: bedrockGeneral,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.ZAI}`]: bedrockZAI,\n  [EModelEndpoint.google]: googleConfig,\n};\n\n/**\n * Maps effective backend param names for OpenAI-compatible/Azure endpoints (as deleted from\n * `llmConfig` via `dropParams`, e.g. `maxTokens`) to their corresponding UI/conversation keys\n * (e.g. `max_tokens`). Native providers (anthropic, google, bedrock, ...) already render these\n * same camelCase names as their UI key (e.g. `topP`), so this alias must only be applied to\n * OpenAI-compatible parameter sets — see `resolveDropParamsUIKeys`.\n */\nconst dropParamsBackendToUIKey: Record<string, string> = {\n  maxTokens: 'max_tokens',\n  topP: 'top_p',\n  frequencyPenalty: 'frequency_penalty',\n  presencePenalty: 'presence_penalty',\n};\n\n/** Endpoint keys whose parameter settings render the OpenAI-compatible (snake_case) UI keys. */\nconst openAILikeParamEndpointKeys: Set<string> = new Set([\n  EModelEndpoint.openAI,\n  EModelEndpoint.azureOpenAI,\n  EModelEndpoint.custom,\n  Providers.OPENROUTER,\n]);\n\n/**\n * Normalizes an admin-configured `dropParams` list into the UI/conversation keys used to hide\n * the matching controls in the settings panels. `endpointKey` should be the same key used to\n * resolve the panel's parameter settings (e.g. `overriddenEndpointKey`); the backend-name alias\n * is only applied for OpenAI-compatible endpoints, since native providers (anthropic, google,\n * bedrock, ...) already use these backend names as their UI key.\n */\nexport function resolveDropParamsUIKeys(\n  dropParams: string[] | undefined,\n  endpointKey: string,\n): Set<string> {\n  if (!dropParams || dropParams.length === 0) {\n    return new Set();\n  }\n  if (!openAILikeParamEndpointKeys.has(endpointKey)) {\n    return new Set(dropParams);\n  }\n  return new Set(dropParams.map((param) => dropParamsBackendToUIKey[param] ?? param));\n}\n\nconst openAIColumns = {\n  col1: openAICol1,\n  col2: openAICol2,\n};\n\nconst bedrockGeneralColumns = {\n  col1: bedrockGeneralCol1,\n  col2: bedrockGeneralCol2,\n};\n\nexport const presetSettings: Record<\n  string,\n  | {\n      col1: SettingsConfiguration;\n      col2: SettingsConfiguration;\n    }\n  | undefined\n> = {\n  [EModelEndpoint.openAI]: openAIColumns,\n  [EModelEndpoint.azureOpenAI]: openAIColumns,\n  [EModelEndpoint.custom]: openAIColumns,\n  [Providers.OPENROUTER]: {\n    col1: openAICol1,\n    col2: [...openAICol2, anthropic.promptCache, anthropic.promptCacheTtl],\n  },\n  [EModelEndpoint.anthropic]: {\n    col1: anthropicCol1,\n    col2: anthropicCol2,\n  },\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Anthropic}`]: {\n    col1: bedrockAnthropicCol1,\n    col2: bedrockAnthropicCol2,\n  },\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.MistralAI}`]: {\n    col1: bedrockMistralCol1,\n    col2: bedrockMistralCol2,\n  },\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Cohere}`]: {\n    col1: bedrockCohereCol1,\n    col2: bedrockCohereCol2,\n  },\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Meta}`]: bedrockGeneralColumns,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.AI21}`]: bedrockGeneralColumns,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Amazon}`]: bedrockGeneralColumns,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.DeepSeek}`]: bedrockGeneralColumns,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.Moonshot}`]: {\n    col1: bedrockMoonshotCol1,\n    col2: bedrockMoonshotCol2,\n  },\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.MoonshotAI}`]: {\n    col1: bedrockMoonshotCol1,\n    col2: bedrockMoonshotCol2,\n  },\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.OpenAI}`]: bedrockGeneralColumns,\n  [`${EModelEndpoint.bedrock}-${BedrockProviders.ZAI}`]: {\n    col1: bedrockZAICol1,\n    col2: bedrockZAICol2,\n  },\n  [EModelEndpoint.google]: {\n    col1: googleCol1,\n    col2: googleCol2,\n  },\n};\n\nexport const agentParamSettings: Record<string, SettingsConfiguration | undefined> = Object.entries(\n  presetSettings,\n).reduce<Record<string, SettingsConfiguration | undefined>>((acc, [key, value]) => {\n  if (value) {\n    acc[key] = value.col2;\n  }\n  return acc;\n}, {});\n\n/**\n * Resolves model-aware defaults for a settings configuration before rendering.\n * Google's `maxOutputTokens` default depends on the selected Gemini model so that\n * current models (2.5 and 3+) surface their 64K output limit instead of the legacy 8K value.\n * Anthropic prompt-cache controls are only surfaced for models that support them.\n */\nexport function applyModelAwareDefaults(\n  settings: SettingsConfiguration,\n  endpoint: string,\n  model?: string,\n): SettingsConfiguration {\n  if (!model) {\n    return settings;\n  }\n  const modelAwareSettings =\n    endpoint === EModelEndpoint.google\n      ? settings.map((setting) => {\n          if (setting.key === 'maxOutputTokens') {\n            return { ...setting, default: googleSettings.maxOutputTokens.reset(model) };\n          }\n          /** The shared thinking budget range is model-agnostic, so it caps Pro below\n           *  its real ceiling and accepts Flash values the provider rejects. The\n           *  maximum and the positive floor move together. `range.min` stays -1 so\n           *  the \"decide automatically\" sentinel remains typeable. */\n          if (setting.key === 'thinkingBudget' && setting.range != null) {\n            const bounds = getGoogleThinkingBudgetBounds(model);\n            if (bounds != null) {\n              return {\n                ...setting,\n                range: {\n                  ...setting.range,\n                  max: bounds.max,\n                  positiveMin: bounds.min,\n                  modelSpecific: true,\n                },\n              };\n            }\n          }\n          return setting;\n        })\n      : settings;\n\n  if (endpoint !== EModelEndpoint.anthropic || supportsPromptCache(model)) {\n    return modelAwareSettings;\n  }\n\n  return modelAwareSettings.filter(\n    (setting) => setting.key !== 'promptCache' && setting.key !== 'promptCacheTtl',\n  );\n}\n","import {\n  actionDelimiter,\n  actionDomainSeparator,\n  isActionTool,\n  type AgentToolOptions,\n  type AllowedCaller,\n} from './types/assistants';\n\nconst actionDomainSeparatorRegex = new RegExp(actionDomainSeparator, 'g');\n\n/**\n * Collapses the encoded-domain suffix of an action tool name to the shape used\n * by runtime tool definitions. The operation id is deliberately preserved.\n */\nexport function normalizeActionToolName(toolName: string): string {\n  if (!isActionTool(toolName)) {\n    return toolName;\n  }\n  const delimiterIndex = toolName.lastIndexOf(actionDelimiter);\n  const prefixEnd = delimiterIndex + actionDelimiter.length;\n  const encodedDomain = toolName.slice(prefixEnd);\n  return toolName.slice(0, prefixEnd) + encodedDomain.replace(actionDomainSeparatorRegex, '_');\n}\n\n/**\n * Removes Code Interpreter as an allowed caller without mutating the input.\n * Tool entries and unrelated options are preserved; an empty entry is removed.\n */\nexport function removeCodeExecutionCaller(\n  toolOptions: AgentToolOptions | undefined,\n): AgentToolOptions | undefined {\n  if (toolOptions == null) {\n    return toolOptions;\n  }\n\n  const normalized: AgentToolOptions = {};\n  for (const [toolName, options] of Object.entries(toolOptions)) {\n    const callers = options.allowed_callers;\n    if (callers?.includes('code_execution') !== true) {\n      normalized[toolName] = options;\n      continue;\n    }\n\n    const allowedCallers = callers.filter(\n      (caller): caller is AllowedCaller => caller !== 'code_execution',\n    );\n    const { allowed_callers: _removed, ...remainingOptions } = options;\n    const nextOptions =\n      allowedCallers.length > 0\n        ? { ...remainingOptions, allowed_callers: allowedCallers }\n        : remainingOptions;\n    if (Object.keys(nextOptions).length > 0) {\n      normalized[toolName] = nextOptions;\n    }\n  }\n\n  return normalized;\n}\n","/**\n * Closed set of resource kinds for sandbox file caching. Defined as a\n * `as const` tuple so the runtime list and the TypeScript union can't\n * drift on future additions — adding a new kind to the tuple updates\n * both at once.\n *\n * - `skill`: shared per skill identity. Cross-user-within-tenant\n *   sharing. Code API sessionKey omits the user dimension.\n *   `version` is required (the skill's monotonic counter scopes the\n *   cache per revision so any edit invalidates the prior cache\n *   entry naturally).\n * - `agent`: shared per agent identity. Same sharing semantic as\n *   skills (agents are addressable resources accessible to a\n *   permission-defined audience).\n * - `user`: user-private. Code API sessionKey is keyed by the\n *   requesting user from auth context. Used for chat attachments\n *   and code-output artifacts.\n */\nexport const CODE_ENV_KINDS = ['skill', 'agent', 'user'] as const;\nexport type CodeEnvKind = (typeof CODE_ENV_KINDS)[number];\n\n/**\n * Typed reference to a file in the code-execution sandbox.\n *\n * `storage_session_id` is intentionally distinct from the *execution*\n * session id at the top level of an execute response — they are\n * different concepts that historically shared the field name\n * `session_id`. This is the long-lived storage session keyed by the\n * resource's identity (skill/agent/user), not the transient\n * sandbox-run session.\n *\n * `kind` and `id` together name the resource that owns this file's\n * storage session. Code API uses them (plus the auth-context tenant\n * id) to derive the sessionKey, which determines who shares the\n * cache. Cross-user sharing for shared resources (skills, agents) is\n * a designed property of the kind switch, not an emergent side\n * effect. See codeapi #1455 / agents #148 / LC #12960.\n *\n * `version` is statically required when `kind === 'skill'` and\n * statically forbidden otherwise via the discriminated union below —\n * the constraint is enforced at compile time, not just by codeapi's\n * runtime validator.\n */\ninterface CodeEnvRefBase {\n  /** Resource identity. Semantics depend on `kind`:\n   *  - `skill`: skill `_id` (sessionKey-meaningful, cross-user shared).\n   *  - `agent`: agent id (sessionKey-meaningful, cross-user shared).\n   *  - `user`: informational only — sessionKey derivation uses the\n   *    requesting user from auth context. Kept on the type for shape\n   *    uniformity across kinds; do not rely on it for routing. */\n  id: string;\n  storage_session_id: string;\n  file_id: string;\n  /** Code API deployment that owns this storage pointer. Legacy refs omit\n   *  the field and are treated as `default`; new writes always persist it. */\n  executionProfile?: CodeExecutionProfile;\n  /** Deployment-specific namespace. Configured stateful environments share\n   * the same wire profile, so this key prevents their file IDs from being\n   * reused against a different Code API server. */\n  executionRouteKey?: string;\n  /** Epoch ms when the file was uploaded to the code env; drives the liveness\n   *  fast-path (distinct from the usage-bumped `updatedAt`). */\n  provisionedAt?: number;\n  /** Actual destination used when uploading this storage object. */\n  sandboxFilename?: string;\n}\n\nexport type CodeExecutionProfile = 'default' | 'stateful';\n\nexport type CodeEnvRef =\n  | (CodeEnvRefBase & { kind: 'skill'; version: number })\n  | (CodeEnvRefBase & { kind: 'agent' })\n  | (CodeEnvRefBase & { kind: 'user' });\n\n/** Deployment-local pointers for a resource that may be used by both Code API profiles. */\nexport type CodeEnvRefMap = Partial<Record<string, CodeEnvRef>>;\n\nexport interface CodeEnvReferenceSet {\n  /** Compatibility pointer for readers that have not adopted profile-aware refs yet. */\n  codeEnvRef?: CodeEnvRef;\n  /** Canonical deployment-local pointers, keyed by trusted execution profile. */\n  codeEnvRefs?: CodeEnvRefMap;\n}\n\nexport function getCodeEnvRefForProfile(\n  refs: CodeEnvReferenceSet | null | undefined,\n  routeKey: string,\n): CodeEnvRef | undefined {\n  const profileRef = refs?.codeEnvRefs?.[routeKey];\n  if (profileRef) {\n    return profileRef;\n  }\n  const legacyRef = refs?.codeEnvRef;\n  if (\n    legacyRef &&\n    (legacyRef.executionRouteKey ?? legacyRef.executionProfile ?? 'default') === routeKey\n  ) {\n    return legacyRef;\n  }\n  return undefined;\n}\n\n/** Adds one profile pointer without discarding the other profile's storage object. */\nexport function mergeCodeEnvRef(\n  refs: CodeEnvReferenceSet | null | undefined,\n  ref: CodeEnvRef,\n): Required<Pick<CodeEnvReferenceSet, 'codeEnvRef' | 'codeEnvRefs'>> {\n  const codeEnvRefs: CodeEnvRefMap = { ...refs?.codeEnvRefs };\n  const legacyRef = refs?.codeEnvRef;\n  if (legacyRef) {\n    codeEnvRefs[legacyRef.executionRouteKey ?? legacyRef.executionProfile ?? 'default'] ??=\n      legacyRef;\n  }\n  const routeKey = ref.executionRouteKey ?? ref.executionProfile ?? 'default';\n  codeEnvRefs[routeKey] = ref;\n  return {\n    codeEnvRef: codeEnvRefs.default ?? codeEnvRefs.stateful ?? ref,\n    codeEnvRefs,\n  };\n}\n\n/** Enumerates every deployment-local pointer, including legacy single-pointer records. */\nexport function getCodeEnvRefs(\n  refs: CodeEnvReferenceSet | null | undefined,\n): Array<[string, CodeEnvRef]> {\n  const merged: CodeEnvRefMap = { ...refs?.codeEnvRefs };\n  const legacyRef = refs?.codeEnvRef;\n  if (legacyRef) {\n    merged[legacyRef.executionRouteKey ?? legacyRef.executionProfile ?? 'default'] ??= legacyRef;\n  }\n  return Object.entries(merged).flatMap(([routeKey, ref]) =>\n    ref ? [[routeKey, ref] as [string, CodeEnvRef]] : [],\n  );\n}\n","import type { TCodeEnvironmentPairingResponse } from '../types';\n\nexport type CodeWorkerShell = 'posix' | 'powershell';\nexport type CodeWorkerPairing = TCodeEnvironmentPairingResponse['pairing'];\n\nexport interface CodeWorkerRunOptions {\n  defaultWorkspace?: boolean;\n  allowWorkspaceWrites?: boolean;\n  allowWorkspaceCommands?: boolean;\n}\n\nexport function isCodeWorkerShell(value: string): value is CodeWorkerShell {\n  return value === 'posix' || value === 'powershell';\n}\n\nfunction quotePosix(value: string): string {\n  return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction quotePowerShell(value: string): string {\n  return `'${value.replace(/'/g, \"''\")}'`;\n}\n\nexport function createCodeWorkerSetupCommand(\n  pairing: CodeWorkerPairing,\n  shell: CodeWorkerShell,\n  options: CodeWorkerRunOptions = {},\n): string {\n  const quote = shell === 'powershell' ? quotePowerShell : quotePosix;\n  const pair = `librechat-code pair ${quote(pairing.endpoint)} ${quote(pairing.code)} --worker-id ${quote(pairing.workerId)}`;\n  const runArgs = [\n    options.defaultWorkspace === false ? null : '--default-workspace',\n    options.allowWorkspaceWrites === true ? '--allow-workspace-writes' : null,\n    options.allowWorkspaceCommands === true ? '--allow-workspace-commands' : null,\n  ].filter((value): value is string => value != null);\n  const run = ['librechat-code run', ...runArgs].join(' ');\n\n  if (shell === 'powershell') {\n    return `${pair}\\n$env:LIBRECHAT_CODE_WORKER_ID = ${quote(pairing.workerId)}\\n${run}`;\n  }\n\n  return `${pair}\\nLIBRECHAT_CODE_WORKER_ID=${quote(pairing.workerId)} ${run}`;\n}\n"],"mappings":";;;;;;;;;;;AAGA,MAAM,0BAA0B;AAChC,MAAM,uCAAuC;AAC7C,MAAa,2BAA2B;AACxC,MAAa,2CAA2C;;;AAIxD,MAAM,0BAA0B,IAAI,IAAY,CAC9C,0BACA,wCACF,CAAC;AAED,MAAM,+BAA+B,IAAI,IAAY,OAAO,OAAOA,sBAAwB,CAAC;;;;;;;;;;;;;;;;;AAuB5F,SAAS,wBAAwB,MAAmC;CAClE,IAAI,OAAO,SAAS,YAAY,SAAS,MACvC;CAEF,MAAM,WAAY,KAAiC;CACnD,IAAI,OAAO,aAAa,YAAY,aAAa,MAC/C;CAEF,MAAM,UAAW,SAAqC;CACtD,OAAO,OAAO,YAAY,WAAW,UAAU,KAAA;AACjD;AAEA,SAAgB,uBACd,OACA,UACwC;CACxC,IAAI,aAAA,cACF,OAAA;CAEF,IAAI,aAAA,WACF,OAAA;CAEF,IAAI,uBAAuB,KAAK,GAC9B,OAAA;AAGJ;;AAaA,SAAS,iBAAiB,OAAwD;CAChF,MAAM,YAAY,MAAM,MAAM,+CAA+C;CAC7E,IAAI,WACF,OAAO;EACL,OAAO,SAAS,UAAU,IAAI,EAAE;EAChC,OAAO,UAAU,MAAM,OAAO,SAAS,UAAU,IAAI,EAAE,IAAI;CAC7D;CAEF,MAAM,WAAW,MAAM,MAAM,2CAA2C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AkB;EAChB,KAAK;EACL,OAAO;EACP,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,MAAM;EACN,SAAS,eAAe,iBAAiB;EACzC,OAAO;GACL,KAAK,eAAe,iBAAiB;GACrC,KAAK,eAAe,iBAAiB;GACrC,MAAM,eAAe,iBAAiB;EACxC;EACA,WAAW;EACX,YAAY;EACZ,YAAY;CACd;CACA,YAAY;EACV,KAAK;EACL,OAAO;EACP,WAAW;EACX,MAAM;EACN,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,aAAa;EACb,iBAAiB;EACjB,YAAY;EACZ,YAAY;CACd;CACA,kBAAkB;EAChB,KAAK;EACL,OAAO;EACP,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,MAAM;EACN,SAAA;EACA,WAAW;EACX,SAAS;;;;;;;;;EAST;EACA,cAAc;SACa;aACD;gBACG;YACJ;eACG;aACF;cACC;YACF;EACzB;EACA,YAAY;EACZ,YAAY;CACd;CACA,iBAAiB;EACf,KAAK;EACL,OAAO;EACP,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,MAAM;EACN,SAAS;EACT,WAAW;EACX,YAAY;EACZ,aAAa;EACb,YAAY;CACd;CACA,YAAY;EACV,KAAK;EACL,OAAO;EACP,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,MAAM;EACN,SAAS;EACT,WAAW;EACX,YAAY;EACZ,aAAa;EACb,YAAY;CACd;CACA,mBAAmB;EACjB,KAAK;EACL,OAAO;EACP,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,MAAM;EACN,SAAA;EACA,WAAW;EACX,SAAS;;;;;EAKT;EACA,cAAc;SACa;aACA;gBACG;iBACC;EAC/B;EACA,YAAY;EACZ,YAAY;CACd;CACA,gBAAgB;EACd,KAAK;EACL,OAAO;EACP,WAAW;EACX,aAAa;EACb,iBAAiB;EACjB,MAAM;EACN,SAAA;EACA,WAAW;EACX,SAAS;;;;EAA+D;EACxE,cAAc;SACW;iBACG;YACL;EACvB;EACA,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