-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathprovider.tsx
More file actions
1818 lines (1705 loc) · 52.7 KB
/
provider.tsx
File metadata and controls
1818 lines (1705 loc) · 52.7 KB
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from 'react'
import type { LocalJSXCommandCall, LocalJSXCommandOnDone } from '../../types/command.js'
import { COMMON_HELP_ARGS, COMMON_INFO_ARGS } from '../../constants/xml.js'
import {
ProviderManager,
type ProviderManagerResult,
} from '../../components/ProviderManager.js'
import TextInput from '../../components/TextInput.js'
import {
Select,
type OptionWithDescription,
} from '../../components/CustomSelect/index.js'
import { Dialog } from '../../components/design-system/Dialog.js'
import { LoadingState } from '../../components/design-system/LoadingState.js'
import { useCodexOAuthFlow } from '../../components/useCodexOAuthFlow.js'
import { useTerminalSize } from '../../hooks/useTerminalSize.js'
import { Box, Text } from '../../ink.js'
import { probeRouteReadiness } from '../../integrations/discoveryService.js'
import {
getProviderPresetUiMetadata,
getRouteLabel,
resolveRouteIdFromBaseUrl,
} from '../../integrations/index.js'
import {
type CodexOAuthTokens,
} from '../../services/api/codexOAuth.js'
import {
DEFAULT_CODEX_BASE_URL,
DEFAULT_OPENAI_BASE_URL,
isLocalProviderUrl,
resolveCodexApiCredentials,
resolveProviderRequest,
} from '../../services/api/providerConfig.js'
import {
applySavedProfileToCurrentSession as applySharedProfileToCurrentSession,
buildCodexOAuthProfileEnv as buildSharedCodexOAuthProfileEnv,
buildCodexProfileEnv,
buildGeminiProfileEnv,
buildMistralProfileEnv,
buildOllamaProfileEnv,
buildOpenAIProfileEnv,
createProfileFile,
DEFAULT_GEMINI_BASE_URL,
DEFAULT_GEMINI_MODEL,
DEFAULT_MISTRAL_BASE_URL,
DEFAULT_MISTRAL_MODEL,
deleteProfileFile,
loadProfileFile,
maskSecretForDisplay,
redactSecretValueForDisplay,
sanitizeApiKey,
sanitizeProviderConfigValue,
saveProfileFile,
type ProfileEnv,
type ProfileFile,
type ProviderProfile,
} from '../../utils/providerProfile.js'
import {
getGeminiProjectIdHint,
mayHaveGeminiAdcCredentials,
} from '../../utils/geminiAuth.js'
import {
readGeminiAccessToken,
saveGeminiAccessToken,
} from '../../utils/geminiCredentials.js'
import { isBareMode } from '../../utils/envUtils.js'
import {
getGoalDefaultOpenAIModel,
normalizeRecommendationGoal,
rankOllamaModels,
recommendOllamaModel,
type RecommendationGoal,
} from '../../utils/providerRecommendation.js'
import {
getOllamaChatBaseUrl,
getLocalOpenAICompatibleProviderLabel,
type OllamaGenerationReadiness,
} from '../../utils/providerDiscovery.js'
export function buildProviderManagerCompletion(result?: ProviderManagerResult): {
message: string
metaMessages?: string[]
} {
const message =
result?.message ??
(result?.action === 'saved'
? 'Provider profile updated'
: 'Provider manager closed')
const metaMessages =
result?.action === 'activated' && result.activeProviderName
? [
`<system-reminder>Provider switched mid-session to ${result.activeProviderName}${
result.activeProviderModel
? ` using model ${result.activeProviderModel}`
: ''
}. Use this provider/model for subsequent requests unless the user switches again.</system-reminder>`,
]
: undefined
return { message, metaMessages }
}
function describeOllamaReadinessIssue(
readiness: OllamaGenerationReadiness,
options?: {
baseUrl?: string
allowManualFallback?: boolean
},
): string {
const endpoint = options?.baseUrl ?? 'http://localhost:11434'
if (readiness.state === 'unreachable') {
return `Could not reach Ollama at ${endpoint}. Start Ollama first, then run /provider again.`
}
if (readiness.state === 'no_models') {
const manualSuffix = options?.allowManualFallback
? ', or enter details manually'
: ''
return `Ollama is running, but no installed models were found. Pull a chat model such as qwen2.5-coder:7b or llama3.1:8b first${manualSuffix}.`
}
if (readiness.state === 'generation_failed') {
const modelHint = readiness.probeModel ?? 'the selected model'
const detailSuffix = readiness.detail
? ` Details: ${readiness.detail}.`
: ''
const manualSuffix = options?.allowManualFallback
? ' You can also enter details manually.'
: ''
return `Ollama is reachable and models are installed, but a generation probe failed for ${modelHint}.${detailSuffix} Run "ollama run ${modelHint}" once and retry.${manualSuffix}`
}
return ''
}
type ProviderChoice = 'auto' | ProviderProfile | 'codex-oauth' | 'clear'
type Step =
| { name: 'choose' }
| { name: 'auto-goal' }
| { name: 'auto-detect'; goal: RecommendationGoal }
| { name: 'ollama-detect' }
| { name: 'openai-key'; defaultModel: string }
| { name: 'openai-base'; apiKey: string; defaultModel: string }
| {
name: 'openai-model'
apiKey: string
baseUrl: string | null
defaultModel: string
}
| { name: 'mistral-key'; defaultModel: string }
| { name: 'mistral-base'; apiKey: string; defaultModel: string }
| {
name: 'mistral-model'
apiKey: string
baseUrl: string | null
defaultModel: string
}
| { name: 'gemini-auth-method' }
| { name: 'gemini-key' }
| { name: 'gemini-access-token' }
| {
name: 'gemini-model'
apiKey?: string
authMode: 'api-key' | 'access-token' | 'adc'
}
| { name: 'codex-oauth' }
| { name: 'codex-check' }
type CurrentProviderSummary = {
providerLabel: string
modelLabel: string
endpointLabel: string
savedProfileLabel: string
}
type SavedProfileSummary = {
providerLabel: string
modelLabel: string
endpointLabel: string
credentialLabel?: string
}
type TextEntryDialogProps = {
title: string
subtitle?: string
resetStateKey?: string
description: React.ReactNode
initialValue: string
placeholder?: string
mask?: string
allowEmpty?: boolean
validate?: (value: string) => string | null
onSubmit: (value: string) => void
onCancel: () => void
}
type ProviderWizardDefaults = {
openAIModel: string
openAIBaseUrl: string
geminiModel: string
mistralModel: string
mistralBaseUrl: string
}
type SecretSourceEnv = NodeJS.ProcessEnv & Partial<ProfileEnv>
function isEnvTruthy(value: string | undefined): boolean {
if (!value) return false
const normalized = value.trim().toLowerCase()
return normalized !== '' && normalized !== '0' && normalized !== 'false' && normalized !== 'no'
}
function getSafeDisplayValue(
value: string | undefined,
processEnv: SecretSourceEnv,
profileEnv?: ProfileEnv,
fallback = '(not set)',
): string {
return (
redactSecretValueForDisplay(value, processEnv, profileEnv) ?? fallback
)
}
function getConfiguredOpenAICompatibleProviderLabel(
baseUrl: string,
options?: {
processEnv?: SecretSourceEnv
model?: string
},
): string {
const routeId = resolveRouteIdFromBaseUrl(baseUrl)
if (routeId) {
return getRouteLabel(routeId) ?? 'OpenAI-compatible'
}
const request = resolveProviderRequest({
model: options?.model,
baseUrl,
})
if (request.transport === 'codex_responses') {
return 'Codex'
}
if (isLocalProviderUrl(request.baseUrl)) {
return getLocalOpenAICompatibleProviderLabel(request.baseUrl)
}
return 'OpenAI-compatible'
}
export function getProviderWizardDefaults(
processEnv: NodeJS.ProcessEnv = process.env,
): ProviderWizardDefaults {
const secretSource = processEnv as SecretSourceEnv
const safeOpenAIModel =
sanitizeProviderConfigValue(processEnv.OPENAI_MODEL, secretSource) ||
'gpt-4o'
const safeOpenAIBaseUrl =
sanitizeProviderConfigValue(processEnv.OPENAI_BASE_URL, secretSource) ||
DEFAULT_OPENAI_BASE_URL
const safeGeminiModel =
sanitizeProviderConfigValue(processEnv.GEMINI_MODEL, secretSource) ||
DEFAULT_GEMINI_MODEL
const safeMistralModel =
sanitizeProviderConfigValue(processEnv.MISTRAL_MODEL, secretSource) ||
DEFAULT_MISTRAL_MODEL
const safeMistralBaseUrl =
sanitizeProviderConfigValue(processEnv.MISTRAL_BASE_URL, secretSource) ||
DEFAULT_MISTRAL_BASE_URL
return {
openAIModel: safeOpenAIModel,
openAIBaseUrl: safeOpenAIBaseUrl,
geminiModel: safeGeminiModel,
mistralModel: safeMistralModel,
mistralBaseUrl: safeMistralBaseUrl,
}
}
export function buildCurrentProviderSummary(options?: {
processEnv?: NodeJS.ProcessEnv
persisted?: ProfileFile | null
}): CurrentProviderSummary {
const processEnv = options?.processEnv ?? process.env
const secretSource = processEnv as SecretSourceEnv
const persisted = options?.persisted ?? loadProfileFile()
const savedProfileLabel = persisted?.profile ?? 'none'
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_GEMINI)) {
const geminiMetadata = getProviderPresetUiMetadata('gemini', processEnv)
return {
providerLabel: geminiMetadata.label,
modelLabel: getSafeDisplayValue(
processEnv.GEMINI_MODEL ?? DEFAULT_GEMINI_MODEL,
secretSource,
),
endpointLabel: getSafeDisplayValue(
processEnv.GEMINI_BASE_URL ?? DEFAULT_GEMINI_BASE_URL,
secretSource,
),
savedProfileLabel,
}
}
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_MISTRAL)) {
const mistralMetadata = getProviderPresetUiMetadata('mistral', processEnv)
return {
providerLabel: mistralMetadata.label,
modelLabel: getSafeDisplayValue(
processEnv.MISTRAL_MODEL ?? DEFAULT_MISTRAL_MODEL,
processEnv
),
endpointLabel: getSafeDisplayValue(
processEnv.MISTRAL_BASE_URL ?? DEFAULT_MISTRAL_BASE_URL,
processEnv
),
savedProfileLabel,
}
}
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_GITHUB)) {
return {
providerLabel: 'GitHub Models',
modelLabel: getSafeDisplayValue(
processEnv.OPENAI_MODEL ?? 'gpt-4o',
secretSource,
),
endpointLabel: getSafeDisplayValue(
processEnv.OPENAI_BASE_URL ??
processEnv.OPENAI_API_BASE ??
'https://models.github.ai/inference',
secretSource,
),
savedProfileLabel,
}
}
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_OPENAI)) {
const request = resolveProviderRequest({
model: processEnv.OPENAI_MODEL,
baseUrl: processEnv.OPENAI_BASE_URL,
})
return {
providerLabel: getConfiguredOpenAICompatibleProviderLabel(
request.baseUrl,
{
model: processEnv.OPENAI_MODEL,
processEnv: secretSource,
},
),
modelLabel: getSafeDisplayValue(request.requestedModel, secretSource),
endpointLabel: getSafeDisplayValue(request.baseUrl, secretSource),
savedProfileLabel,
}
}
return {
providerLabel: 'Anthropic',
modelLabel: getSafeDisplayValue(
processEnv.ANTHROPIC_MODEL ??
processEnv.CLAUDE_MODEL ??
'claude-sonnet-4-6',
secretSource,
),
endpointLabel: getSafeDisplayValue(
processEnv.ANTHROPIC_BASE_URL ?? 'https://api.anthropic.com',
secretSource,
),
savedProfileLabel,
}
}
function buildSavedProfileSummary(
profile: ProviderProfile,
env: ProfileEnv,
): SavedProfileSummary {
switch (profile) {
case 'gemini':
{
const geminiMetadata = getProviderPresetUiMetadata('gemini')
return {
providerLabel: geminiMetadata.label,
modelLabel: getSafeDisplayValue(
env.GEMINI_MODEL ?? DEFAULT_GEMINI_MODEL,
process.env,
env,
),
endpointLabel: getSafeDisplayValue(
env.GEMINI_BASE_URL ?? DEFAULT_GEMINI_BASE_URL,
process.env,
env,
),
credentialLabel:
env.GEMINI_AUTH_MODE === 'access-token'
? 'access token (stored securely)'
: env.GEMINI_AUTH_MODE === 'adc'
? 'local ADC'
: maskSecretForDisplay(env.GEMINI_API_KEY) !== undefined
? 'configured'
: undefined,
}
}
case 'mistral':
{
const mistralMetadata = getProviderPresetUiMetadata('mistral')
return {
providerLabel: mistralMetadata.label,
modelLabel: getSafeDisplayValue(
env.MISTRAL_MODEL ?? DEFAULT_MISTRAL_MODEL,
process.env,
env,
),
endpointLabel: getSafeDisplayValue(
env.MISTRAL_BASE_URL ?? DEFAULT_MISTRAL_BASE_URL,
process.env,
env,
),
credentialLabel:
maskSecretForDisplay(env.MISTRAL_API_KEY) !== undefined
? 'configured'
: undefined,
}
}
case 'codex':
return {
providerLabel: 'Codex',
modelLabel: getSafeDisplayValue(
env.OPENAI_MODEL ?? 'codexplan',
process.env,
env,
),
endpointLabel: getSafeDisplayValue(
env.OPENAI_BASE_URL ?? DEFAULT_CODEX_BASE_URL,
process.env,
env,
),
credentialLabel:
maskSecretForDisplay(env.CODEX_API_KEY) !== undefined
? 'configured'
: undefined,
}
case 'ollama':
return {
providerLabel: 'Ollama',
modelLabel: getSafeDisplayValue(
env.OPENAI_MODEL,
process.env,
env,
),
endpointLabel: getSafeDisplayValue(
env.OPENAI_BASE_URL,
process.env,
env,
),
}
case 'openai':
default: {
const baseUrl = env.OPENAI_BASE_URL ?? DEFAULT_OPENAI_BASE_URL
return {
providerLabel: getConfiguredOpenAICompatibleProviderLabel(baseUrl, {
model: env.OPENAI_MODEL,
}),
modelLabel: getSafeDisplayValue(
env.OPENAI_MODEL ?? 'gpt-4o',
process.env,
env,
),
endpointLabel: getSafeDisplayValue(
baseUrl,
process.env,
env,
),
credentialLabel:
maskSecretForDisplay(env.OPENAI_API_KEY) !== undefined
? 'configured'
: undefined,
}
}
}
}
export function buildProfileSaveMessage(
profile: ProviderProfile,
env: ProfileEnv,
filePath: string,
options?: {
activatedInSession?: boolean
activationWarning?: string | null
},
): string {
const summary = buildSavedProfileSummary(profile, env)
const lines = [
`Saved ${summary.providerLabel} profile.`,
`Model: ${summary.modelLabel}`,
`Endpoint: ${summary.endpointLabel}`,
]
if (summary.credentialLabel) {
lines.push(`Credentials: ${summary.credentialLabel}`)
}
lines.push(`Profile: ${filePath}`)
if (options?.activatedInSession) {
lines.push('OpenClaude switched to it for this session.')
} else if (options?.activationWarning) {
lines.push(
`Saved for next startup. Warning: could not activate it in this session (${options.activationWarning}).`,
)
} else {
lines.push('Restart OpenClaude to use it.')
}
return lines.join('\n')
}
function buildUsageText(): string {
const summary = buildCurrentProviderSummary()
const availableProviders = isBareMode()
? 'Choose Auto, Ollama, OpenAI-compatible, Gemini, or Codex, then save a provider profile.'
: 'Choose Auto, Ollama, OpenAI-compatible, Gemini, Codex, or Codex OAuth, then save a provider profile.'
return [
'Usage: /provider',
'',
'Guided setup for saved provider profiles.',
'',
`Current provider: ${summary.providerLabel}`,
`Current model: ${summary.modelLabel}`,
`Current endpoint: ${summary.endpointLabel}`,
`Saved profile: ${summary.savedProfileLabel}`,
'',
availableProviders,
].join('\n')
}
function finishProfileSave(
onDone: LocalJSXCommandOnDone,
profile: ProviderProfile,
env: ProfileEnv,
): void {
void saveProfileAndNotify(onDone, profile, env)
}
export function buildCodexOAuthProfileEnv(
tokens: Pick<CodexOAuthTokens, 'accessToken' | 'idToken' | 'accountId'>,
): ProfileEnv | null {
return buildSharedCodexOAuthProfileEnv(tokens)
}
export async function applySavedProfileToCurrentSession(options: {
profileFile: ProfileFile
processEnv?: NodeJS.ProcessEnv
}): Promise<string | null> {
return applySharedProfileToCurrentSession(options)
}
async function saveProfileAndNotify(
onDone: LocalJSXCommandOnDone,
profile: ProviderProfile,
env: ProfileEnv,
): Promise<void> {
try {
const profileFile = createProfileFile(profile, env)
const filePath = saveProfileFile(profileFile)
const shouldActivateInSession = profile === 'codex'
const activationWarning = shouldActivateInSession
? await applySharedProfileToCurrentSession({ profileFile })
: null
onDone(
buildProfileSaveMessage(profile, env, filePath, {
activatedInSession:
shouldActivateInSession && activationWarning === null,
activationWarning,
}),
{
display: 'system',
},
)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
onDone(`Failed to save provider profile: ${message}`, {
display: 'system',
})
}
}
export function TextEntryDialog({
title,
subtitle,
resetStateKey,
description,
initialValue,
placeholder,
mask,
allowEmpty = false,
validate,
onSubmit,
onCancel,
}: TextEntryDialogProps): React.ReactNode {
const { columns } = useTerminalSize()
const [value, setValue] = React.useState(initialValue)
const [cursorOffset, setCursorOffset] = React.useState(initialValue.length)
const [error, setError] = React.useState<string | null>(null)
React.useLayoutEffect(() => {
setValue(initialValue)
setCursorOffset(initialValue.length)
setError(null)
}, [initialValue, resetStateKey])
const inputColumns = Math.max(30, columns - 6)
const handleSubmit = React.useCallback(
(nextValue: string) => {
if (!allowEmpty && nextValue.trim().length === 0) {
setError('A value is required for this step.')
return
}
const validationError = validate?.(nextValue)
if (validationError) {
setError(validationError)
return
}
setError(null)
onSubmit(nextValue)
},
[allowEmpty, onSubmit, validate],
)
return (
<Dialog title={title} subtitle={subtitle} onCancel={onCancel}>
<Box flexDirection="column" gap={1}>
<Text>{description}</Text>
<TextInput
value={value}
onChange={setValue}
onSubmit={handleSubmit}
placeholder={placeholder}
mask={mask}
columns={inputColumns}
cursorOffset={cursorOffset}
onChangeCursorOffset={setCursorOffset}
focus
showCursor
/>
{error ? <Text color="error">{error}</Text> : null}
</Box>
</Dialog>
)
}
function ProviderChooser({
onChoose,
onCancel,
}: {
onChoose: (value: ProviderChoice) => void
onCancel: () => void
}): React.ReactNode {
const summary = buildCurrentProviderSummary()
const canUseCodexOAuth = !isBareMode()
const ollamaMetadata = getProviderPresetUiMetadata('ollama')
const openAIMetadata = getProviderPresetUiMetadata('openai')
const geminiMetadata = getProviderPresetUiMetadata('gemini')
const mistralMetadata = getProviderPresetUiMetadata('mistral')
const helperText = canUseCodexOAuth
? 'Save a provider profile without editing environment variables first. Codex profiles backed by env, auth.json, or OpenClaude secure storage can switch this session immediately when validation succeeds.'
: 'Save a provider profile without editing environment variables first. Codex profiles backed by env or auth.json can switch this session immediately.'
const options: OptionWithDescription<ProviderChoice>[] = [
{
label: 'Auto',
value: 'auto',
description:
'Prefer local Ollama when available, otherwise guide you into OpenAI-compatible setup',
},
{
label: ollamaMetadata.label,
value: 'ollama',
description: ollamaMetadata.description,
},
{
label: openAIMetadata.name,
value: 'openai',
description: 'OpenAI and similar OpenAI-compatible APIs',
},
{
label: geminiMetadata.label,
value: 'gemini',
description: 'Use Gemini with API key, access token, or local ADC',
},
{
label: mistralMetadata.label,
value: 'mistral',
description: mistralMetadata.description,
},
{
label: 'Codex',
value: 'codex',
description: 'Use existing ChatGPT Codex CLI auth or env credentials',
},
...(canUseCodexOAuth
? [
{
label: 'Codex OAuth',
value: 'codex-oauth' as const,
description:
'Sign in with ChatGPT in your browser and store Codex tokens securely',
},
]
: []),
]
if (summary.savedProfileLabel !== 'none') {
options.push({
label: 'Clear saved profile',
value: 'clear',
description: 'Remove .openclaude-profile.json and return to normal startup',
})
}
return (
<Dialog
title="Set up a provider profile"
subtitle={`Current provider: ${summary.providerLabel}`}
onCancel={onCancel}
>
<Box flexDirection="column" gap={1}>
<Text>{helperText}</Text>
<Box flexDirection="column">
<Text dimColor>Current model: {summary.modelLabel}</Text>
<Text dimColor>Current endpoint: {summary.endpointLabel}</Text>
<Text dimColor>Saved profile: {summary.savedProfileLabel}</Text>
</Box>
<Select
options={options}
inlineDescriptions
visibleOptionCount={options.length}
onChange={onChoose}
onCancel={onCancel}
/>
</Box>
</Dialog>
)
}
function AutoGoalChooser({
onChoose,
onBack,
}: {
onChoose: (goal: RecommendationGoal) => void
onBack: () => void
}): React.ReactNode {
const options: OptionWithDescription<RecommendationGoal>[] = [
{
label: 'Balanced',
value: 'balanced',
description: 'Strong everyday default for most users',
},
{
label: 'Coding',
value: 'coding',
description: 'Prefer coding-oriented local models or GPT-4o defaults',
},
{
label: 'Latency',
value: 'latency',
description: 'Prefer faster local models or gpt-4o-mini defaults',
},
]
return (
<Dialog title="Auto setup goal" onCancel={onBack}>
<Box flexDirection="column" gap={1}>
<Text>Pick the goal Auto setup should optimize for.</Text>
<Select
options={options}
defaultValue="balanced"
defaultFocusValue="balanced"
inlineDescriptions
visibleOptionCount={options.length}
onChange={onChoose}
onCancel={onBack}
/>
</Box>
</Dialog>
)
}
function AutoRecommendationStep({
goal,
onBack,
onSave,
onNeedOpenAI,
onCancel,
}: {
goal: RecommendationGoal
onBack: () => void
onSave: (profile: ProviderProfile, env: ProfileEnv) => void
onNeedOpenAI: (defaultModel: string) => void
onCancel: () => void
}): React.ReactNode {
const [status, setStatus] = React.useState<
| {
state: 'loading'
}
| {
state: 'ollama'
model: string
summary: string
}
| {
state: 'openai'
defaultModel: string
reason: string
}
| {
state: 'error'
message: string
}
>({ state: 'loading' })
React.useEffect(() => {
let cancelled = false
void (async () => {
const defaultModel = getGoalDefaultOpenAIModel(goal)
try {
const readiness = await probeRouteReadiness('ollama')
if (!readiness) {
if (!cancelled) {
setStatus({
state: 'error',
message: 'Ollama readiness probe is not configured for this route.',
})
}
return
}
if (readiness.state !== 'ready') {
if (!cancelled) {
setStatus({
state: 'openai',
defaultModel,
reason: describeOllamaReadinessIssue(readiness),
})
}
return
}
const recommended = recommendOllamaModel(readiness.models, goal)
if (!recommended) {
if (!cancelled) {
setStatus({
state: 'openai',
defaultModel,
reason:
'Ollama responded to a generation probe, but no recommended chat model matched this goal.',
})
}
return
}
if (!cancelled) {
setStatus({
state: 'ollama',
model: recommended.name,
summary: recommended.summary,
})
}
} catch (error) {
if (!cancelled) {
setStatus({
state: 'error',
message: error instanceof Error ? error.message : String(error),
})
}
}
})()
return () => {
cancelled = true
}
}, [goal])
if (status.state === 'loading') {
return <LoadingState message="Checking local providers…" />
}
if (status.state === 'error') {
return (
<Dialog title="Auto setup failed" onCancel={onCancel} color="warning">
<Box flexDirection="column" gap={1}>
<Text>{status.message}</Text>
<Select
options={[
{ label: 'Back', value: 'back' },
{ label: 'Cancel', value: 'cancel' },
]}
onChange={(value: string) =>
value === 'back' ? onBack() : onCancel()
}
onCancel={onCancel}
/>
</Box>
</Dialog>
)
}
if (status.state === 'openai') {
return (
<Dialog title="Auto setup fallback" onCancel={onCancel}>
<Box flexDirection="column" gap={1}>
<Text>
Auto setup can continue into OpenAI-compatible setup with a default model of{' '}
{status.defaultModel}.
</Text>
<Text dimColor>{status.reason}</Text>
<Select
options={[
{ label: 'Continue to OpenAI-compatible setup', value: 'continue' },
{ label: 'Back', value: 'back' },
{ label: 'Cancel', value: 'cancel' },
]}
onChange={(value: string) => {
if (value === 'continue') {
onNeedOpenAI(status.defaultModel)
} else if (value === 'back') {
onBack()
} else {
onCancel()
}
}}
onCancel={onCancel}
/>
</Box>
</Dialog>
)
}
return (
<Dialog title="Save recommended profile?" onCancel={onBack}>
<Box flexDirection="column" gap={1}>
<Text>
Auto setup recommends a local Ollama profile for {goal} based on the
models currently available on this machine.
</Text>
<Text dimColor>
Recommended model: {status.model}
{status.summary ? ` · ${status.summary}` : ''}
</Text>
<Select
options={[
{ label: 'Save recommended Ollama profile', value: 'save' },
{ label: 'Back', value: 'back' },
{ label: 'Cancel', value: 'cancel' },
]}
onChange={(value: string) => {
if (value === 'save') {
onSave(
'ollama',
buildOllamaProfileEnv(status.model, {
getOllamaChatBaseUrl,
}),
)
} else if (value === 'back') {
onBack()
} else {
onCancel()
}
}}
onCancel={onBack}
/>
</Box>
</Dialog>
)
}
function OllamaModelStep({
onSave,
onBack,
onCancel,
}: {
onSave: (profile: ProviderProfile, env: ProfileEnv) => void
onBack: () => void
onCancel: () => void
}): React.ReactNode {
const [status, setStatus] = React.useState<
| { state: 'loading' }
| {
state: 'ready'
options: OptionWithDescription<string>[]
defaultValue?: string
}