File size: 15,616 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**

 * Settings-specific Zod schemas.

 *

 * Extracted from schemas.ts to work around the webpack barrel-file

 * optimization bug that makes large schema barrel exports `undefined`

 * at runtime (see: https://github.com/vercel/next.js/issues/12557).

 */
import { z } from "zod";
import { COMBO_CONFIG_MODES } from "@/shared/constants/comboConfigMode";
import { MAX_REQUEST_BODY_LIMIT_MB, MIN_REQUEST_BODY_LIMIT_MB } from "@/shared/constants/bodySize";
import { HIDEABLE_SIDEBAR_ITEM_IDS, SIDEBAR_SECTIONS } from "@/shared/constants/sidebarVisibility";
import { ACCOUNT_FALLBACK_STRATEGY_VALUES } from "@/shared/constants/routingStrategies";
import { RESPONSES_PREVIOUS_RESPONSE_ID_MODES } from "@/shared/constants/responsesPreviousResponseId";

const signatureCacheModeValues = ["enabled", "bypass", "bypass-strict"] as const;

export const updateSettingsSchema = z.object({
  newPassword: z.string().min(1).max(200).optional(),
  currentPassword: z.string().max(200).optional(),
  theme: z.string().max(50).optional(),
  language: z.string().max(10).optional(),
  requireLogin: z.boolean().optional(),
  enableSocks5Proxy: z.boolean().optional(),
  instanceName: z.string().max(100).optional(),
  customLogoUrl: z.string().max(2000).optional(),
  customLogoBase64: z.string().max(100000).optional(),
  customFaviconUrl: z.string().max(2000).optional(),
  customFaviconBase64: z.string().max(50000).optional(),
  corsOrigins: z.string().max(500).optional(),
  cloudUrl: z.string().max(500).optional(),
  baseUrl: z.string().max(500).optional(),
  setupComplete: z.boolean().optional(),
  blockedProviders: z.array(z.string().max(100)).optional(),
  hideHealthCheckLogs: z.boolean().optional(),
  hideEndpointCloudflaredTunnel: z.boolean().optional(),
  hideEndpointTailscaleFunnel: z.boolean().optional(),
  hideEndpointNgrokTunnel: z.boolean().optional(),
  autoRefreshProviderQuota: z.boolean().optional(),
  autoRefreshProviderQuotaInterval: z.number().int().min(10).max(3600).optional(),
  pinProviderQuotaToHome: z.boolean().optional(),
  showQuickStartOnHome: z.boolean().optional(),
  showProviderTopologyOnHome: z.boolean().optional(),
  localOnlyManageScopeBypassEnabled: z.boolean().optional(),
  localOnlyManageScopeBypassPrefixes: z.array(z.string().max(200)).optional(),
  debugMode: z.boolean().optional(),
  hiddenSidebarItems: z.array(z.enum(HIDEABLE_SIDEBAR_ITEM_IDS)).optional(),
  sidebarSectionOrder: z
    .array(z.enum(SIDEBAR_SECTIONS.map((s) => s.id) as [string, ...string[]]))
    .optional(),
  sidebarItemOrder: z.record(z.string(), z.array(z.string().max(100))).optional(),
  sidebarActivePreset: z.enum(["all", "minimal", "developer", "admin"]).nullable().optional(),
  comboConfigMode: z.enum(COMBO_CONFIG_MODES).optional(),
  codexServiceTier: z
    .object({
      enabled: z.boolean().optional(),
      tier: z.enum(["default", "priority", "flex"]).optional(),
      supportedModels: z.array(z.string().max(200)).max(200).optional(),
    })
    .optional(),
  // Claude Fast Mode: opt-in toggle that asks a paired CLIProxyAPI build
  // (claude-fastmode-spoof) to rewrite SDK-shaped entrypoints so requests can
  // reach Anthropic Fast Mode (speed:"fast"). Default off; only the listed
  // Opus models are gated by the Anthropic binary KT() check. Schema is
  // intentionally permissive on supportedModels so additional eligible model
  // ids can be enabled without a schema bump.
  claudeFastMode: z
    .object({
      enabled: z.boolean().optional(),
      supportedModels: z.array(z.string().max(200)).max(200).optional(),
    })
    .optional(),
  codexSessionAffinityTtlMs: z.number().int().min(0).max(86_400_000).optional(),
  responsesPreviousResponseIdMode: z.enum(RESPONSES_PREVIOUS_RESPONSE_ID_MODES).optional(),
  // Routing settings (#134)
  fallbackStrategy: z.enum(ACCOUNT_FALLBACK_STRATEGY_VALUES).optional(),
  wildcardAliases: z.array(z.object({ pattern: z.string(), target: z.string() })).optional(),
  stickyRoundRobinLimit: z.number().int().min(0).max(1000).optional(),
  requestRetry: z.number().int().min(0).max(10).optional(),
  maxRetryIntervalSec: z.number().int().min(0).max(300).optional(),
  maxBodySizeMb: z
    .number()
    .int()
    .min(MIN_REQUEST_BODY_LIMIT_MB)
    .max(MAX_REQUEST_BODY_LIMIT_MB)
    .optional(),
  // Auto intent classifier settings (multilingual routing)
  intentDetectionEnabled: z.boolean().optional(),
  intentSimpleMaxWords: z.number().int().min(1).max(500).optional(),
  intentExtraCodeKeywords: z.array(z.string().max(100)).optional(),
  intentExtraReasoningKeywords: z.array(z.string().max(100)).optional(),
  intentExtraSimpleKeywords: z.array(z.string().max(100)).optional(),
  // Protocol toggles (default: disabled)
  mcpEnabled: z.boolean().optional(),
  mcpTransport: z.enum(["stdio", "sse", "streamable-http"]).optional(),
  a2aEnabled: z.boolean().optional(),
  wsAuth: z.boolean().optional(),
  // CLI Fingerprint compatibility (per-provider)
  cliCompatProviders: z.array(z.string().max(100)).optional(),
  // CC bridge transforms (issue #2260): config-driven pipeline that normalizes
  // system blocks at the Claude Code bridge so any client (OpenCode, Cline,
  // Cursor, Continue, raw API) ends up with classifier-correct structure.
  ccBridgeTransforms: z
    .object({
      enabled: z.boolean(),
      pipeline: z
        .array(
          z.discriminatedUnion("kind", [
            z.object({
              kind: z.literal("drop_paragraph_if_contains"),
              needles: z.array(z.string().max(500)).max(50),
              caseSensitive: z.boolean().optional(),
            }),
            z.object({
              kind: z.literal("drop_paragraph_if_starts_with"),
              prefixes: z.array(z.string().max(500)).max(50),
              caseSensitive: z.boolean().optional(),
            }),
            z.object({
              kind: z.literal("replace_text"),
              match: z.string().min(1).max(500),
              replacement: z.string().max(500),
              allOccurrences: z.boolean().optional(),
            }),
            z.object({
              kind: z.literal("replace_regex"),
              pattern: z.string().min(1).max(500),
              flags: z.string().max(10).optional(),
              replacement: z.string().max(500),
            }),
            z.object({
              kind: z.literal("drop_block_if_contains"),
              needles: z.array(z.string().max(500)).max(50),
            }),
            z.object({
              kind: z.literal("prepend_system_block"),
              text: z.string().min(1).max(2000),
              idempotencyKey: z.string().max(100).optional(),
            }),
            z.object({
              kind: z.literal("append_system_block"),
              text: z.string().min(1).max(2000),
              idempotencyKey: z.string().max(100).optional(),
            }),
            z.object({
              kind: z.literal("inject_billing_header"),
              entrypoint: z.string().min(1).max(50),
              versionFormat: z.enum(["ex-machina", "omniroute-daystamp"]),
              cchAlgo: z.enum(["sha256-first-user", "xxhash64-body", "static-zero"]),
              version: z.string().max(50).optional(),
            }),
          ])
        )
        .max(50),
    })
    .optional(),
  // System Transforms (issue #2260 v2): generic per-provider DSL covering
  // native `claude`, `anthropic-compatible-cc-*` bridge, and any other
  // provider key. Adds `obfuscate_words` op kind on top of the base set.
  systemTransforms: z
    .object({
      providers: z.record(
        z.string().max(100),
        z.object({
          enabled: z.boolean(),
          pipeline: z
            .array(
              z.discriminatedUnion("kind", [
                z.object({
                  kind: z.literal("drop_paragraph_if_contains"),
                  needles: z.array(z.string().max(500)).max(50),
                  caseSensitive: z.boolean().optional(),
                }),
                z.object({
                  kind: z.literal("drop_paragraph_if_starts_with"),
                  prefixes: z.array(z.string().max(500)).max(50),
                  caseSensitive: z.boolean().optional(),
                }),
                z.object({
                  kind: z.literal("replace_text"),
                  match: z.string().min(1).max(500),
                  replacement: z.string().max(500),
                  allOccurrences: z.boolean().optional(),
                }),
                z.object({
                  kind: z.literal("replace_regex"),
                  pattern: z.string().min(1).max(500),
                  flags: z.string().max(10).optional(),
                  replacement: z.string().max(500),
                }),
                z.object({
                  kind: z.literal("drop_block_if_contains"),
                  needles: z.array(z.string().max(500)).max(50),
                }),
                z.object({
                  kind: z.literal("prepend_system_block"),
                  text: z.string().min(1).max(2000),
                  idempotencyKey: z.string().max(100).optional(),
                }),
                z.object({
                  kind: z.literal("append_system_block"),
                  text: z.string().min(1).max(2000),
                  idempotencyKey: z.string().max(100).optional(),
                }),
                z.object({
                  kind: z.literal("inject_billing_header"),
                  entrypoint: z.string().min(1).max(50),
                  versionFormat: z.enum(["ex-machina", "omniroute-daystamp"]),
                  cchAlgo: z.enum(["sha256-first-user", "xxhash64-body", "static-zero"]),
                  version: z.string().max(50).optional(),
                }),
                z.object({
                  kind: z.literal("obfuscate_words"),
                  words: z.array(z.string().max(100)).max(200),
                  targets: z
                    .array(z.enum(["system", "messages", "tools"]))
                    .max(3)
                    .optional(),
                }),
              ])
            )
            .max(50),
        })
      ),
    })
    .optional(),
  // Strip provider/model prefix at proxy layer (e.g. "openai/gpt-4" → "gpt-4")
  stripModelPrefix: z.boolean().optional(),
  // Cache control preservation mode
  alwaysPreserveClientCache: z.enum(["auto", "always", "never"]).optional(),
  antigravitySignatureCacheMode: z.enum(signatureCacheModeValues).optional(),
  // Adaptive Volume Routing
  adaptiveVolumeRouting: z.boolean().optional(),
  // Usage token buffer — safety margin added to reported prompt/input token counts.
  // Prevents CLI tools from overrunning context windows. Set to 0 to disable.
  usageTokenBuffer: z.number().int().min(0).max(50000).optional(),
  // Custom CLI agent definitions for ACP
  customAgents: z
    .array(
      z.object({
        id: z.string().max(50),
        name: z.string().max(100),
        binary: z.string().max(200),
        versionCommand: z.string().max(300),
        providerAlias: z.string().max(50),
        spawnArgs: z.array(z.string().max(200)),
        protocol: z.enum(["stdio", "http"]),
      })
    )
    .optional(),
  // SkillsMP marketplace API key
  skillsmpApiKey: z.string().max(200).optional(),
  // Active skills provider (single source of truth for skills page)
  skillsProvider: z.enum(["skillsmp", "skillssh"]).optional(),
  // models.dev sync settings
  modelsDevSyncEnabled: z.boolean().optional(),
  modelsDevSyncInterval: z.number().int().min(3600000).max(604800000).optional(),
  // Vision Bridge settings
  visionBridgeEnabled: z.boolean().optional(),
  visionBridgeModel: z.string().max(200).optional(),
  visionBridgePrompt: z.string().max(5000).optional(),
  visionBridgeTimeout: z.number().int().min(1000).max(300000).optional(),
  visionBridgeMaxImages: z.number().int().min(1).max(20).optional(),
  // Missing settings
  lkgpEnabled: z.boolean().optional(),
  backgroundDegradation: z.unknown().optional(),
  bruteForceProtection: z.boolean().optional(),
  // Auto-routing settings
  autoRoutingEnabled: z.boolean().optional(),
  autoRoutingDefaultVariant: z
    .enum(["lkgp", "coding", "fast", "cheap", "offline", "smart"])
    .optional(),
  proxyEnabled: z.boolean().optional(),
  perKeyProxyEnabled: z.boolean().optional(),
  // CLIProxyAPI connection settings
  cliproxyapi_fallback_enabled: z.boolean().optional(),
  cliproxyapi_url: z.string().url().max(500).optional(),
  cliproxyapi_fallback_codes: z.string().max(200).optional(),
  // CLIProxyAPI model mapping (Record<string, string>)
  cliproxyapi_model_mapping: z.record(z.string(), z.string()).optional(),
});

export const databaseSettingsSchema = z.object(
  {
    // Logs settings
    logs: z.object({
      detailedLogsEnabled: z.boolean(),
      callLogPipelineEnabled: z.boolean(),
      maxDetailSizeKb: z.number().int().nonnegative(),
      ringBufferSize: z.number().int().min(100).max(10000),
    }),

    // Backup settings
    backup: z.object({
      autoBackupEnabled: z.boolean(),
      autoBackupFrequency: z
        .literal("never")
        .or(z.literal("daily"))
        .or(z.literal("weekly"))
        .or(z.literal("monthly")),
      keepLastNBackups: z.number().int().min(1).max(100),
    }),

    // Cache settings
    cache: z.object({
      semanticCacheEnabled: z.boolean(),
      semanticCacheMaxSize: z.number().int().min(10).max(1000),
      semanticCacheTTL: z.number().int().min(60000),
      promptCacheEnabled: z.boolean(),
      promptCacheStrategy: z.literal("auto").or(z.literal("system-only")).or(z.literal("manual")),
      alwaysPreserveClientCache: z.literal("auto").or(z.literal("always")).or(z.literal("never")),
    }),

    // Retention settings
    retention: z.object({
      quotaSnapshots: z.number().int().min(1).max(3650), // Max 10 years
      compressionAnalytics: z.number().int().min(1).max(365),
      mcpAudit: z.number().int().min(1).max(365),
      a2aEvents: z.number().int().min(1).max(365),
      callLogs: z.number().int().min(1).max(3650),
      usageHistory: z.number().int().min(1).max(3650),
      memoryEntries: z.number().int().min(1).max(3650),
      autoCleanupEnabled: z.boolean(),
    }),

    // Aggregation settings
    aggregation: z.object({
      enabled: z.boolean(),
      rawDataRetentionDays: z.number().int().min(1).max(3650),
      granularity: z.literal("hourly").or(z.literal("daily")).or(z.literal("weekly")),
    }),

    // Optimization settings
    optimization: z.object({
      autoVacuumMode: z.literal("NONE").or(z.literal("FULL")).or(z.literal("INCREMENTAL")),
      scheduledVacuum: z
        .literal("never")
        .or(z.literal("daily"))
        .or(z.literal("weekly"))
        .or(z.literal("monthly")),
      vacuumHour: z.number().int().min(0).max(23),
      pageSize: z.number().multipleOf(512).min(512).max(65536),
      cacheSize: z.number().int().min(-1000000).max(1000000),
      optimizeOnStartup: z.boolean(),
    }),

    // Skip location and stats as they're read-only
}).strict();

export type DatabaseSettingsSchema = z.infer<typeof databaseSettingsSchema>;

export const featureFlagUpdateSchema = z.object({
  key: z.string().min(1),
  value: z.string().optional(),
});