-
Notifications
You must be signed in to change notification settings - Fork 827
Expand file tree
/
Copy pathonboarding-ipc.ts
More file actions
1410 lines (1317 loc) · 52.8 KB
/
Copy pathonboarding-ipc.ts
File metadata and controls
1410 lines (1317 loc) · 52.8 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 { readFile } from 'node:fs/promises';
import { type ValidateResult, pingProvider } from '@open-codesign/providers';
import {
BUILTIN_PROVIDERS,
type ClaudeCodeDetectionMeta,
CodesignError,
type CodexDetectionMeta,
type Config,
ERROR_CODES,
type ExternalConfigsDetection,
type GeminiDetectionMeta,
type OnboardingState,
type OpencodeDetectionMeta,
type ProviderEntry,
type ReasoningLevel,
ReasoningLevelSchema,
StoredDesignSystem,
type StoredDesignSystem as StoredDesignSystemValue,
type SupportedOnboardingProvider,
type WireApi,
WireApiSchema,
hydrateConfig,
isSupportedOnboardingProvider,
modelsEndpointUrl,
} from '@open-codesign/shared';
import { buildAuthHeadersForWire } from './auth-headers';
import { defaultConfigDir, readConfig, writeConfig } from './config';
import { dialog, ipcMain, shell } from './electron-runtime';
import { type ClaudeCodeImport, readClaudeCodeSettings } from './imports/claude-code-config';
import {
ALLOWED_IMPORT_ENV_KEYS,
type CodexImport,
codexAuthPath,
readCodexConfig,
} from './imports/codex-config';
import { type GeminiImport, readGeminiCliConfig } from './imports/gemini-cli-config';
import { type OpencodeImport, readOpencodeConfig } from './imports/opencode-config';
import { buildSecretRef, decryptSecret, migrateSecrets } from './keychain';
import { defaultLogsDir, getLogger } from './logger';
import {
type ProviderRow,
assertProviderHasStoredSecret,
computeDeleteProviderResult,
getAddProviderDefaults,
isKeylessProviderAllowed,
toProviderRows,
} from './provider-settings';
import {
type AppPaths,
type StorageKind,
buildAppPathsForLocations,
getDefaultUserDataDir,
patchForStorageKind,
readPersistedStorageLocations,
writeStorageLocations,
} from './storage-settings';
import { createWarnOnce } from './warnOnce';
const logger = getLogger('settings-ipc');
const warnLegacy = createWarnOnce(logger);
interface SaveKeyInput {
provider: string;
apiKey: string;
modelPrimary: string;
baseUrl?: string;
}
interface ValidateKeyInput {
provider: SupportedOnboardingProvider;
apiKey: string;
baseUrl?: string;
}
export type { ProviderRow } from './provider-settings';
let cachedConfig: Config | null = null;
let configLoaded = false;
export async function loadConfigOnBoot(): Promise<void> {
const parsed = await readConfig();
configLoaded = true;
if (parsed === null) {
cachedConfig = null;
return;
}
// Boot-time migration: rewrite any legacy safeStorage-encrypted secrets
// as plaintext, and fill in missing display masks. This is the ONLY path
// that can trigger a keychain prompt (and only on an upgrade from an
// older build that still used safeStorage). After one successful run the
// config is pure plaintext forever.
const migrated = migrateSecrets(parsed);
cachedConfig = migrated.config;
if (migrated.changed) {
try {
await writeConfig(migrated.config);
} catch (err) {
logger.warn('boot.migrate_secrets.writeConfig_failed', {
err: err instanceof Error ? err.message : String(err),
});
}
}
}
/**
* Overwrite the cached config reference. For use by sibling IPC modules (e.g.
* `codex-oauth-ipc`) that mutate `config.providers` via their own write path
* and need `getCachedConfig` / `toState` to reflect the change immediately.
* Callers are responsible for having already persisted `next` to disk.
*/
export function setCachedConfig(next: Config): void {
cachedConfig = next;
configLoaded = true;
}
export function getCachedConfig(): Config | null {
if (!configLoaded) {
throw new CodesignError(
'getCachedConfig called before loadConfigOnBoot',
ERROR_CODES.CONFIG_NOT_LOADED,
);
}
return cachedConfig;
}
export function getApiKeyForProvider(provider: string): string {
const cfg = getCachedConfig();
if (cfg === null) {
throw new CodesignError(
'No configuration found. Complete onboarding first.',
ERROR_CODES.CONFIG_MISSING,
);
}
const ref = cfg.secrets[provider as keyof typeof cfg.secrets];
if (ref !== undefined) return decryptSecret(ref.ciphertext);
// Fallback: if the provider entry declares an envKey (e.g. imported
// Claude Code providers always declare ANTHROPIC_AUTH_TOKEN), resolve
// the key from the process environment. This rescues two cases that
// would otherwise be dead ends:
// 1. User exported ANTHROPIC_API_KEY in their shell and launched
// from a terminal — the env is inherited but our onboarding never
// called `encryptSecret`, so cfg.secrets[provider] is empty.
// 2. User deleted the persisted key from Settings but the env var is
// still present. Treat it as a valid credential rather than
// throwing a misleading "key missing" error.
const entry = cfg.providers[provider];
if (entry?.envKey !== undefined) {
// Defense in depth against legacy configs: Codex's config.toml env_key
// field is now allowlisted at import time, but older configs may have
// stored arbitrary env-var names (pre-allowlist). Re-check here so a
// stale `envKey: "AWS_SECRET_ACCESS_KEY"` can't still exfiltrate on
// every LLM call.
if (!ALLOWED_IMPORT_ENV_KEYS.has(entry.envKey)) {
logger.warn('get_api_key.envKey_blocked', {
provider,
envKey: entry.envKey,
});
} else {
const fromEnv = process.env[entry.envKey]?.trim();
if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;
}
}
throw new CodesignError(
`No API key stored for provider "${provider}". Re-run onboarding to add one.`,
ERROR_CODES.PROVIDER_KEY_MISSING,
);
}
export function getBaseUrlForProvider(provider: string): string | undefined {
const cfg = getCachedConfig();
if (cfg === null) return undefined;
return cfg.providers[provider]?.baseUrl;
}
function toState(cfg: Config | null): OnboardingState {
if (cfg === null) {
return {
hasKey: false,
provider: null,
modelPrimary: null,
baseUrl: null,
designSystem: null,
};
}
const active = cfg.activeProvider;
const ref = cfg.secrets[active];
if (ref === undefined && !isKeylessProviderAllowed(active, cfg.providers[active])) {
return {
hasKey: false,
provider: active,
modelPrimary: null,
baseUrl: null,
designSystem: cfg.designSystem ?? null,
};
}
return {
hasKey: true,
provider: active,
modelPrimary: cfg.activeModel,
baseUrl: cfg.providers[active]?.baseUrl ?? null,
designSystem: cfg.designSystem ?? null,
};
}
export function getOnboardingState(): OnboardingState {
return toState(getCachedConfig());
}
export async function setDesignSystem(
designSystem: StoredDesignSystemValue | null,
): Promise<OnboardingState> {
const cfg = getCachedConfig();
if (cfg === null) {
throw new CodesignError(
'Cannot save a design system before onboarding has completed.',
ERROR_CODES.CONFIG_MISSING,
);
}
const next: Config = hydrateConfig({
version: 3,
activeProvider: cfg.activeProvider,
activeModel: cfg.activeModel,
secrets: cfg.secrets,
providers: cfg.providers,
...(designSystem !== null ? { designSystem: StoredDesignSystem.parse(designSystem) } : {}),
});
await writeConfig(next);
cachedConfig = next;
configLoaded = true;
return toState(cachedConfig);
}
function parseSaveKey(raw: unknown): SaveKeyInput {
if (typeof raw !== 'object' || raw === null) {
throw new CodesignError('save-key expects an object payload', ERROR_CODES.IPC_BAD_INPUT);
}
const r = raw as Record<string, unknown>;
const provider = r['provider'];
const apiKey = r['apiKey'];
const modelPrimary = r['modelPrimary'];
const baseUrl = r['baseUrl'];
if (typeof provider !== 'string' || provider.trim().length === 0) {
throw new CodesignError(
`Provider "${String(provider)}" is invalid.`,
ERROR_CODES.IPC_BAD_INPUT,
);
}
const providerId = provider.trim();
const isKeylessBuiltin =
isSupportedOnboardingProvider(providerId) &&
BUILTIN_PROVIDERS[providerId].requiresApiKey === false;
if (typeof apiKey !== 'string' || (apiKey.trim().length === 0 && !isKeylessBuiltin)) {
throw new CodesignError('apiKey must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof modelPrimary !== 'string' || modelPrimary.trim().length === 0) {
throw new CodesignError('modelPrimary must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
const out: SaveKeyInput = { provider: providerId, apiKey: apiKey.trim(), modelPrimary };
if (typeof baseUrl === 'string' && baseUrl.trim().length > 0) {
try {
new URL(baseUrl);
} catch {
throw new CodesignError(`baseUrl "${baseUrl}" is not a valid URL`, ERROR_CODES.IPC_BAD_INPUT);
}
out.baseUrl = baseUrl.trim();
}
return out;
}
function parseValidateKey(raw: unknown): ValidateKeyInput {
if (typeof raw !== 'object' || raw === null) {
throw new CodesignError('validate-key expects an object payload', ERROR_CODES.IPC_BAD_INPUT);
}
const r = raw as Record<string, unknown>;
const provider = r['provider'];
const apiKey = r['apiKey'];
const baseUrl = r['baseUrl'];
if (typeof provider !== 'string') {
throw new CodesignError('provider must be a string', ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof apiKey !== 'string' || apiKey.trim().length === 0) {
throw new CodesignError('apiKey must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
if (!isSupportedOnboardingProvider(provider)) {
throw new CodesignError(
`Provider "${provider}" is not supported in v0.1. Only anthropic, openai, openrouter, minimax.`,
ERROR_CODES.PROVIDER_NOT_SUPPORTED,
);
}
const out: ValidateKeyInput = { provider, apiKey };
if (typeof baseUrl === 'string' && baseUrl.length > 0) out.baseUrl = baseUrl;
return out;
}
// ── Settings handler implementations (shared by v1 and legacy channels) ───────
function runListProviders(): ProviderRow[] {
// Secret migration happens once at boot (see `loadConfigOnBoot` →
// `migrateSecrets`). By the time Settings is opened, every row has a
// persisted plaintext + mask and `toProviderRows` never touches any
// decrypt path for render. `decryptSecret` is only passed in as a
// late-stage fallback for exotic rows that somehow slipped through.
return toProviderRows(getCachedConfig(), decryptSecret);
}
interface SetProviderAndModelsInput extends SaveKeyInput {
setAsActive: boolean;
}
function parseSetProviderAndModels(raw: unknown): SetProviderAndModelsInput {
if (typeof raw !== 'object' || raw === null) {
throw new CodesignError(
'set-provider-and-models expects an object payload',
ERROR_CODES.IPC_BAD_INPUT,
);
}
const r = raw as Record<string, unknown>;
const sv = r['schemaVersion'];
if (sv !== undefined && sv !== 1) {
throw new CodesignError(
`Unsupported schemaVersion ${String(sv)} (expected 1)`,
ERROR_CODES.IPC_BAD_INPUT,
);
}
const setAsActive = r['setAsActive'];
if (typeof setAsActive !== 'boolean') {
throw new CodesignError('setAsActive must be a boolean', ERROR_CODES.IPC_BAD_INPUT);
}
return { ...parseSaveKey(raw), setAsActive };
}
/**
* Canonical "add or update a provider" mutation. Atomic: writes secret +
* baseUrl + (optionally) flips active provider in a single writeConfig.
*
* Returns the full OnboardingState so renderer can hydrate Zustand without a
* follow-up read — that store-sync gap is what made TopBar drift out of date
* after Settings mutations.
*/
async function runSetProviderAndModels(input: SetProviderAndModelsInput): Promise<OnboardingState> {
const nextProviders: Record<string, ProviderEntry> = { ...(cachedConfig?.providers ?? {}) };
const existing = nextProviders[input.provider];
const builtin = BUILTIN_PROVIDERS[input.provider as SupportedOnboardingProvider];
const seed: ProviderEntry = existing ??
builtin ?? {
id: input.provider,
name: input.provider,
builtin: false,
wire: 'openai-chat',
baseUrl: input.baseUrl ?? 'https://api.openai.com/v1',
defaultModel: input.modelPrimary,
};
nextProviders[input.provider] = {
...seed,
baseUrl: input.baseUrl ?? seed.baseUrl,
defaultModel: input.modelPrimary || seed.defaultModel,
};
const nextSecrets = { ...(cachedConfig?.secrets ?? {}) };
if (input.apiKey.length > 0) {
nextSecrets[input.provider] = buildSecretRef(input.apiKey);
} else {
delete nextSecrets[input.provider];
}
const activate = input.setAsActive || cachedConfig === null;
const nextActiveProvider = activate
? input.provider
: (cachedConfig?.activeProvider ?? input.provider);
const nextActiveModel = activate
? input.modelPrimary
: (cachedConfig?.activeModel ?? input.modelPrimary);
const next: Config = hydrateConfig({
version: 3,
activeProvider: nextActiveProvider,
activeModel: nextActiveModel,
secrets: nextSecrets,
providers: nextProviders,
...(cachedConfig?.designSystem !== undefined
? { designSystem: cachedConfig.designSystem }
: {}),
});
await writeConfig(next);
cachedConfig = next;
configLoaded = true;
return toState(cachedConfig);
}
async function runAddProvider(raw: unknown): Promise<ProviderRow[]> {
const input = parseSaveKey(raw);
const defaults = getAddProviderDefaults(cachedConfig, input);
await runSetProviderAndModels({
...input,
setAsActive: defaults.activeProvider === input.provider,
modelPrimary: defaults.modelPrimary,
});
return toProviderRows(cachedConfig, decryptSecret);
}
async function runDeleteProvider(raw: unknown): Promise<ProviderRow[]> {
if (typeof raw !== 'string') {
throw new CodesignError('delete-provider expects a provider string', ERROR_CODES.IPC_BAD_INPUT);
}
const cfg = getCachedConfig();
if (cfg === null) return [];
const nextSecrets = { ...cfg.secrets };
delete nextSecrets[raw];
const nextProviders: Record<string, ProviderEntry> = { ...cfg.providers };
// Remove the provider entry unconditionally. Earlier revisions kept
// builtin entries around (only clearing the secret) so a user could
// "re-add" without losing wire/baseUrl defaults — but that left the row
// visibly undeletable while the UI still toasted "removed". Users who
// want the builtin back can re-add from the "+ Add provider" menu,
// which seeds a fresh copy from BUILTIN_PROVIDERS with no data loss.
delete nextProviders[raw];
const { nextActive, modelPrimary } = computeDeleteProviderResult(cfg, raw);
if (nextActive === null) {
// All providers gone. Reset BOTH activeProvider and activeModel to ''
// so the config doesn't carry a dangling reference to the just-deleted
// provider id (which was the old bug: the app would boot next time
// with activeProvider='openrouter' pointing at a missing entry and
// activeModel='' failing zod's min(1)).
const emptyNext: Config = hydrateConfig({
version: 3,
activeProvider: '',
activeModel: '',
secrets: {},
providers: nextProviders,
...(cfg.designSystem !== undefined ? { designSystem: cfg.designSystem } : {}),
});
await writeConfig(emptyNext);
cachedConfig = emptyNext;
return toProviderRows(cachedConfig, decryptSecret);
}
const next: Config = hydrateConfig({
version: 3,
activeProvider: nextActive,
activeModel: modelPrimary,
secrets: nextSecrets,
providers: nextProviders,
...(cfg.designSystem !== undefined ? { designSystem: cfg.designSystem } : {}),
});
await writeConfig(next);
cachedConfig = next;
return toProviderRows(cachedConfig, decryptSecret);
}
async function runSetActiveProvider(raw: unknown): Promise<OnboardingState> {
if (typeof raw !== 'object' || raw === null) {
throw new CodesignError('set-active-provider expects an object', ERROR_CODES.IPC_BAD_INPUT);
}
const r = raw as Record<string, unknown>;
const provider = r['provider'];
const modelPrimary = r['modelPrimary'];
if (typeof provider !== 'string' || provider.length === 0) {
throw new CodesignError('provider must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof modelPrimary !== 'string' || modelPrimary.trim().length === 0) {
throw new CodesignError('modelPrimary must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
const cfg = getCachedConfig();
if (cfg === null) {
throw new CodesignError('No configuration found', ERROR_CODES.CONFIG_MISSING);
}
assertProviderHasStoredSecret(cfg, provider);
const next: Config = hydrateConfig({
version: 3,
activeProvider: provider,
activeModel: modelPrimary,
secrets: cfg.secrets,
providers: cfg.providers,
...(cfg.designSystem !== undefined ? { designSystem: cfg.designSystem } : {}),
});
await writeConfig(next);
cachedConfig = next;
return toState(cachedConfig);
}
function defaultDataDir(): string {
return getDefaultUserDataDir();
}
function getStoragePathDefaults() {
return {
configDir: defaultConfigDir(),
logsDir: defaultLogsDir(),
dataDir: defaultDataDir(),
};
}
async function runGetPaths(): Promise<AppPaths> {
const persisted = await readPersistedStorageLocations();
return buildAppPathsForLocations(persisted, getStoragePathDefaults());
}
function parseStorageKind(raw: unknown): StorageKind {
if (raw === 'config' || raw === 'logs' || raw === 'data') return raw;
throw new CodesignError(
'storage kind must be "config", "logs", or "data"',
ERROR_CODES.IPC_BAD_INPUT,
);
}
async function runChooseStorageFolder(raw: unknown): Promise<AppPaths> {
const kind = parseStorageKind(raw);
const result = await dialog.showOpenDialog({
properties: ['openDirectory', 'createDirectory'],
});
if (result.canceled || result.filePaths.length === 0) {
return runGetPaths();
}
const selected = result.filePaths[0];
if (selected === undefined || selected.trim().length === 0) {
return runGetPaths();
}
await writeStorageLocations(patchForStorageKind(kind, selected));
return runGetPaths();
}
async function runOpenFolder(raw: unknown): Promise<void> {
if (typeof raw !== 'string') {
throw new CodesignError('open-folder expects a path string', ERROR_CODES.IPC_BAD_INPUT);
}
const error = await shell.openPath(raw);
if (error) {
throw new CodesignError(`Could not open ${raw}: ${error}`, ERROR_CODES.OPEN_PATH_FAILED);
}
}
async function runResetOnboarding(): Promise<void> {
const cfg = getCachedConfig();
if (cfg === null) return;
// Clear secrets so onboarding flow triggers again on next load.
const next: Config = hydrateConfig({
version: 3,
activeProvider: cfg.activeProvider,
activeModel: cfg.activeModel,
secrets: {},
providers: cfg.providers,
...(cfg.designSystem !== undefined ? { designSystem: cfg.designSystem } : {}),
});
await writeConfig(next);
cachedConfig = next;
}
// ── v3 custom provider helpers ────────────────────────────────────────────
interface AddCustomProviderInput {
id: string;
name: string;
wire: WireApi;
baseUrl: string;
apiKey: string;
defaultModel: string;
httpHeaders?: Record<string, string>;
queryParams?: Record<string, string>;
envKey?: string;
setAsActive: boolean;
}
function parseAddProviderPayload(raw: unknown): AddCustomProviderInput {
if (typeof raw !== 'object' || raw === null) {
throw new CodesignError('config:v1:add-provider expects an object', ERROR_CODES.IPC_BAD_INPUT);
}
const r = raw as Record<string, unknown>;
const id = r['id'];
const name = r['name'];
const wire = r['wire'];
const baseUrl = r['baseUrl'];
const apiKey = r['apiKey'];
const defaultModel = r['defaultModel'];
if (typeof id !== 'string' || id.trim().length === 0) {
throw new CodesignError('id must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof name !== 'string' || name.trim().length === 0) {
throw new CodesignError('name must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
const parsedWire = WireApiSchema.safeParse(wire);
if (!parsedWire.success) {
throw new CodesignError(`Unsupported wire: ${String(wire)}`, ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof baseUrl !== 'string' || baseUrl.trim().length === 0) {
throw new CodesignError('baseUrl must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
try {
new URL(baseUrl);
} catch {
throw new CodesignError(`baseUrl "${baseUrl}" is not a valid URL`, ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof apiKey !== 'string') {
throw new CodesignError('apiKey must be a string', ERROR_CODES.IPC_BAD_INPUT);
}
if (typeof defaultModel !== 'string' || defaultModel.trim().length === 0) {
throw new CodesignError('defaultModel must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
const setAsActive = r['setAsActive'];
const out: AddCustomProviderInput = {
id: id.trim(),
name: name.trim(),
wire: parsedWire.data,
baseUrl: baseUrl.trim(),
apiKey: apiKey.trim(),
defaultModel: defaultModel.trim(),
setAsActive: setAsActive === true,
};
const headers = r['httpHeaders'];
if (headers !== undefined && headers !== null && typeof headers === 'object') {
const map: Record<string, string> = {};
for (const [k, v] of Object.entries(headers as Record<string, unknown>)) {
if (typeof v === 'string') map[k] = v;
}
if (Object.keys(map).length > 0) out.httpHeaders = map;
}
const qp = r['queryParams'];
if (qp !== undefined && qp !== null && typeof qp === 'object') {
const map: Record<string, string> = {};
for (const [k, v] of Object.entries(qp as Record<string, unknown>)) {
if (typeof v === 'string') map[k] = v;
}
if (Object.keys(map).length > 0) out.queryParams = map;
}
if (typeof r['envKey'] === 'string' && (r['envKey'] as string).length > 0) {
out.envKey = r['envKey'] as string;
}
return out;
}
async function runAddCustomProvider(input: AddCustomProviderInput): Promise<OnboardingState> {
const entry: ProviderEntry = {
id: input.id,
name: input.name,
builtin: false,
wire: input.wire,
baseUrl: input.baseUrl,
defaultModel: input.defaultModel,
...(input.httpHeaders !== undefined ? { httpHeaders: input.httpHeaders } : {}),
...(input.queryParams !== undefined ? { queryParams: input.queryParams } : {}),
...(input.envKey !== undefined ? { envKey: input.envKey } : {}),
};
const secretRef = buildSecretRef(input.apiKey);
const nextProviders = { ...(cachedConfig?.providers ?? {}), [entry.id]: entry };
const nextSecrets = { ...(cachedConfig?.secrets ?? {}), [entry.id]: secretRef };
const shouldActivate = input.setAsActive || cachedConfig === null;
const next = hydrateConfig({
version: 3,
activeProvider: shouldActivate ? entry.id : (cachedConfig?.activeProvider ?? entry.id),
activeModel: shouldActivate
? input.defaultModel
: (cachedConfig?.activeModel ?? input.defaultModel),
secrets: nextSecrets,
providers: nextProviders,
...(cachedConfig?.designSystem !== undefined
? { designSystem: cachedConfig.designSystem }
: {}),
});
await writeConfig(next);
cachedConfig = next;
configLoaded = true;
return toState(cachedConfig);
}
interface UpdateProviderInput {
id: string;
name?: string;
baseUrl?: string;
defaultModel?: string;
httpHeaders?: Record<string, string>;
queryParams?: Record<string, string>;
wire?: WireApi;
reasoningLevel?: ReasoningLevel | null;
/** When present AND non-empty, re-encrypt and replace the stored secret.
* Empty string means "clear stored secret" for providers that became
* keyless (e.g. switched to local Ollama). `undefined` means "leave alone". */
apiKey?: string;
}
function parseUpdateProviderPayload(raw: unknown): UpdateProviderInput {
if (typeof raw !== 'object' || raw === null) {
throw new CodesignError(
'config:v1:update-provider expects an object',
ERROR_CODES.IPC_BAD_INPUT,
);
}
const r = raw as Record<string, unknown>;
const id = r['id'];
if (typeof id !== 'string' || id.length === 0) {
throw new CodesignError('id must be a non-empty string', ERROR_CODES.IPC_BAD_INPUT);
}
const out: UpdateProviderInput = { id };
if (typeof r['name'] === 'string') out.name = r['name'] as string;
if (typeof r['baseUrl'] === 'string') out.baseUrl = r['baseUrl'] as string;
if (typeof r['defaultModel'] === 'string') out.defaultModel = r['defaultModel'] as string;
if (
r['httpHeaders'] !== undefined &&
typeof r['httpHeaders'] === 'object' &&
r['httpHeaders'] !== null
) {
const map: Record<string, string> = {};
for (const [k, v] of Object.entries(r['httpHeaders'] as Record<string, unknown>)) {
if (typeof v === 'string') map[k] = v;
}
out.httpHeaders = map;
}
if (
r['queryParams'] !== undefined &&
typeof r['queryParams'] === 'object' &&
r['queryParams'] !== null
) {
const map: Record<string, string> = {};
for (const [k, v] of Object.entries(r['queryParams'] as Record<string, unknown>)) {
if (typeof v === 'string') map[k] = v;
}
out.queryParams = map;
}
if (typeof r['wire'] === 'string') {
const parsedWire = WireApiSchema.safeParse(r['wire']);
if (parsedWire.success) out.wire = parsedWire.data;
}
if (r['reasoningLevel'] === null) {
// Explicit null clears the override so the core default kicks in.
out.reasoningLevel = null;
} else if (typeof r['reasoningLevel'] === 'string') {
const parsed = ReasoningLevelSchema.safeParse(r['reasoningLevel']);
if (parsed.success) out.reasoningLevel = parsed.data;
}
if (typeof r['apiKey'] === 'string') out.apiKey = r['apiKey'];
return out;
}
async function runUpdateProvider(input: UpdateProviderInput): Promise<OnboardingState> {
const cfg = getCachedConfig();
if (cfg === null) {
throw new CodesignError('No configuration found', ERROR_CODES.CONFIG_MISSING);
}
// Builtin providers may not have an entry on disk yet on a fresh install
// (the providers map is seeded lazily). Fall back to BUILTIN_PROVIDERS so
// "change my Ollama baseUrl" works before the user ever opened onboarding.
const existing =
cfg.providers[input.id] ??
(isSupportedOnboardingProvider(input.id) ? { ...BUILTIN_PROVIDERS[input.id] } : undefined);
if (existing === undefined) {
throw new CodesignError(`Provider "${input.id}" not found`, ERROR_CODES.IPC_BAD_INPUT);
}
const updated: ProviderEntry = {
...existing,
...(input.name !== undefined ? { name: input.name } : {}),
...(input.baseUrl !== undefined ? { baseUrl: input.baseUrl } : {}),
...(input.defaultModel !== undefined ? { defaultModel: input.defaultModel } : {}),
...(input.httpHeaders !== undefined ? { httpHeaders: input.httpHeaders } : {}),
...(input.queryParams !== undefined ? { queryParams: input.queryParams } : {}),
...(input.wire !== undefined ? { wire: input.wire } : {}),
};
// reasoningLevel has a tri-state semantic: undefined means "untouched",
// null means "explicitly clear the override so core picks the default",
// a string level means "set it". Handle separately from the spread above
// because the `...undefined ? {} : {...}` pattern can't express "delete".
if (input.reasoningLevel === null) {
updated.reasoningLevel = undefined;
} else if (input.reasoningLevel !== undefined) {
updated.reasoningLevel = input.reasoningLevel;
}
// Secret rotation: only touch secrets when the caller explicitly supplied
// an apiKey field. Empty string clears the secret (keyless providers);
// a non-empty value re-encrypts under the current safeStorage session key.
let nextSecrets = cfg.secrets;
if (input.apiKey !== undefined) {
const trimmed = input.apiKey.trim();
if (trimmed.length === 0) {
const { [input.id]: _removed, ...rest } = cfg.secrets;
nextSecrets = rest;
} else {
nextSecrets = { ...cfg.secrets, [input.id]: buildSecretRef(trimmed) };
}
}
const next = hydrateConfig({
version: 3,
activeProvider: cfg.activeProvider,
activeModel: cfg.activeModel,
secrets: nextSecrets,
providers: { ...cfg.providers, [input.id]: updated },
...(cfg.designSystem !== undefined ? { designSystem: cfg.designSystem } : {}),
});
await writeConfig(next);
cachedConfig = next;
return toState(cachedConfig);
}
// `ExternalConfigsDetection` and its four `*DetectionMeta` satellites now
// live in `packages/shared/src/detection.ts` so the main process and the
// preload facade can import one source — see that file's header for the
// "we were drifting silently" background.
/** Test seam: the real IPC handler calls `detectChatgptSubscription()` with
* no args, which resolves the path via `codexAuthPath()`. Tests can pass
* a fabricated path pointing at a tmpdir file without having to mock
* `node:fs/promises`. */
export async function detectChatgptSubscription(
authPath: string = codexAuthPath(),
): Promise<boolean> {
try {
const raw = await readFile(authPath, 'utf8');
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== 'object' || parsed === null) return false;
return (parsed as Record<string, unknown>)['auth_mode'] === 'chatgpt';
} catch (err) {
// ENOENT is the "no Codex installed" case; every other error (EACCES,
// corrupt JSON, etc.) drives the wrong error-message branch for the
// caller, so log it instead of swallowing silently.
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
logger.warn('detect_chatgpt_subscription.failed', {
code: code ?? 'unknown',
err: err instanceof Error ? err.message : String(err),
});
}
return false;
}
}
async function runImportCodex(imported: CodexImport): Promise<OnboardingState> {
if (imported.providers.length === 0) {
throw new CodesignError(
(await detectChatgptSubscription())
? 'Detected Codex ChatGPT subscription login (auth_mode: chatgpt). It cannot be imported as an API-key provider yet — the "Sign in with ChatGPT subscription" feature is still being polished and will ship in the next release. For now, configure [model_providers] in ~/.codex/config.toml manually, or switch to API-key mode in Codex. / 检测到 Codex 使用 ChatGPT 订阅登录,无法自动导入为 API key provider。"用 ChatGPT 订阅登录"功能仍在打磨中,下个版本开放 —— 目前请在 ~/.codex/config.toml 里手动配置 [model_providers],或改用 API key 登录 Codex。'
: 'No importable API provider found in Codex config (~/.codex/config.toml is missing a [model_providers] section). / Codex 配置里没有可导入的 API provider(~/.codex/config.toml 里缺少 [model_providers] 段)。',
ERROR_CODES.CONFIG_MISSING,
);
}
const nextProviders: Record<string, ProviderEntry> = { ...(cachedConfig?.providers ?? {}) };
const nextSecrets = { ...(cachedConfig?.secrets ?? {}) };
// Seed builtins if we're on a fresh install so the user keeps a fallback.
if (cachedConfig === null) {
for (const [id, entry] of Object.entries(BUILTIN_PROVIDERS)) {
if (nextProviders[id] === undefined) nextProviders[id] = { ...entry };
}
}
for (const entry of imported.providers) {
nextProviders[entry.id] = entry;
const importedApiKey = imported.apiKeyMap[entry.id]?.trim();
if (entry.envKey !== undefined) {
const envValue = process.env[entry.envKey]?.trim();
if (envValue !== undefined && envValue.length > 0) {
// buildSecretRef throws only on empty input — length is already
// guarded. Bare call instead of wrapping in try/catch so any future
// invariant break fails loudly rather than quietly writing a row
// with no key and reporting success.
nextSecrets[entry.id] = buildSecretRef(envValue);
continue;
}
}
const fallbackApiKey =
importedApiKey !== undefined && importedApiKey.length > 0
? importedApiKey
: entry.requiresApiKey === true
? process.env['OPENAI_API_KEY']?.trim()
: undefined;
if (fallbackApiKey !== undefined && fallbackApiKey.length > 0) {
nextSecrets[entry.id] = buildSecretRef(fallbackApiKey);
}
}
const fallbackActive = imported.providers[0];
if (fallbackActive === undefined) {
throw new CodesignError('Codex config parse produced no providers', ERROR_CODES.CONFIG_MISSING);
}
const activeProvider =
imported.activeProvider !== null && nextProviders[imported.activeProvider] !== undefined
? imported.activeProvider
: fallbackActive.id;
const activeModel = imported.activeModel ?? nextProviders[activeProvider]?.defaultModel ?? '';
const next = hydrateConfig({
version: 3,
activeProvider,
activeModel,
secrets: nextSecrets,
providers: nextProviders,
...(cachedConfig?.designSystem !== undefined
? { designSystem: cachedConfig.designSystem }
: {}),
});
await writeConfig(next);
cachedConfig = next;
configLoaded = true;
return toState(cachedConfig);
}
async function runImportClaudeCode(imported: ClaudeCodeImport): Promise<OnboardingState> {
// OAuth-only users: bail loudly without touching config. The renderer
// catches this error code and shows the "subscription can't be shared"
// banner instead of a fake "imported" toast that would then immediately
// leave the user in a dead-locked hasKey:false state.
if (imported.userType === 'oauth-only') {
throw new CodesignError(
'Claude Code uses OAuth subscription auth. Generate an API key at https://console.anthropic.com to use it here.',
ERROR_CODES.CLAUDE_CODE_OAUTH_ONLY,
);
}
if (imported.provider === null) {
throw new CodesignError('Claude Code config produced no provider', ERROR_CODES.CONFIG_MISSING);
}
const nextProviders: Record<string, ProviderEntry> = { ...(cachedConfig?.providers ?? {}) };
const nextSecrets = { ...(cachedConfig?.secrets ?? {}) };
if (cachedConfig === null) {
for (const [id, entry] of Object.entries(BUILTIN_PROVIDERS)) {
if (nextProviders[id] === undefined) nextProviders[id] = { ...entry };
}
}
nextProviders[imported.provider.id] = imported.provider;
const importedApiKey = imported.apiKey?.trim();
const keySaved = importedApiKey !== undefined && importedApiKey.length > 0;
if (keySaved) {
nextSecrets[imported.provider.id] = buildSecretRef(importedApiKey);
}
// Flip active only when we have a key the new provider can actually use,
// or when the user is on a fresh install (no existing active to preserve).
// This is what kills the "active swapped to claude-code-imported but no
// key stored → hasKey:false → Onboarding is not complete" death path.
const shouldActivate = keySaved || cachedConfig === null;
const nextActiveProvider = shouldActivate
? imported.provider.id
: (cachedConfig?.activeProvider ?? '');
const nextActiveModel = shouldActivate
? (imported.activeModel ?? imported.provider.defaultModel)
: (cachedConfig?.activeModel ?? '');
const next = hydrateConfig({
version: 3,
activeProvider: nextActiveProvider,
activeModel: nextActiveModel,
secrets: nextSecrets,
providers: nextProviders,
...(cachedConfig?.designSystem !== undefined
? { designSystem: cachedConfig.designSystem }
: {}),
});
await writeConfig(next);
cachedConfig = next;
configLoaded = true;
return toState(cachedConfig);
}
async function runImportGemini(imported: GeminiImport): Promise<OnboardingState> {
// Blocked state: Vertex detection etc. — no provider to write. The
// renderer catches CONFIG_MISSING and surfaces the warning in a toast.
if (imported.kind === 'blocked') {
throw new CodesignError(
imported.warnings[0] ?? 'Gemini CLI config produced no provider',
ERROR_CODES.CONFIG_MISSING,
);
}
const nextProviders: Record<string, ProviderEntry> = { ...(cachedConfig?.providers ?? {}) };
const nextSecrets = { ...(cachedConfig?.secrets ?? {}) };
if (cachedConfig === null) {
for (const [id, entry] of Object.entries(BUILTIN_PROVIDERS)) {
if (nextProviders[id] === undefined) nextProviders[id] = { ...entry };
}
}
nextProviders[imported.provider.id] = imported.provider;
const importedApiKey = imported.apiKey.trim();
const keySaved = importedApiKey.length > 0;
if (keySaved) {
nextSecrets[imported.provider.id] = buildSecretRef(importedApiKey);
}
const shouldActivate = keySaved || cachedConfig === null;
const nextActiveProvider = shouldActivate
? imported.provider.id
: (cachedConfig?.activeProvider ?? '');
const nextActiveModel = shouldActivate
? imported.provider.defaultModel
: (cachedConfig?.activeModel ?? '');
const next = hydrateConfig({
version: 3,
activeProvider: nextActiveProvider,
activeModel: nextActiveModel,
secrets: nextSecrets,
providers: nextProviders,
...(cachedConfig?.designSystem !== undefined
? { designSystem: cachedConfig.designSystem }
: {}),
});
await writeConfig(next);
cachedConfig = next;
configLoaded = true;
return toState(cachedConfig);
}
async function runImportOpencode(imported: OpencodeImport): Promise<OnboardingState> {
if (imported.providers.length === 0) {
throw new CodesignError(
'No importable API provider found in OpenCode auth.json (~/.local/share/opencode/auth.json). Log in to a provider with an API key in OpenCode first. / OpenCode 配置里没有可导入的 API provider,请先在 OpenCode 里用 API key 登录。',
ERROR_CODES.CONFIG_MISSING,
);
}