-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathProviderSettingsManager.ts
More file actions
917 lines (789 loc) · 29 KB
/
Copy pathProviderSettingsManager.ts
File metadata and controls
917 lines (789 loc) · 29 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
import { ExtensionContext } from "vscode"
import { z, ZodError } from "zod"
import deepEqual from "fast-deep-equal"
import {
type ProviderSettingsWithId,
providerSettingsWithIdSchema,
discriminatedProviderSettingsWithIdSchema,
isSecretStateKey,
ProviderSettingsEntry,
DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
getModelId,
type ProviderName,
isProviderName,
isRetiredProvider,
} from "@roo-code/types"
import { TelemetryService } from "@roo-code/telemetry"
import { Mode, modes } from "../../shared/modes"
import { buildApiHandler } from "../../api"
import { downgradeLegacyRooConfig } from "./routerRemoval"
// Type-safe model migrations mapping
type ModelMigrations = {
[K in ProviderName]?: Record<string, string>
}
const MODEL_MIGRATIONS: ModelMigrations = {} as const satisfies ModelMigrations
export interface SyncCloudProfilesResult {
hasChanges: boolean
activeProfileChanged: boolean
activeProfileId: string
}
export const providerProfilesSchema = z.object({
currentApiConfigName: z.string(),
apiConfigs: z.record(z.string(), providerSettingsWithIdSchema),
modeApiConfigs: z.record(z.string(), z.string()).optional(),
cloudProfileIds: z.array(z.string()).optional(),
migrations: z
.object({
rateLimitSecondsMigrated: z.boolean().optional(),
openAiHeadersMigrated: z.boolean().optional(),
consecutiveMistakeLimitMigrated: z.boolean().optional(),
todoListEnabledMigrated: z.boolean().optional(),
claudeCodeLegacySettingsMigrated: z.boolean().optional(),
routerProviderMigrated: z.boolean().optional(),
})
.optional(),
})
export type ProviderProfiles = z.infer<typeof providerProfilesSchema>
export class ProviderSettingsManager {
private static readonly SCOPE_PREFIX = "roo_cline_config_"
private readonly defaultConfigId = this.generateId()
private readonly defaultModeApiConfigs: Record<string, string> = Object.fromEntries(
modes.map((mode) => [mode.slug, this.defaultConfigId]),
)
private readonly defaultProviderProfiles: ProviderProfiles = {
currentApiConfigName: "default",
apiConfigs: { default: { id: this.defaultConfigId } },
modeApiConfigs: this.defaultModeApiConfigs,
migrations: {
rateLimitSecondsMigrated: true, // Mark as migrated on fresh installs
openAiHeadersMigrated: true, // Mark as migrated on fresh installs
consecutiveMistakeLimitMigrated: true, // Mark as migrated on fresh installs
todoListEnabledMigrated: true, // Mark as migrated on fresh installs
claudeCodeLegacySettingsMigrated: true, // Mark as migrated on fresh installs
routerProviderMigrated: true, // Mark as migrated on fresh installs
},
}
private readonly context: ExtensionContext
constructor(context: ExtensionContext) {
this.context = context
// TODO: We really shouldn't have async methods in the constructor.
this.initialize().catch(console.error)
}
public generateId() {
return Math.random().toString(36).substring(2, 15)
}
// Synchronize readConfig/writeConfig operations to avoid data loss.
private _lock = Promise.resolve()
private lock<T>(cb: () => Promise<T>) {
const next = this._lock.then(cb)
this._lock = next.catch(() => {}) as Promise<void>
return next
}
/**
* Initialize config if it doesn't exist and run migrations.
*/
public async initialize() {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
if (!providerProfiles) {
await this.store(this.defaultProviderProfiles)
return
}
let isDirty = false
// Migrate existing installs to have per-mode API config map
if (!providerProfiles.modeApiConfigs) {
// Use the currently selected config for all modes initially
const currentName = providerProfiles.currentApiConfigName
const seedId =
providerProfiles.apiConfigs[currentName]?.id ??
Object.values(providerProfiles.apiConfigs)[0]?.id ??
this.defaultConfigId
providerProfiles.modeApiConfigs = Object.fromEntries(modes.map((m) => [m.slug, seedId]))
isDirty = true
}
// Apply model migrations for all providers
if (this.applyModelMigrations(providerProfiles)) {
isDirty = true
}
// Ensure all configs have IDs.
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
if (!apiConfig.id) {
apiConfig.id = this.generateId()
isDirty = true
}
}
// Ensure migrations field exists
if (!providerProfiles.migrations) {
providerProfiles.migrations = {
rateLimitSecondsMigrated: false,
openAiHeadersMigrated: false,
consecutiveMistakeLimitMigrated: false,
todoListEnabledMigrated: false,
claudeCodeLegacySettingsMigrated: false,
routerProviderMigrated: false,
} // Initialize with default values
isDirty = true
}
if (!providerProfiles.migrations.routerProviderMigrated) {
if (this.migrateLegacyRooProviderProfiles(providerProfiles)) {
isDirty = true
}
providerProfiles.migrations.routerProviderMigrated = true
isDirty = true
}
if (!providerProfiles.migrations.rateLimitSecondsMigrated) {
await this.migrateRateLimitSeconds(providerProfiles)
providerProfiles.migrations.rateLimitSecondsMigrated = true
isDirty = true
}
if (!providerProfiles.migrations.openAiHeadersMigrated) {
await this.migrateOpenAiHeaders(providerProfiles)
providerProfiles.migrations.openAiHeadersMigrated = true
isDirty = true
}
if (!providerProfiles.migrations.consecutiveMistakeLimitMigrated) {
await this.migrateConsecutiveMistakeLimit(providerProfiles)
providerProfiles.migrations.consecutiveMistakeLimitMigrated = true
isDirty = true
}
if (!providerProfiles.migrations.todoListEnabledMigrated) {
await this.migrateTodoListEnabled(providerProfiles)
providerProfiles.migrations.todoListEnabledMigrated = true
isDirty = true
}
if (!providerProfiles.migrations.claudeCodeLegacySettingsMigrated) {
// These keys were used by the removed local Claude Code CLI wrapper.
for (const apiConfig of Object.values(providerProfiles.apiConfigs)) {
// Cast to string for comparison since "claude-code" is no longer a valid ProviderName
if ((apiConfig.apiProvider as string) !== "claude-code") continue
const config = apiConfig as unknown as Record<string, unknown>
if ("claudeCodePath" in config) {
delete config.claudeCodePath
isDirty = true
}
if ("claudeCodeMaxOutputTokens" in config) {
delete config.claudeCodeMaxOutputTokens
isDirty = true
}
}
providerProfiles.migrations.claudeCodeLegacySettingsMigrated = true
isDirty = true
}
if (isDirty) {
await this.store(providerProfiles)
}
})
} catch (error) {
throw new Error(`Failed to initialize config: ${error}`)
}
}
private async migrateRateLimitSeconds(providerProfiles: ProviderProfiles) {
try {
let rateLimitSeconds: number | undefined
try {
rateLimitSeconds = await this.context.globalState.get<number>("rateLimitSeconds")
} catch (error) {
console.error("[MigrateRateLimitSeconds] Error getting global rate limit:", error)
}
if (rateLimitSeconds === undefined) {
// Failed to get the existing value, use the default.
rateLimitSeconds = 0
}
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
if (apiConfig.rateLimitSeconds === undefined) {
apiConfig.rateLimitSeconds = rateLimitSeconds
}
}
} catch (error) {
console.error(`[MigrateRateLimitSeconds] Failed to migrate rate limit settings:`, error)
}
}
private async migrateOpenAiHeaders(providerProfiles: ProviderProfiles) {
try {
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
// Use type assertion to access the deprecated property safely
const configAny = apiConfig as any
// Check if openAiHostHeader exists but openAiHeaders doesn't
if (
configAny.openAiHostHeader &&
(!apiConfig.openAiHeaders || Object.keys(apiConfig.openAiHeaders || {}).length === 0)
) {
// Create the headers object with the Host value
apiConfig.openAiHeaders = { Host: configAny.openAiHostHeader }
// Delete the old property to prevent re-migration
// This prevents the header from reappearing after deletion
configAny.openAiHostHeader = undefined
}
}
} catch (error) {
console.error(`[MigrateOpenAiHeaders] Failed to migrate OpenAI headers:`, error)
}
}
private async migrateConsecutiveMistakeLimit(providerProfiles: ProviderProfiles) {
try {
for (const [name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
if (apiConfig.consecutiveMistakeLimit == null) {
apiConfig.consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT
}
}
} catch (error) {
console.error(`[MigrateConsecutiveMistakeLimit] Failed to migrate consecutive mistake limit:`, error)
}
}
private async migrateTodoListEnabled(providerProfiles: ProviderProfiles) {
try {
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
if (apiConfig.todoListEnabled === undefined) {
apiConfig.todoListEnabled = true
}
}
} catch (error) {
console.error(`[MigrateTodoListEnabled] Failed to migrate todo list enabled setting:`, error)
}
}
/**
* Apply model migrations for all providers
* Returns true if any migrations were applied
*/
private applyModelMigrations(providerProfiles: ProviderProfiles): boolean {
let migrated = false
try {
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
// Skip configs without provider or model ID
if (!apiConfig.apiProvider || !apiConfig.apiModelId) {
continue
}
// Check if this provider has migrations (with type safety)
const provider = apiConfig.apiProvider as ProviderName
const providerMigrations = MODEL_MIGRATIONS[provider]
if (!providerMigrations) {
continue
}
// Check if the current model ID needs migration
const newModelId = providerMigrations[apiConfig.apiModelId]
if (newModelId && newModelId !== apiConfig.apiModelId) {
console.log(
`[ModelMigration] Migrating ${apiConfig.apiProvider} model from ${apiConfig.apiModelId} to ${newModelId}`,
)
apiConfig.apiModelId = newModelId
migrated = true
}
}
} catch (error) {
console.error(`[ModelMigration] Failed to apply model migrations:`, error)
}
return migrated
}
private migrateLegacyRooProviderProfiles(providerProfiles: ProviderProfiles): boolean {
let migrated = false
for (const [name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
const { config: downgradedConfig, migrated: didMigrate } = downgradeLegacyRooConfig(
apiConfig as Record<string, unknown>,
)
if (!didMigrate) {
continue
}
providerProfiles.apiConfigs[name] = providerSettingsWithIdSchema.parse(downgradedConfig)
migrated = true
}
return migrated
}
/**
* Clean model ID by removing prefix before "/"
*/
private cleanModelId(modelId: string | undefined): string | undefined {
if (!modelId) return undefined
// Check for "/" and take the part after it
if (modelId.includes("/")) {
return modelId.split("/").pop()
}
return modelId
}
/**
* List all available configs with metadata.
*/
public async listConfig(): Promise<ProviderSettingsEntry[]> {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
return Object.entries(providerProfiles.apiConfigs).map(([name, apiConfig]) => ({
name,
id: apiConfig.id || "",
apiProvider: apiConfig.apiProvider,
modelId: this.cleanModelId(getModelId(apiConfig)),
}))
})
} catch (error) {
throw new Error(`Failed to list configs: ${error}`)
}
}
/**
* Save a config with the given name.
* Preserves the ID from the input 'config' object if it exists,
* otherwise generates a new one (for creation scenarios).
*/
public async saveConfig(name: string, config: ProviderSettingsWithId): Promise<string> {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
// Preserve the existing ID if this is an update to an existing config.
const existingId = providerProfiles.apiConfigs[name]?.id
const id = config.id || existingId || this.generateId()
const normalizedConfig = downgradeLegacyRooConfig(config as Record<string, unknown>)
.config as ProviderSettingsWithId
// For active providers, filter out settings from other providers.
// For retired providers, preserve full profile fields (including legacy
// provider-specific keys) to avoid data loss — passthrough() keeps
// unknown keys that strict parse() would strip.
const filteredConfig =
typeof normalizedConfig.apiProvider === "string" && isRetiredProvider(normalizedConfig.apiProvider)
? providerSettingsWithIdSchema.passthrough().parse(normalizedConfig)
: discriminatedProviderSettingsWithIdSchema.parse(normalizedConfig)
providerProfiles.apiConfigs[name] = { ...filteredConfig, id }
await this.store(providerProfiles)
return id
})
} catch (error) {
throw new Error(`Failed to save config: ${error}`)
}
}
public async getProfile(
params: { name: string } | { id: string },
): Promise<ProviderSettingsWithId & { name: string }> {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
let name: string
let providerSettings: ProviderSettingsWithId
if ("name" in params) {
name = params.name
if (!providerProfiles.apiConfigs[name]) {
throw new Error(`Config with name '${name}' not found`)
}
providerSettings = providerProfiles.apiConfigs[name]
} else {
const id = params.id
const entry = Object.entries(providerProfiles.apiConfigs).find(
([_, apiConfig]) => apiConfig.id === id,
)
if (!entry) {
throw new Error(`Config with ID '${id}' not found`)
}
name = entry[0]
providerSettings = entry[1]
}
return { name, ...providerSettings }
})
} catch (error) {
throw new Error(`Failed to get profile: ${error instanceof Error ? error.message : error}`)
}
}
/**
* Activate a profile by name or ID.
*/
public async activateProfile(
params: { name: string } | { id: string },
): Promise<ProviderSettingsWithId & { name: string }> {
const { name, ...providerSettings } = await this.getProfile(params)
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
providerProfiles.currentApiConfigName = name
await this.store(providerProfiles)
return { name, ...providerSettings }
})
} catch (error) {
throw new Error(`Failed to activate profile: ${error instanceof Error ? error.message : error}`)
}
}
/**
* Delete a config by name.
*/
public async deleteConfig(name: string) {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
if (!providerProfiles.apiConfigs[name]) {
throw new Error(`Config '${name}' not found`)
}
if (Object.keys(providerProfiles.apiConfigs).length === 1) {
throw new Error(`Cannot delete the last remaining configuration`)
}
delete providerProfiles.apiConfigs[name]
await this.store(providerProfiles)
})
} catch (error) {
throw new Error(`Failed to delete config: ${error}`)
}
}
/**
* Check if a config exists by name.
*/
public async hasConfig(name: string) {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
return name in providerProfiles.apiConfigs
})
} catch (error) {
throw new Error(`Failed to check config existence: ${error}`)
}
}
/**
* Set the API config for a specific mode.
*/
public async setModeConfig(mode: Mode, configId: string) {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
// Ensure the per-mode config map exists
if (!providerProfiles.modeApiConfigs) {
providerProfiles.modeApiConfigs = {}
}
// Assign the chosen config ID to this mode
providerProfiles.modeApiConfigs[mode] = configId
await this.store(providerProfiles)
})
} catch (error) {
throw new Error(`Failed to set mode config: ${error}`)
}
}
/**
* Get the API config ID for a specific mode.
*/
public async getModeConfigId(mode: Mode) {
try {
return await this.lock(async () => {
const { modeApiConfigs } = await this.load()
return modeApiConfigs?.[mode]
})
} catch (error) {
throw new Error(`Failed to get mode config: ${error}`)
}
}
public async export() {
try {
return await this.lock(async () => {
const profiles = providerProfilesSchema.parse(await this.load())
const configs = profiles.apiConfigs
for (const name in configs) {
const apiProvider = configs[name].apiProvider
if (typeof apiProvider === "string" && isRetiredProvider(apiProvider)) {
// Preserve retired-provider profiles as-is to prevent dropping legacy fields.
continue
}
// Avoid leaking properties from other active providers.
configs[name] = discriminatedProviderSettingsWithIdSchema.parse(configs[name])
// If it has no apiProvider, skip filtering
if (!configs[name].apiProvider) {
continue
}
// Try to build an API handler to get model information
try {
const apiHandler = buildApiHandler(configs[name])
const modelInfo = apiHandler.getModel().info
// Check if the model supports reasoning budgets
const supportsReasoningBudget =
modelInfo.supportsReasoningBudget || modelInfo.requiredReasoningBudget
// modelMaxThinkingTokens only applies to reasoning budgets, but modelMaxTokens
// also caps output on models that expose a configurable max (e.g. GLM), so keep
// it whenever the model supports either feature.
const supportsMaxTokens = supportsReasoningBudget || modelInfo.supportsMaxTokens
if (!supportsReasoningBudget) {
delete configs[name].modelMaxThinkingTokens
}
if (!supportsMaxTokens) {
delete configs[name].modelMaxTokens
}
} catch (error) {
// If we can't build the API handler or get model info, skip filtering
// to avoid accidental data loss from incomplete configurations
console.warn(`Skipping token field filtering for config '${name}': ${error}`)
}
}
return profiles
})
} catch (error) {
throw new Error(`Failed to export provider profiles: ${error}`)
}
}
public async import(providerProfiles: ProviderProfiles) {
try {
return await this.lock(() => this.store(providerProfiles))
} catch (error) {
throw new Error(`Failed to import provider profiles: ${error}`)
}
}
/**
* Reset provider profiles by deleting them from secrets.
*/
public async resetAllConfigs() {
return await this.lock(async () => {
await this.context.secrets.delete(this.secretsKey)
})
}
private get secretsKey() {
return `${ProviderSettingsManager.SCOPE_PREFIX}api_config`
}
private async load(): Promise<ProviderProfiles> {
try {
const content = await this.context.secrets.get(this.secretsKey)
if (!content) {
return this.defaultProviderProfiles
}
const providerProfiles = providerProfilesSchema
.extend({
apiConfigs: z.record(z.string(), z.any()),
})
.parse(JSON.parse(content))
const apiConfigs = Object.entries(providerProfiles.apiConfigs).reduce(
(acc, [key, apiConfig]) => {
// First, sanitize invalid apiProvider values before parsing
// This handles removed providers (like "glama") gracefully
const sanitizedConfig = this.sanitizeProviderConfig(apiConfig)
// For retired providers, use passthrough() to preserve legacy
// provider-specific fields (e.g. groqApiKey, deepInfraModelId)
// that strict parse() would strip.
const providerValue =
typeof sanitizedConfig === "object" &&
sanitizedConfig !== null &&
"apiProvider" in sanitizedConfig
? (sanitizedConfig as Record<string, unknown>).apiProvider
: undefined
const schema =
typeof providerValue === "string" && isRetiredProvider(providerValue)
? providerSettingsWithIdSchema.passthrough()
: providerSettingsWithIdSchema
const result = schema.safeParse(sanitizedConfig)
return result.success ? { ...acc, [key]: result.data } : acc
},
{} as Record<string, ProviderSettingsWithId>,
)
return {
...providerProfiles,
apiConfigs: Object.fromEntries(
Object.entries(apiConfigs).filter(([_, apiConfig]) => apiConfig !== null),
),
}
} catch (error) {
if (error instanceof ZodError) {
TelemetryService.instance.captureSchemaValidationError({
schemaName: "ProviderProfiles",
error,
})
}
throw new Error(`Failed to read provider profiles from secrets: ${error}`)
}
}
/**
* Sanitizes a provider config by resetting unknown apiProvider values.
* Retired providers are preserved.
* This handles cases where a user had a provider selected that was later removed
* from the extension (e.g., "glama").
*/
private sanitizeProviderConfig(apiConfig: unknown): unknown {
if (typeof apiConfig !== "object" || apiConfig === null) {
return apiConfig
}
const { config } = downgradeLegacyRooConfig(apiConfig as Record<string, unknown>)
const apiProvider = config.apiProvider
// Check if apiProvider is set and if it's still recognized (active or retired)
if (
apiProvider !== undefined &&
(typeof apiProvider !== "string" || (!isProviderName(apiProvider) && !isRetiredProvider(apiProvider)))
) {
console.log(
`[ProviderSettingsManager] Sanitizing unknown provider "${config.apiProvider}" - resetting to undefined`,
)
// Return a new config object without the invalid apiProvider
// This effectively resets the profile so the user can select a valid provider
const { apiProvider, ...restConfig } = config
return restConfig
}
return apiConfig
}
private async store(providerProfiles: ProviderProfiles) {
try {
await this.context.secrets.store(this.secretsKey, JSON.stringify(providerProfiles, null, 2))
} catch (error) {
throw new Error(`Failed to write provider profiles to secrets: ${error}`)
}
}
private findUniqueProfileName(baseName: string, existingNames: Set<string>): string {
if (!existingNames.has(baseName)) {
return baseName
}
// Try _local first
const localName = `${baseName}_local`
if (!existingNames.has(localName)) {
return localName
}
// Try _1, _2, etc.
let counter = 1
let candidateName: string
do {
candidateName = `${baseName}_${counter}`
counter++
} while (existingNames.has(candidateName))
return candidateName
}
public async syncCloudProfiles(
cloudProfiles: Record<string, ProviderSettingsWithId>,
currentActiveProfileName?: string,
): Promise<SyncCloudProfilesResult> {
try {
return await this.lock(async () => {
const providerProfiles = await this.load()
const changedProfiles: string[] = []
const existingNames = new Set(Object.keys(providerProfiles.apiConfigs))
let activeProfileChanged = false
let activeProfileId = ""
if (currentActiveProfileName && providerProfiles.apiConfigs[currentActiveProfileName]) {
activeProfileId = providerProfiles.apiConfigs[currentActiveProfileName].id || ""
}
const currentCloudIds = new Set(providerProfiles.cloudProfileIds || [])
const newCloudIds = new Set(
Object.values(cloudProfiles)
.map((p) => p.id)
.filter((id): id is string => Boolean(id)),
)
// Step 1: Delete profiles that are cloud-managed but not in the new cloud profiles
for (const [name, profile] of Object.entries(providerProfiles.apiConfigs)) {
if (profile.id && currentCloudIds.has(profile.id) && !newCloudIds.has(profile.id)) {
// Check if we're deleting the active profile
if (name === currentActiveProfileName) {
activeProfileChanged = true
activeProfileId = "" // Clear the active profile ID since it's being deleted
}
delete providerProfiles.apiConfigs[name]
changedProfiles.push(name)
existingNames.delete(name)
}
}
// Step 2: Process each cloud profile
for (const [cloudName, cloudProfile] of Object.entries(cloudProfiles)) {
if (!cloudProfile.id) {
continue // Skip profiles without IDs
}
// Find existing profile with matching ID
const existingEntry = Object.entries(providerProfiles.apiConfigs).find(
([_, profile]) => profile.id === cloudProfile.id,
)
if (existingEntry) {
// Step 3: Update existing profile
const [existingName, existingProfile] = existingEntry
// Check if this is the active profile
const isActiveProfile = existingName === currentActiveProfileName
// Merge settings, preserving secret keys
const updatedProfile: ProviderSettingsWithId = { ...cloudProfile }
for (const [key, value] of Object.entries(existingProfile)) {
if (isSecretStateKey(key) && value !== undefined) {
;(updatedProfile as any)[key] = value
}
}
// Check if the profile actually changed using deepEqual
const profileChanged = !deepEqual(existingProfile, updatedProfile)
// Handle name change
if (existingName !== cloudName) {
// Remove old entry
delete providerProfiles.apiConfigs[existingName]
existingNames.delete(existingName)
// Handle name conflict
const finalName = cloudName
if (existingNames.has(cloudName)) {
// There's a conflict - rename the existing non-cloud profile
const conflictingProfile = providerProfiles.apiConfigs[cloudName]
if (conflictingProfile.id !== cloudProfile.id) {
const newName = this.findUniqueProfileName(cloudName, existingNames)
providerProfiles.apiConfigs[newName] = conflictingProfile
existingNames.add(newName)
changedProfiles.push(newName)
}
delete providerProfiles.apiConfigs[cloudName]
existingNames.delete(cloudName)
}
// Add updated profile with new name
providerProfiles.apiConfigs[finalName] = updatedProfile
existingNames.add(finalName)
changedProfiles.push(finalName)
if (existingName !== finalName) {
changedProfiles.push(existingName) // Mark old name as changed (deleted)
}
// If this was the active profile, mark it as changed
if (isActiveProfile) {
activeProfileChanged = true
activeProfileId = cloudProfile.id || ""
}
} else if (profileChanged) {
// Same name, but profile content changed - update in place
providerProfiles.apiConfigs[existingName] = updatedProfile
changedProfiles.push(existingName)
// If this was the active profile and settings changed, mark it as changed
if (isActiveProfile) {
activeProfileChanged = true
activeProfileId = cloudProfile.id || ""
}
}
// If name is the same and profile hasn't changed, do nothing
} else {
// Step 4: Add new cloud profile
const finalName = cloudName
// Handle name conflict with existing non-cloud profile
if (existingNames.has(cloudName)) {
const existingProfile = providerProfiles.apiConfigs[cloudName]
if (existingProfile.id !== cloudProfile.id) {
// Rename the existing profile
const newName = this.findUniqueProfileName(cloudName, existingNames)
providerProfiles.apiConfigs[newName] = existingProfile
existingNames.add(newName)
changedProfiles.push(newName)
// Remove the old entry
delete providerProfiles.apiConfigs[cloudName]
existingNames.delete(cloudName)
}
}
// Add the new cloud profile (without secret keys)
const newProfile: ProviderSettingsWithId = { ...cloudProfile }
// Remove any secret keys from cloud profile
for (const key of Object.keys(newProfile)) {
if (isSecretStateKey(key)) {
delete (newProfile as any)[key]
}
}
providerProfiles.apiConfigs[finalName] = newProfile
existingNames.add(finalName)
changedProfiles.push(finalName)
}
}
// Step 5: Handle case where all profiles might be deleted
if (Object.keys(providerProfiles.apiConfigs).length === 0 && changedProfiles.length > 0) {
// Create a default profile only if we have changed profiles
const defaultProfile = { id: this.generateId() }
providerProfiles.apiConfigs["default"] = defaultProfile
activeProfileChanged = true
activeProfileId = defaultProfile.id || ""
changedProfiles.push("default")
}
// Step 6: If active profile was deleted, find a replacement
if (activeProfileChanged && !activeProfileId) {
const firstProfile = Object.values(providerProfiles.apiConfigs)[0]
if (firstProfile?.id) {
activeProfileId = firstProfile.id
}
}
// Step 7: Update cloudProfileIds
providerProfiles.cloudProfileIds = Array.from(newCloudIds)
// Save the updated profiles
await this.store(providerProfiles)
return {
hasChanges: changedProfiles.length > 0,
activeProfileChanged,
activeProfileId,
}
})
} catch (error) {
throw new Error(`Failed to sync cloud profiles: ${error}`)
}
}
}