File size: 17,625 Bytes
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a457004
 
 
 
 
 
4e7af9b
 
 
 
 
a457004
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85a51a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a457004
 
 
 
 
 
 
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92e96ba
4e7af9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f21206
4e7af9b
 
 
85a51a2
 
 
 
 
1fc102a
 
85a51a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e7af9b
85a51a2
 
4e7af9b
 
 
 
85a51a2
 
1f21206
85a51a2
1f21206
85a51a2
 
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a457004
 
 
1f21206
 
 
 
a457004
 
 
1f21206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
/**
 * Models REST API
 *
 * GET  /api/models          โ€” ่Žทๅ–ๅฏ็”จๆจกๅž‹ๅˆ—่กจ
 * GET  /api/models/current  โ€” ่Žทๅ–ๅฝ“ๅ‰้€‰ไธญ็š„ๆจกๅž‹
 * PUT  /api/models/current  โ€” ๅˆ‡ๆขๆจกๅž‹
 * GET  /api/effort          โ€” ่Žทๅ– Effort ็ญ‰็บง
 * PUT  /api/effort          โ€” ่ฎพ็ฝฎ Effort ็ญ‰็บง
 */

import { SettingsService } from '../services/settingsService.js'
import { ProviderService } from '../services/providerService.js'
import { attributionHeaderEnvForModel } from '../services/attributionHeaderPolicy.js'
import { ApiError, errorResponse } from '../middleware/errorHandler.js'
import { hasOpenAIAuthLogin } from '../../utils/auth.js'
import { OPENAI_CODEX_MODEL_CATALOG } from '../../services/openaiAuth/models.js'
import {
  OPENAI_OFFICIAL_PROVIDER_ID,
  OPENAI_OFFICIAL_PROVIDER_NAME,
  isOpenAIOfficialProviderId,
} from '../services/openaiOfficialProvider.js'

// โ”€โ”€โ”€ Fallback models (used when no provider is configured) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

const DEFAULT_MODELS = [
  {
    id: 'claude-opus-4-7',
    name: 'Opus 4.7',
    description: 'Most capable for ambitious work',
    context: '1m',
  },
  {
    id: 'claude-sonnet-4-6',
    name: 'Sonnet 4.6',
    description: 'Most efficient for everyday tasks',
    context: '200k',
  },
  {
    id: 'claude-haiku-4-5',
    name: 'Haiku 4.5',
    description: 'Fastest for quick answers',
    context: '200k',
  },
] as const

const EFFORT_LEVELS = ['low', 'medium', 'high', 'max'] as const

const DEFAULT_MODEL = 'claude-opus-4-7'
const DEFAULT_EFFORT = 'medium'

const settingsService = new SettingsService()
const providerService = new ProviderService()

type ApiModelInfo = {
  id: string
  name: string
  description: string
  context: string
}

function addUniqueModel(
  models: ApiModelInfo[],
  model: ApiModelInfo | null,
): void {
  if (!model || !model.id.trim()) {
    return
  }

  if (models.some(existing => existing.id === model.id)) {
    return
  }

  models.push(model)
}

function buildProviderModelList(models: {
  main: string
  haiku: string
  sonnet: string
  opus: string
}): ApiModelInfo[] {
  const modelList: ApiModelInfo[] = []

  addUniqueModel(modelList, {
    id: models.main,
    name: models.main,
    description: 'Main model',
    context: '',
  })
  addUniqueModel(modelList, models.haiku
    ? {
        id: models.haiku,
        name: models.haiku,
        description: 'Haiku model',
        context: '',
      }
    : null)
  addUniqueModel(modelList, models.sonnet
    ? {
        id: models.sonnet,
        name: models.sonnet,
        description: 'Sonnet model',
        context: '',
      }
    : null)
  addUniqueModel(modelList, models.opus
    ? {
        id: models.opus,
        name: models.opus,
        description: 'Opus model',
        context: '',
      }
    : null)

  return modelList
}

function buildOpenAIModelList(): ApiModelInfo[] {
  return OPENAI_CODEX_MODEL_CATALOG.map(model => ({
    id: model.value,
    name: model.label,
    description: model.description,
    context: '',
  }))
}

function getEnvConfiguredAnthropicModels(): ApiModelInfo[] {
  return buildProviderModelList({
    main: process.env.ANTHROPIC_MODEL?.trim() || '',
    haiku: process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL?.trim() || '',
    sonnet: process.env.ANTHROPIC_DEFAULT_SONNET_MODEL?.trim() || '',
    opus: process.env.ANTHROPIC_DEFAULT_OPUS_MODEL?.trim() || '',
  })
}

function getOpenAIAuthModels(): ApiModelInfo[] {
  if (!hasOpenAIAuthLogin()) {
    return []
  }

  return buildOpenAIModelList()
}

function getStandaloneModelList(): ApiModelInfo[] {
  const models = [...getEnvConfiguredAnthropicModels()]

  if (models.length === 0) {
    models.push(...DEFAULT_MODELS)
  }

  for (const model of getOpenAIAuthModels()) {
    addUniqueModel(models, model)
  }

  return models
}

function normalizeEffortLevel(value: unknown): (typeof EFFORT_LEVELS)[number] {
  return typeof value === 'string' && EFFORT_LEVELS.includes(value as (typeof EFFORT_LEVELS)[number])
    ? value as (typeof EFFORT_LEVELS)[number]
    : DEFAULT_EFFORT
}

// โ”€โ”€โ”€ CLI provider model cache (fetched from external APIs) โ”€โ”€โ”€โ”€โ”€

let cliProviderModelCache: ApiModelInfo[] | null = null
let cliProviderModelCacheTime = 0
const CLI_PROVIDER_CACHE_TTL = 5 * 60 * 1000 // 5 minutes

export function invalidateCliProviderModelCache(): void {
  cliProviderModelCache = null
  cliProviderModelCacheTime = 0
}

async function fetchCliProviderModels(): Promise<ApiModelInfo[]> {
  if (cliProviderModelCache && Date.now() - cliProviderModelCacheTime < CLI_PROVIDER_CACHE_TTL) {
    return cliProviderModelCache
  }

  try {
    // Read ~/.claude.json directly โ€” avoids importing CLI-side config modules
    const { homedir } = await import('node:os')
    const { readFileSync } = await import('node:fs')
    const { join } = await import('node:path')
    let config: Record<string, unknown> = {}
    try {
      const raw = readFileSync(join(homedir(), '.claude.json'), 'utf8')
      config = JSON.parse(raw)
    } catch {
      return []
    }
    const authProvider = config.authProvider as string | undefined

    // โ”€โ”€ OpenCode โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (authProvider === 'opencode' && config.openCodeApiKey) {
      try {
        const res = await fetch('https://models.dev/api.json')
        if (res.ok) {
          const data = await res.json() as any
          const opencodeModels = data?.opencode?.models || {}
          const models: ApiModelInfo[] = []

          for (const [modelId, modelCfg] of Object.entries(opencodeModels) as [string, any][]) {
            if (modelCfg.status === 'deprecated') continue
            const isFree = modelCfg.cost?.input === 0 && modelCfg.cost?.output === 0
            models.push({
              id: modelId,
              name: modelCfg.name || modelId,
              description: isFree ? 'Free model' : 'Paid model',
              context: '',
            })
          }

          if (models.length > 0) {
            cliProviderModelCache = models
            cliProviderModelCacheTime = Date.now()
            return models
          }
        }
      } catch {
        // fall through
      }
    }

    // โ”€โ”€ OpenRouter โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (authProvider === 'openrouter' && config.openRouterApiKey) {
      try {
        const res = await fetch('https://openrouter.ai/api/v1/models', {
          headers: { Authorization: `Bearer ${config.openRouterApiKey}` },
        })
        if (res.ok) {
          const data = await res.json() as any
          const models: ApiModelInfo[] = (data.data || []).map((m: any) => ({
            id: m.id,
            name: m.name || m.id,
            description: m.description || '',
            context: String(m.context_length || ''),
          }))

          if (models.length > 0) {
            cliProviderModelCache = models
            cliProviderModelCacheTime = Date.now()
            return models
          }
        }
      } catch {
        // fall through
      }
    }

    // โ”€โ”€ NVIDIA NIM โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (authProvider === 'nvidia' && config.nvidiaApiKey) {
      try {
        const res = await fetch('https://integrate.api.nvidia.com/v1/models', {
          headers: { Authorization: `Bearer ${config.nvidiaApiKey}` },
        })
        if (res.ok) {
          const data = await res.json() as any
          const models: ApiModelInfo[] = (data.data || []).map((m: any) => ({
            id: m.id,
            name: m.id,
            description: m.owned_by || '',
            context: '',
          }))

          if (models.length > 0) {
            cliProviderModelCache = models
            cliProviderModelCacheTime = Date.now()
            return models
          }
        }
      } catch {
        // fall through
      }
    }
  } catch {
    // fall through
  }

  return []
}

// โ”€โ”€โ”€ Router โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

export async function handleModelsApi(
  req: Request,
  url: URL,
  segments: string[],
): Promise<Response> {
  try {
    const resource = segments[1] // 'models' | 'effort'
    const sub = segments[2] // 'current' | undefined

    // โ”€โ”€ /api/effort โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    if (resource === 'effort') {
      return await handleEffort(req)
    }

    // โ”€โ”€ /api/models/* โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    switch (sub) {
      case undefined:
        // GET /api/models โ€” ไผ˜ๅ…ˆไปŽๆฟ€ๆดป็š„ Provider ่ฏปๅ–ๆจกๅž‹ๅˆ—่กจ
        if (req.method !== 'GET') throw methodNotAllowed(req.method)
        return await handleModelsList()

      case 'current':
        return await handleCurrentModel(req)

      default:
        throw ApiError.notFound(`Unknown models endpoint: ${sub}`)
    }
  } catch (error) {
    return errorResponse(error)
  }
}

// โ”€โ”€โ”€ Handlers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

export async function readCliAuthProvider(): Promise<{
  authProvider?: 'anthropic' | 'openai' | 'openrouter' | 'local' | 'opencode' | 'nvidia'
} | null> {
  try {
    const { homedir } = await import('node:os')
    const { readFileSync } = await import('node:fs')
    const { join } = await import('node:path')
    const raw = readFileSync(join(homedir(), '.claude.json'), 'utf8')
    return JSON.parse(raw)
  } catch {
    return null
  }
}

const CLI_PROVIDER_NAMES: Record<string, string> = {
  opencode: 'OpenCode Zen',
  nvidia: 'NVIDIA',
  openrouter: 'OpenRouter',
  local: 'Local',
  anthropic: 'Anthropic',
  openai: 'OpenAI',
}

async function handleModelsList(): Promise<Response> {
  const cliConfig = await readCliAuthProvider()
  const cliAuthProvider = cliConfig?.authProvider

  const { providers, activeId } = await providerService.listProviders()

  if (activeId) {
    const activeProvider = providers.find((p) => p.id === activeId)
    if (activeProvider) {
      const presetType = activeProvider.presetId?.replace(/^tui-/, '')
      if (presetType && cliAuthProvider === presetType) {
        const cliModels = await fetchCliProviderModels()
        if (cliModels.length > 0) {
          return Response.json({
            models: cliModels,
            provider: { id: activeProvider.id, name: activeProvider.name },
          })
        }
      }

      if (isOpenAIOfficialProviderId(activeId)) {
        return Response.json({
          models: buildOpenAIModelList(),
          provider: { id: OPENAI_OFFICIAL_PROVIDER_ID, name: OPENAI_OFFICIAL_PROVIDER_NAME },
        })
      }

      return Response.json({
        models: buildProviderModelList(activeProvider.models),
        provider: { id: activeProvider.id, name: activeProvider.name },
      })
    }
  }

  if (cliAuthProvider && cliAuthProvider !== 'anthropic' && cliAuthProvider !== 'openai') {
    const cliModels = await fetchCliProviderModels()
    return Response.json({
      models: cliModels,
      provider: {
        id: `cli-${cliAuthProvider}`,
        name: CLI_PROVIDER_NAMES[cliAuthProvider] || cliAuthProvider,
      },
    })
  }

  return Response.json({ models: getStandaloneModelList(), provider: null })
}

async function handleCurrentModel(req: Request): Promise<Response> {
  if (req.method === 'GET') {
    // Build the full model list: prefer active provider's models, fall back to defaults
    const { providers, activeId } = await providerService.listProviders()
    const isOpenAIProviderActive = isOpenAIOfficialProviderId(activeId)
    const activeProvider = activeId ? providers.find((p) => p.id === activeId) : null
    const settings = activeProvider || isOpenAIProviderActive
      ? await providerService.getManagedSettings()
      : await settingsService.getUserSettings()
    const explicitModel = (settings.model as string) || ''
    const contextTier = (settings.modelContext as string) || undefined
    const env = (settings.env as Record<string, string>) || {}
    const envModel = process.env.ANTHROPIC_MODEL?.trim() || ''

    let currentModelId: string
    let currentModelName: string

    if (isOpenAIProviderActive) {
      currentModelId = explicitModel || env.ANTHROPIC_MODEL || 'gpt-5.3-codex'
      currentModelName = currentModelId
    } else if (activeProvider) {
      // Provider is active โ€” only use the provider-managed cc-haha settings.
      // This avoids leaking global ~/.claude/settings.json model choices into
      // the active provider flow.
      const providerEnvModel = env.ANTHROPIC_MODEL
      if (providerEnvModel && !explicitModel) {
        currentModelId = providerEnvModel
        currentModelName = providerEnvModel
      } else {
        currentModelId = explicitModel || providerEnvModel || activeProvider.models.main
        currentModelName = currentModelId
      }
    } else {
      // No provider โ€” use settings model with context tier
      currentModelId = explicitModel || envModel || DEFAULT_MODEL
      currentModelName = currentModelId
    }

    const lookupId = contextTier ? `${currentModelId}:${contextTier}` : currentModelId

    // Build available models for name lookup
    const cliModelsFallback = !isOpenAIProviderActive && !activeProvider
      ? await fetchCliProviderModels()
      : []
    const availableModels = isOpenAIProviderActive
      ? buildOpenAIModelList()
      : activeProvider
        ? buildProviderModelList(activeProvider.models)
        : cliModelsFallback.length > 0
          ? cliModelsFallback
          : getStandaloneModelList()

    const modelEntry = availableModels.find((m) => m.id === lookupId)
      || availableModels.find((m) => m.id === currentModelId)
      || {
        id: currentModelId,
        name: currentModelName,
        description: 'Custom model',
        context: contextTier || 'unknown',
      }

    return Response.json({ model: { ...modelEntry, context: contextTier || modelEntry.context } })
  }

  if (req.method === 'PUT') {
    const body = await parseJsonBody(req)
    const modelId = body.modelId
    if (typeof modelId !== 'string' || !modelId) {
      throw ApiError.badRequest('Missing or invalid "modelId" in request body')
    }

    // Parse composite IDs like 'claude-opus-4-7-20250610:1m'
    // Persist the base model ID for CLI compatibility and context tier separately
    const colonIdx = modelId.indexOf(':')
    const baseId = colonIdx !== -1 ? modelId.slice(0, colonIdx) : modelId
    const contextTier = colonIdx !== -1 ? modelId.slice(colonIdx + 1) : undefined

    const updates: Record<string, unknown> = { model: baseId }
    if (contextTier) {
      updates.modelContext = contextTier
    } else {
      // Clear context tier when switching to a non-composite model
      updates.modelContext = undefined
    }
    const { activeId } = await providerService.listProviders()
    if (activeId) {
      const currentManagedSettings = await providerService.getManagedSettings()
      const currentEnv =
        (currentManagedSettings.env as Record<string, string> | undefined) ?? {}
      await providerService.updateManagedSettings({
        ...updates,
        env: {
          ...currentEnv,
          ...attributionHeaderEnvForModel(baseId),
        },
      })
    } else {
      await settingsService.updateUserSettings(updates)
    }
    return Response.json({ ok: true, model: modelId })
  }

  throw methodNotAllowed(req.method)
}

async function handleEffort(req: Request): Promise<Response> {
  if (req.method === 'GET') {
    const settings = await settingsService.getUserSettings()
    const level = normalizeEffortLevel(settings.effort)
    return Response.json({ level, available: EFFORT_LEVELS })
  }

  if (req.method === 'PUT') {
    const body = await parseJsonBody(req)
    const level = body.level
    if (typeof level !== 'string') {
      throw ApiError.badRequest('Missing or invalid "level" in request body')
    }
    if (!EFFORT_LEVELS.includes(level as (typeof EFFORT_LEVELS)[number])) {
      throw ApiError.badRequest(
        `Invalid effort level: "${level}". Valid levels: ${EFFORT_LEVELS.join(', ')}`,
      )
    }
    await settingsService.updateUserSettings({ effort: level })
    return Response.json({ ok: true, level })
  }

  throw methodNotAllowed(req.method)
}

// โ”€โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

async function parseJsonBody(req: Request): Promise<Record<string, unknown>> {
  try {
    return (await req.json()) as Record<string, unknown>
  } catch {
    throw ApiError.badRequest('Invalid JSON body')
  }
}

function methodNotAllowed(method: string): ApiError {
  return new ApiError(405, `Method ${method} not allowed`, 'METHOD_NOT_ALLOWED')
}