Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

14.4 KB
Raw Blame
import { z } from "zod";
import { ROUTING_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";
import { SUPPORTED_BATCH_ENDPOINTS } from "@/shared/constants/batchEndpoints";
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
import { providerAllowsOptionalApiKey } from "@/shared/constants/providers";
import { HIDEABLE_SIDEBAR_ITEM_IDS } from "@/shared/constants/sidebarVisibility";
import { HIDEABLE_SIDEBAR_GROUP_IDS } from "@/shared/constants/sidebarGroupVisibility";
import {
  isForbiddenUpstreamHeaderName,
  isForbiddenCustomHeaderName,
} from "@/shared/constants/upstreamHeaders";
import { MAX_TIMER_TIMEOUT_MS } from "@/shared/utils/runtimeTimeouts";
import { AUTO_DISABLE_BANNED_SCOPES } from "@/shared/utils/autoDisableBanned";

// Single source of truth: ../settingsSchemas (the schema the runtime settings route validates
// against). Re-exported here so this modular barrel stays in exact lockstep — a divergent local
// copy (introduced by the #3988 lossy modularization) silently dropped 40 fields while gaining a
// few others. The settings-schema parity test guards this; see QUALITY_GATE_PLAYBOOK Parte 6 (G2).
export { updateSettingsSchema } from "../settingsSchemas";

export const legacyResilienceProfileSchema = z.object({
  transientCooldown: z.number().min(0),
  rateLimitCooldown: z.number().min(0),
  maxBackoffLevel: z.number().int().min(0),
  circuitBreakerThreshold: z.number().int().min(0),
  circuitBreakerReset: z.number().min(0),
});

export const legacyResilienceDefaultsSchema = z
  .object({
    requestsPerMinute: z.number().int().min(1).optional(),
    minTimeBetweenRequests: z.number().int().min(0).optional(),
    concurrentRequests: z.number().int().min(1).optional(),
    globalConcurrentRequests: z.number().int().min(0).max(100_000).optional(),
  })
  .strict();

export const requestQueueSettingsSchema = z
  .object({
    autoEnableApiKeyProviders: z.boolean().optional(),
    requestsPerMinute: z.number().int().min(1).optional(),
    minTimeBetweenRequestsMs: z.number().int().min(0).optional(),
    concurrentRequests: z.number().int().min(1).optional(),
    // 0 is an explicit "disable the queue-wait budget" sentinel (see
    // src/lib/resilience/settings/normalize.ts maxWaitMs) — do not clamp it up to 1.
    maxWaitMs: z.number().int().min(0).optional(),
    executionMaxWaitMs: z.number().int().min(1).optional(),
    maxQueueDepth: z.number().int().min(0).max(100_000).optional(),
  })
  .strict();

export const connectionCooldownProfileSchema = z
  .object({
    baseCooldownMs: z.number().int().min(0).optional(),
    useUpstreamRetryHints: z.boolean().optional(),
    // Issue #2100 follow-up: per-profile toggle for upstream 429 hint trust.
    // `null` is an explicit unset sentinel — PATCH handler deletes the key
    // from stored settings so the per-provider default resolves at runtime.
    // `undefined` (key omitted) means "leave existing value unchanged".
    useUpstream429BreakerHints: z.boolean().nullable().optional(),
    maxBackoffSteps: z.number().int().min(0).optional(),
  })
  .strict();

export const providerBreakerProfileSchema = z
  .object({
    failureThreshold: z.number().int().min(1).max(1000).optional(),
    degradationThreshold: z.number().int().min(1).max(1000).optional(),
    resetTimeoutMs: z.number().int().min(1000).optional(),
  })
  .strict()
  .superRefine((value, ctx) => {
    if (
      typeof value.failureThreshold === "number" &&
      value.failureThreshold > 1 &&
      typeof value.degradationThreshold === "number" &&
      value.degradationThreshold >= value.failureThreshold
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "degradationThreshold must be lower than failureThreshold",
        path: ["degradationThreshold"],
      });
    }
  });

export const waitForCooldownSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
    maxRetries: z.number().int().min(0).max(10).optional(),
    maxRetryWaitSec: z.number().int().min(0).max(300).optional(),
  })
  .strict();

// Quota-share combo cooldown-aware retry (Variante A). Bounds mirror
// normalizeComboCooldownWaitSettings: a single wait <= 30s, <= 10 attempts.
export const comboCooldownWaitSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
    maxWaitMs: z.number().int().min(0).max(30000).optional(),
    maxAttempts: z.number().int().min(0).max(10).optional(),
    budgetMs: z.number().int().min(0).max(300000).optional(),
  })
  .strict();

// FASE 2.1: kill-switch for the per-connection quota-share concurrency limit.
// The cap itself comes from each connection's max_concurrent, so only `enabled`
// is configurable here.
export const quotaShareConcurrencyLimitSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
  })
  .strict();

// Whether a stream content stall cools down the account that served it (default off).
export const streamStallCooldownSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
  })
  .strict();

// Mid-stream recovery block. Bounds mirror normalizeStreamRecoverySettings in
// src/lib/resilience/settings/normalize.ts.
export const throughputWatchdogSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
    warmupMs: z.number().int().min(0).max(600_000).optional(),
    windowMs: z.number().int().min(1_000).max(600_000).optional(),
    minUsefulBytesPerSecond: z.number().int().min(1).max(1_000_000).optional(),
    minUsefulBytes: z.number().int().min(1).max(1_000_000).optional(),
  })
  .strict();

export const streamRecoverySettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
    continueMidStream: z.boolean().optional(),
    throughputWatchdog: throughputWatchdogSettingsSchema.optional(),
  })
  .strict();

// Quota preflight cutoff (auth-level account skipping). Thresholds use
// "minimum remaining %" semantics to match the dashboard's quota bars, and the
// per-(provider, window) defaults override the global default per window.
// Values clamp/coerce in normalizeQuotaPreflightSettings — this schema only
// bounds the wire shape.
export const quotaPreflightSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
    defaultThresholdPercent: z.number().int().min(0).max(99).optional(),
    warnThresholdPercent: z.number().int().min(0).max(100).optional(),
    providerWindowDefaults: z
      .record(z.string().min(1), z.record(z.string().min(1), z.number().int().min(0).max(100)))
      .optional(),
  })
  .strict();

export const providerCooldownSettingsSchema = z
  .object({
    enabled: z.boolean().optional(),
    minRetryCooldownMs: z.number().int().min(0).max(300000).optional(),
    maxRetryCooldownMs: z.number().int().min(0).max(3600000).optional(),
  })
  .strict()
  .superRefine((value, ctx) => {
    if (
      typeof value.minRetryCooldownMs === "number" &&
      typeof value.maxRetryCooldownMs === "number" &&
      value.maxRetryCooldownMs < value.minRetryCooldownMs
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "maxRetryCooldownMs must be greater than or equal to minRetryCooldownMs",
        path: ["maxRetryCooldownMs"],
      });
    }
  });

// Global default cadence (minutes) for the background credential health check
// sweep. 0 = disabled; 1440 = 24 hours. Per-connection overrides win.
export const credentialHealthCheckSettingsSchema = z
  .object({
    intervalMinutes: z.number().int().min(0).max(1440).optional(),
  })
  .strict();

// Token-refresh breaker scope + thresholds. Bounds mirror
// normalizeTokenRefreshBreakerSettings: a refresh is a real upstream OAuth
// call, so the cooldown floor stays at 60s (never hammer the provider).
export const tokenRefreshBreakerSettingsSchema = z
  .object({
    scope: z.enum(["provider", "connection"]).optional(),
    failureThreshold: z.number().int().min(1).max(100).optional(),
    cooldownMs: z.number().int().min(60_000).max(86_400_000).optional(),
  })
  .strict();

export const updateResilienceSchema = z
  .object({
    requestQueue: requestQueueSettingsSchema.optional(),
    connectionCooldown: z
      .object({
        oauth: connectionCooldownProfileSchema.optional(),
        apikey: connectionCooldownProfileSchema.optional(),
      })
      .strict()
      .optional(),
    providerBreaker: z
      .object({
        oauth: providerBreakerProfileSchema.optional(),
        apikey: providerBreakerProfileSchema.optional(),
      })
      .strict()
      .optional(),
    waitForCooldown: waitForCooldownSettingsSchema.optional(),
    comboCooldownWait: comboCooldownWaitSettingsSchema.optional(),
    quotaShareConcurrencyLimit: quotaShareConcurrencyLimitSettingsSchema.optional(),
    streamStallCooldown: streamStallCooldownSettingsSchema.optional(),
    streamRecovery: streamRecoverySettingsSchema.optional(),
    providerCooldown: providerCooldownSettingsSchema.optional(),
    // Quota preflight cutoff (auth-level account skipping) — surfaced in the
    // Settings → Routing UI. Mirrors QuotaPreflightSettings in
    // src/lib/resilience/settings/types.ts.
    quotaPreflight: quotaPreflightSettingsSchema.optional(),
    profiles: z
      .object({
        oauth: legacyResilienceProfileSchema.optional(),
        apikey: legacyResilienceProfileSchema.optional(),
      })
      .strict()
      .optional(),
    defaults: legacyResilienceDefaultsSchema.optional(),
    // #6846 Phase 2: per-provider operator overrides for the header-less
    // "provider default" static budget (open-sse/services/providerDefaultRateLimit.ts)
    // and its companion per-connection concurrency cap. Mirrors
    // ProviderQuotaOverrideSettings in src/lib/resilience/settings/types.ts.
    providerQuotaOverrides: z
      .record(
        z.string().min(1),
        z
          .object({
            rpm: z.number().int().min(1).optional(),
            concurrency: z.number().int().min(1).optional(),
            providerConcurrency: z.number().int().min(0).max(100_000).optional(),
          })
          .strict()
      )
      .optional(),
    credentialHealthCheck: credentialHealthCheckSettingsSchema.optional(),
    tokenRefreshBreaker: tokenRefreshBreakerSettingsSchema.optional(),
  })
  .strict()
  .superRefine((value, ctx) => {
    const provided = [
      value.requestQueue,
      value.connectionCooldown,
      value.providerBreaker,
      value.tokenRefreshBreaker,
      value.waitForCooldown,
      value.comboCooldownWait,
      value.quotaShareConcurrencyLimit,
      value.streamStallCooldown,
      value.streamRecovery,
      value.providerCooldown,
      value.quotaPreflight,
      value.profiles,
      value.defaults,
      value.providerQuotaOverrides,
      value.credentialHealthCheck,
    ].some(Boolean);
    if (!provided) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "Must provide resilience settings to update",
        path: [],
      });
    }
  });

export const updateRequireLoginSchema = z
  .object({
    requireLogin: z.boolean().optional(),
    password: z.string().min(4, "Password must be at least 4 characters").optional(),
    // Proof of the current password for a password change. Whether it is required depends on
    // the caller's credential kind (a dashboard session must send it, the local CLI and the
    // bootstrap window must not have to), so the route enforces it, not the schema.
    currentPassword: z.string().optional(),
  })
  .superRefine((value, ctx) => {
    if (value.requireLogin === undefined && !value.password) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "No valid fields to update",
        path: [],
      });
    }
  });

export const updateSystemPromptSchema = z
  .object({
    prompt: z.string().max(50000).optional(), // legacy compat
    prefixPrompt: z.string().max(50000).optional(),
    suffixPrompt: z.string().max(50000).optional(),
    enabled: z.boolean().optional(),
  })
  .strict()
  .superRefine((value, ctx) => {
    if (
      value.prompt === undefined &&
      value.prefixPrompt === undefined &&
      value.suffixPrompt === undefined &&
      value.enabled === undefined
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "No valid fields to update",
        path: [],
      });
    }
  });

export const updateThinkingBudgetSchema = z
  .object({
    mode: z.enum(["passthrough", "auto", "custom", "adaptive"]).optional(),
    customBudget: z.coerce.number().int().min(0).max(131072).optional(),
    effortLevel: z.enum(["none", "low", "medium", "high", "xhigh", "max"]).optional(),
    baseBudget: z.coerce.number().int().min(0).max(131072).optional(),
    complexityMultiplier: z.coerce.number().min(0).optional(),
  })
  .strict()
  .superRefine((value, ctx) => {
    if (
      value.mode === undefined &&
      value.customBudget === undefined &&
      value.effortLevel === undefined &&
      value.baseBudget === undefined &&
      value.complexityMultiplier === undefined
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "No valid fields to update",
        path: [],
      });
    }
  });

export const guideSettingsSaveSchema = z
  .object({
    baseUrl: z.string().trim().min(1).optional(),
    // #3552: the CLI tool cards post `apiKey: null` in cloud mode (the real key is resolved
    // server-side from keyId), and `z.string().optional()` rejected null → 400. Normalize
    // null → undefined so validation passes and the keyId/default path is used.
    apiKey: z.preprocess((v) => (v === null ? undefined : v), z.string().optional()),
    model: z.string().trim().min(1, "Model is required").optional(),
    models: z.array(z.string().trim().min(1, "Models must be non-empty")).min(1).optional(),
    modelLabels: z.record(z.string(), z.string().trim().min(1)).optional(),
    // OpenCode dashboard save forwards the /v1/models catalog the page already
    // loaded. Unknown keys stay so context_length / capabilities are not stripped.
    // Absent catalog keeps the writer's 128K/8K fallback.
    catalog: z.array(z.object({ id: z.string().trim().min(1) }).passthrough()).optional(),
  })
  .refine((data) => !!data.model || !!data.models?.length, {
    message: "Model is required",
    path: ["model"],
  });

// ─── Auto-disable banned/error accounts ───────────────────────────────────
export const updateAutoDisableAccountsSchema = z
  .object({
    enabled: z.boolean(),
    threshold: z.number().int().min(1).max(10).optional(),
    scope: z.enum(AUTO_DISABLE_BANNED_SCOPES).optional(),
  })
  .strict();