-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAI-Config-Manager.ps1
More file actions
1302 lines (1173 loc) · 58.2 KB
/
Copy pathAI-Config-Manager.ps1
File metadata and controls
1302 lines (1173 loc) · 58.2 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
# AI Config Manager
#
# Arrow-key TUI to point Claude Code, OpenCode, and Codex at a custom gateway
# (AgentRouter, EuroModels, or any OpenAI/Anthropic-compatible base URL), and to
# launch Hermes Desktop's own model setup. Presets live in AI-Config-Presets.json;
# model lists are fetched live when the gateway allows it, with curated fallbacks.
#
# Requires Windows PowerShell 5.1+ or PowerShell 7+, and curl (curl.exe is
# bundled with Windows 10/11; pwsh's curl on Linux/macOS). Existing config files
# are backed up before every write.
#
# Usage: powershell -ExecutionPolicy Bypass -File .\AI-Config-Manager.ps1
# Selftest: powershell -File .\AI-Config-Manager.ps1 -SelfTest
param([switch]$SelfTest, [switch]$SkipVersionCheck)
$ErrorActionPreference = "Stop"
$Host.UI.RawUI.WindowTitle = "AI Config Manager"
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}
# Platform detection (works in both Windows PowerShell 5.1 and pwsh 7+).
$script:IsWindows = ($PSVersionTable.PSEdition -eq 'Desktop') -or ((Get-Variable IsWindows -ErrorAction SilentlyContinue) -and $IsWindows)
$script:IsLinux = (Get-Variable IsLinux -ErrorAction SilentlyContinue) -and $IsLinux
$script:IsMacOS = (Get-Variable IsMacOS -ErrorAction SilentlyContinue) -and $IsMacOS
$script:CurlBin = if ($script:IsWindows) { 'curl.exe' } else { 'curl' }
$script:Version = "1.2.1"
# Compare two dotted version strings ("v1.2.0" vs "1.2.1"). Returns $true if the
# first is older than the second. Missing segments count as 0.
function Test-OlderVersion([string]$Current, [string]$Latest) {
$a = @(($Current -replace "^v", "").Split(".")) + @("0", "0", "0")
$b = @(($Latest -replace "^v", "").Split(".")) + @("0", "0", "0")
for ($i = 0; $i -lt 3; $i++) {
$ai = 0; $bi = 0
[void][int]::TryParse($a[$i], [ref]$ai)
[void][int]::TryParse($b[$i], [ref]$bi)
if ($ai -lt $bi) { return $true }
if ($ai -gt $bi) { return $false }
}
return $false
}
# Best-effort check of the latest release tag on GitHub. Fails silently offline
# (returns $null) and never blocks startup for long.
function Get-LatestVersion {
$tag = $null
$tmp = [IO.Path]::GetTempFileName()
try {
$json = & $script:CurlBin "-sS" "--connect-timeout", "5", "--max-time", "10", "-H", "Accept: application/vnd.github+json", "-o", $tmp, "https://api.github.com/repos/TechTronixx/Custom-modelswitch/releases/latest"
$null = $json
if ($LASTEXITCODE -ne 0) { return $null }
$release = Get-Content $tmp -Raw | ConvertFrom-Json
$tag = [string]$release.tag_name
} catch { return $null }
finally { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
if ([string]::IsNullOrWhiteSpace($tag)) { return $null }
return $tag
}
# Runs the version check once at startup; stores the notice in the script scope.
function Check-ForUpdate {
if ($SkipVersionCheck) { return }
$latest = Get-LatestVersion
if ($null -eq $latest) { return }
if (Test-OlderVersion $script:Version $latest) {
$script:UpdateNotice = "Update available: $($script:Version) -> $latest (github.com/TechTronixx/Custom-modelswitch/releases)"
}
}
# Pure scroll-window math (extracted so it can be self-tested without a TTY).
function Get-ScrollWindow {
param([int]$Selected, [int]$Count, [int]$PageSize, [int]$CurrentTop)
if ($Count -le $PageSize) { return 0 }
if ($Selected -lt $CurrentTop) { return $Selected }
if ($Selected -ge ($CurrentTop + $PageSize)) { return $Selected - $PageSize + 1 }
return $CurrentTop
}
# ---------- UI helpers ----------
function Write-Banner([string]$Title) {
$w = [Console]::WindowWidth - 4
$title = " $Title "
$title = if ($title.Length -ge $w) { $title.Substring(0, $w - 1) } else { $title }
$pad = [Math]::Max(0, $w - $title.Length)
Write-Host ""
Write-Host (" " + "═" * $w) -ForegroundColor Cyan
Write-Host (" " + $title + " " * $pad) -ForegroundColor Black -BackgroundColor Cyan
Write-Host (" " + "═" * $w) -ForegroundColor Cyan
Write-Host ""
}
function Write-Separator {
Write-Host ""
Write-Host (" " + ("─" * 46)) -ForegroundColor DarkGray
Write-Host ""
}
function Show-Menu {
param(
[string]$Title,
[string[]]$Options,
[string[]]$Header = @(),
[int]$DefaultIndex = 0
)
if ($Options.Count -eq 0) { return -1 }
$selected = [Math]::Min($DefaultIndex, $Options.Count - 1)
$top = 0
while ($true) {
Clear-Host
Write-Banner $Title
$pageSize = [Math]::Max(5, [Console]::WindowHeight - 11 - $Header.Count)
$top = Get-ScrollWindow $selected $Options.Count $pageSize $top
$last = [Math]::Min($top + $pageSize, $Options.Count) - 1
# Compute box width from the widest visible line.
$lines = @()
foreach ($h in $Header) { $lines += (" " + $h) }
if ($Header.Count -gt 0) { $lines += "" }
for ($i = $top; $i -le $last; $i++) {
$lines += (" " + $Options[$i])
}
$scrollNote = ""
if ($top -gt 0 -or $last -lt $Options.Count - 1) {
$scrollNote = " ($($top + 1)-$($last + 1) of $($Options.Count))"
$lines += ""
$lines += $scrollNote
}
$inner = ($lines | Measure-Object -Property Length -Maximum).Maximum
$inner = [Math]::Min($inner, [Console]::WindowWidth - 6)
$inner = [Math]::Max($inner, 20)
Write-Host (" " + "╔" + "═" * $inner + "╗") -ForegroundColor Cyan
foreach ($h in $Header) {
Write-Host (" ║ " + $h.PadRight($inner - 2) + " ║") -ForegroundColor DarkGray
}
if ($Header.Count -gt 0) { Write-Host (" ║" + " " * $inner + "║") }
for ($i = $top; $i -le $last; $i++) {
if ($i -eq $selected) {
Write-Host (" ║ " + (" " + $Options[$i]).PadRight($inner - 2) + " ║") -ForegroundColor Black -BackgroundColor Cyan
} else {
Write-Host (" ║ " + (" " + $Options[$i]).PadRight($inner - 2) + " ║") -ForegroundColor Gray
}
}
if ($scrollNote) {
Write-Host (" ║" + " " * $inner + "║")
Write-Host (" ║ " + $scrollNote.Trim().PadRight($inner - 2) + " ║") -ForegroundColor DarkGray
}
Write-Host (" " + "╚" + "═" * $inner + "╝") -ForegroundColor Cyan
$pageLabel = if ($scrollNote) { $scrollNote.Trim() } else { "all $($Options.Count)" }
Write-Host ""
Write-Host (" " + "↑/↓ move highlight Enter select Esc back") -ForegroundColor DarkGray
Write-Host (" " + $pageLabel + " · v$script:Version") -ForegroundColor DarkGray
$key = [Console]::ReadKey($true)
switch ($key.Key) {
UpArrow { if ($selected -gt 0) { $selected-- } }
DownArrow { if ($selected -lt $Options.Count - 1) { $selected++ } }
Home { $selected = 0 }
End { $selected = $Options.Count - 1 }
Enter { return $selected }
Escape { return -1 }
}
}
}
function Pause-Screen {
Write-Host ""
Read-Host "Press Enter to continue" | Out-Null
}
# ---------- input helpers ----------
function Read-SecretPlain {
$secure = Read-Host "Enter API Key" -AsSecureString
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
}
function Mask-Key([string]$Key) {
if ([string]::IsNullOrWhiteSpace($Key)) { return "(empty)" }
if ($Key.Length -le 8) { return ("*" * $Key.Length) }
return $Key.Substring(0,4) + ("*" * [Math]::Min(12,$Key.Length-8)) + $Key.Substring($Key.Length-4)
}
function Normalize-BaseUrl([string]$Url) { return $Url.Trim().TrimEnd("/") }
# Cap how much of a server response we echo back on failure. A huge body is
# noise in a TUI; the status code plus a short excerpt is enough to diagnose.
function Truncate-Text([string]$Text, [int]$Max = 800) {
if ([string]::IsNullOrWhiteSpace($Text)) { return $Text }
if ($Text.Length -le $Max) { return $Text }
return $Text.Substring(0, $Max) + "`n...[truncated $($Text.Length - $Max) characters]"
}
# PS 5.1's ConvertFrom-Json throws on JSON object keys that are the empty string
# (AgentRouter's pricing payload has one, inside usable_group). Rename such keys
# to a harmless placeholder instead of regex-stripping a subtree, which is
# brittle when that subtree contains nested objects.
function Repair-JsonEmptyKeys([string]$Json) {
return [regex]::Replace($Json, '("")\s*:', '"__empty__":')
}
function Get-ModelsEndpoint([string]$BaseUrl) {
$b = Normalize-BaseUrl $BaseUrl
if ($b -match "/v1$") { return "$b/models" }
return "$b/v1/models"
}
# Run $Action and animate a spinner on its own line until it finishes. The
# spinner runs in a background runspace and only touches [Console], so it is
# safe to run alongside the blocking foreground call. Returns $Action's output.
# Console writes are best-effort: if stdout is redirected, the spinner silently
# does nothing rather than crashing the script.
function Invoke-Spinner([string]$Label, [scriptblock]$Action) {
Write-Host ""
$frames = '|/-\'
$rs = [RunspaceFactory]::CreateRunspace()
$rs.Open()
$spinner = [PowerShell]::Create()
$spinner.Runspace = $rs
$spinnerScript = {
param($label, $frames)
try {
$i = 0
while ($true) {
[Console]::Write("`r $label $($frames[$i++ % 4])")
[Threading.Thread]::Sleep(120)
}
} catch { }
}
$spinner.AddScript($spinnerScript.ToString()).AddArgument($Label).AddArgument($frames) | Out-Null
$async = $spinner.BeginInvoke()
try { return & $Action }
finally {
$spinner.Stop()
$spinner.Dispose()
$rs.Close()
$rs.Dispose()
try {
[Console]::Write(("`r $Label done") + (' ' * 4) + "`r")
[Console]::WriteLine()
} catch { }
}
}
# ---------- live model fetch ----------
function Get-LiveModels([string]$BaseUrl, [string]$ApiKey) {
$endpoint = Get-ModelsEndpoint $BaseUrl
Invoke-Spinner "Fetching models from $endpoint" {
$tmp = [IO.Path]::GetTempFileName()
try {
$curlArgs = @(
"-sS", "--fail-with-body",
"--connect-timeout", "15",
"--max-time", "45",
"-H", "Authorization: Bearer $ApiKey",
"-H", "Accept: application/json",
"-o", $tmp,
"-w", "%{http_code}",
$endpoint
)
$status = & $script:CurlBin @curlArgs
$exit = $LASTEXITCODE
$body = [IO.File]::ReadAllText($tmp, [Text.Encoding]::UTF8)
if ($exit -ne 0 -or $status -notmatch "^2") {
throw "Request failed. HTTP $status`n$(Truncate-Text $body)"
}
if ([string]::IsNullOrWhiteSpace($body)) {
throw "Request succeeded (HTTP $status) but the response body was empty."
}
$json = $body | ConvertFrom-Json
$ids = @()
if ($null -ne $json.data) {
$ids = @($json.data | ForEach-Object {
if ($_ -is [string]) { $_ } elseif ($_.id) { [string]$_.id }
})
} elseif ($null -ne $json.models) {
$ids = @($json.models | ForEach-Object {
if ($_ -is [string]) { $_ }
elseif ($_.id) { [string]$_.id }
elseif ($_.name) { [string]$_.name }
})
}
$ids = @($ids | Where-Object { $_ } | Sort-Object -Unique)
if ($ids.Count -eq 0) { throw "API responded successfully, but no model IDs were found in data[].id or models[]." }
return $ids
}
finally { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
}
}
# AgentRouter exposes its full model list (with IDs and supported endpoints) at a
# public, no-auth JSON endpoint behind the /pricing page. Unlike /v1/models and
# /api/models, this one is NOT client-gated (no 401). Returns data[].model_name
# and data[].supported_endpoint_types (e.g. ["anthropic","openai"]).
function Get-AgentRouterPricingModels([string]$Url) {
Invoke-Spinner "Fetching model list from $Url" {
$tmp = [IO.Path]::GetTempFileName()
try {
$curlArgs = @(
"-sS", "--fail-with-body",
"--connect-timeout", "15",
"--max-time", "45",
"-H", "Accept: application/json",
"-o", $tmp,
"-w", "%{http_code}",
$Url
)
$status = & $script:CurlBin @curlArgs
$exit = $LASTEXITCODE
$body = [IO.File]::ReadAllText($tmp, [Text.Encoding]::UTF8)
if ($exit -ne 0 -or $status -notmatch "^2") { throw "Request failed. HTTP $status`n$(Truncate-Text $body)" }
if ([string]::IsNullOrWhiteSpace($body)) { throw "Request succeeded (HTTP $status) but the response body was empty." }
$json = Repair-JsonEmptyKeys $body | ConvertFrom-Json
if (-not $json.success) { throw "Pricing API returned success=false.`n$(Truncate-Text $body)" }
if ($null -eq $json.data) { throw "Pricing API returned no data." }
return @($json.data)
}
finally { Remove-Item $tmp -Force -ErrorAction SilentlyContinue }
}
}
# ---------- config writers ----------
function Backup-File([string]$Path) {
if (Test-Path $Path) {
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$ticks = ([DateTime]::UtcNow.Ticks % 10000000).ToString("0000000")
$backup = "$Path.backup-$stamp-$ticks"
Copy-Item $Path $backup -Force
return $backup
}
return $null
}
function Ensure-Parent([string]$Path) {
$dir = Split-Path $Path -Parent
if (!(Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
}
function Load-JsonObject([string]$Path) {
if (!(Test-Path $Path)) { return [PSCustomObject]@{} }
$raw = Get-Content $Path -Raw
if ([string]::IsNullOrWhiteSpace($raw)) { return [PSCustomObject]@{} }
try { return $raw | ConvertFrom-Json }
catch {
throw "Cannot safely edit $Path because it is not strict JSON. If it is JSONC with comments, back it up and convert it to JSON first."
}
}
function Set-Prop($Object, [string]$Name, $Value) {
if ($null -eq $Object.PSObject.Properties[$Name]) {
$Object | Add-Member -NotePropertyName $Name -NotePropertyValue $Value
} else { $Object.$Name = $Value }
}
function Save-Json($Object, [string]$Path) {
Ensure-Parent $Path
# BOM-less UTF-8 is required: the Claude Desktop app's JSON.parse rejects files
# that start with a BOM (PowerShell 5.1's Set-Content -Encoding UTF8 adds one).
$json = $Object | ConvertTo-Json -Depth 100
[IO.File]::WriteAllText($Path, $json, (New-Object Text.UTF8Encoding($false)))
}
function Invoke-HermesModelSetup {
$hermes = Get-Command hermes -ErrorAction SilentlyContinue
if ($null -eq $hermes) {
Write-Host "Hermes is not installed. Install Hermes first, then rerun this option." -ForegroundColor Yellow
Pause-Screen
return
}
Write-Host "Launching Hermes model setup. Complete prompts manually." -ForegroundColor Cyan
& $hermes.Source model
if ($LASTEXITCODE -ne 0) {
Write-Host "Hermes model setup exited with code $LASTEXITCODE." -ForegroundColor Yellow
}
Pause-Screen
}
function Configure-Claude([string]$BaseUrl, [string]$ApiKey, [string]$Model) {
$claudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
$path = Join-Path $claudeDir "settings.json"
$backup = Backup-File $path
$cfg = Load-JsonObject $path
if ($null -eq $cfg.PSObject.Properties["env"]) { Set-Prop $cfg "env" ([PSCustomObject]@{}) }
Set-Prop $cfg.env "ANTHROPIC_BASE_URL" (Normalize-BaseUrl $BaseUrl)
Set-Prop $cfg.env "ANTHROPIC_AUTH_TOKEN" $ApiKey
Set-Prop $cfg.env "ANTHROPIC_MODEL" $Model
Set-Prop $cfg "model" $Model
Save-Json $cfg $path
return @{ Path=$path; Backup=$backup }
}
# The Claude Desktop Electron app runs in "3P" mode and reads its gateway
# settings from a managed config file in the configLibrary: the active entry is
# the JSON file named by configLibrary/_meta.json -> appliedId. Its schema:
# inferenceProvider = "gateway"
# inferenceGatewayBaseUrl = <base URL>
# inferenceGatewayApiKey = <api key>
# inferenceGatewayAuthScheme = "x-api-key" | "bearer" | "sso"
# inferenceModels = [ "model-id", ... ]
# We rewrite that entry (backed up first). The app picks it up on next launch.
# Locate the Claude Desktop config root per platform. Windows uses the 3P-mode
# configLibrary under LOCALAPPDATA; macOS and Linux use the app's config dir,
# preferring the 3P-mode "Claude-3p" folder when present (macOS apps historically
# wrote under "Claude").
function Get-ClaudeDesktopConfigDir {
if ($script:IsWindows) {
return Join-Path $env:LOCALAPPDATA "Claude-3p"
}
if ($script:IsMacOS) {
return Join-Path $HOME "Library/Application Support/Claude"
}
$base = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $HOME ".config" }
$c3p = Join-Path $base "Claude-3p"
if (Test-Path $c3p) { return $c3p }
return Join-Path $base "Claude"
}
function Configure-ClaudeDesktop([string]$BaseUrl, [string]$ApiKey, [string]$Model, [string]$AuthScheme) {
$dir = Get-ClaudeDesktopConfigDir
$libraryDir = Join-Path $dir "configLibrary"
$metaPath = Join-Path $libraryDir "_meta.json"
if (!(Test-Path $metaPath)) {
throw "Claude Desktop configLibrary not found at $metaPath. Install and launch the Claude Desktop app once so it initializes its config."
}
$meta = Load-JsonObject $metaPath
$appliedId = [string]$meta.appliedId
if ([string]::IsNullOrWhiteSpace($appliedId)) {
throw "No appliedId in $metaPath. Open the Claude Desktop app once so it writes its active config entry."
}
$cfgPath = Join-Path $libraryDir "$appliedId.json"
$backup = Backup-File $cfgPath
$cfg = Load-JsonObject $cfgPath
$scheme = if ($AuthScheme) { $AuthScheme } else { "x-api-key" }
Set-Prop $cfg "inferenceProvider" "gateway"
Set-Prop $cfg "inferenceGatewayBaseUrl" (Normalize-BaseUrl $BaseUrl)
Set-Prop $cfg "inferenceGatewayApiKey" $ApiKey
Set-Prop $cfg "inferenceGatewayAuthScheme" $scheme
Set-Prop $cfg "inferenceModels" @($Model)
Save-Json $cfg $cfgPath
return @{ Path=$cfgPath; Backup=$backup }
}
function Configure-OpenCode([string]$BaseUrl, [string]$ApiKey, [string]$Model, [string]$ProviderKey, [string]$ProviderName, [string]$NpmPackage) {
if ([string]::IsNullOrWhiteSpace($ProviderKey)) { throw "OpenCode provider key is empty; preset is missing 'opencode.providerKey'." }
if ([string]::IsNullOrWhiteSpace($NpmPackage)) { throw "OpenCode npm package is empty; preset is missing 'opencode.npmPackage'." }
$path = Join-Path $HOME ".config/opencode/opencode.json"
$backup = Backup-File $path
$cfg = Load-JsonObject $path
Set-Prop $cfg '$schema' "https://opencode.ai/config.json"
if ($null -eq $cfg.PSObject.Properties["provider"]) { Set-Prop $cfg "provider" ([PSCustomObject]@{}) }
$modelObj = [PSCustomObject]@{}
Set-Prop $modelObj $Model ([PSCustomObject]@{ name = $Model })
$provider = [PSCustomObject]@{
npm = $NpmPackage
name = $ProviderName
options = [PSCustomObject]@{ baseURL = (Normalize-BaseUrl $BaseUrl); apiKey = $ApiKey }
models = $modelObj
}
Set-Prop $cfg.provider $ProviderKey $provider
Set-Prop $cfg "model" ("$ProviderKey/" + $Model)
Save-Json $cfg $path
return @{ Path=$path; Backup=$backup }
}
# Set a document-ROOT key. Root keys must precede the first [table] header,
# otherwise TOML parses them as members of that table (e.g. windows.model).
# We split the text at the first table header, edit only the root portion, and
# strip any stray copy of this key from inside the tables (self-heals configs
# an earlier version may have mis-written).
function Set-TomlValue([string]$Text, [string]$Key, [string]$Value) {
$escaped = $Value -replace '\\', '\\\\' -replace '"', '\\"'
$line = '{0} = "{1}"' -f $Key, $escaped
$pattern = "(?m)^\s*" + [regex]::Escape($Key) + "\s*=.*$"
$firstTable = [regex]::Match($Text, '(?m)^[ \t]*\[')
if ($firstTable.Success) {
$head = $Text.Substring(0, $firstTable.Index)
$tail = $Text.Substring($firstTable.Index)
} else {
$head = $Text
$tail = ""
}
# Remove any misplaced copy of this key from within the tables.
$tail = [regex]::Replace($tail, "(?m)^[ \t]*" + [regex]::Escape($Key) + "[ \t]*=.*\r?\n?", "")
if ($head -match $pattern) {
$head = [regex]::Replace($head, $pattern, $line, 1)
} else {
if ($head -and !$head.EndsWith("`n")) { $head += "`r`n" }
$head += $line + "`r`n"
}
return $head + $tail
}
# Same root-placement logic as Set-TomlValue, but writes the value verbatim
# (no quotes) for bare TOML values like booleans/numbers.
function Set-TomlBareValue([string]$Text, [string]$Key, [string]$Value) {
$line = '{0} = {1}' -f $Key, $Value
$pattern = "(?m)^\s*" + [regex]::Escape($Key) + "\s*=.*$"
$firstTable = [regex]::Match($Text, '(?m)^[ \t]*\[')
if ($firstTable.Success) {
$head = $Text.Substring(0, $firstTable.Index)
$tail = $Text.Substring($firstTable.Index)
} else {
$head = $Text
$tail = ""
}
$tail = [regex]::Replace($tail, "(?m)^[ \t]*" + [regex]::Escape($Key) + "[ \t]*=.*\r?\n?", "")
if ($head -match $pattern) {
$head = [regex]::Replace($head, $pattern, $line, 1)
} else {
if ($head -and !$head.EndsWith("`n")) { $head += "`r`n" }
$head += $line + "`r`n"
}
return $head + $tail
}
# Set a key INSIDE the [shell_environment_policy.set] table (not root). Codex
# exposes these vars to shells it spawns for tools. If the table is missing we
# append it; if the key exists there we replace it in place.
function Set-TomlEnvPolicyValue([string]$Text, [string]$Key, [string]$Value) {
$escaped = $Value -replace '\\', '\\\\' -replace '"', '\\"'
$line = '{0} = "{1}"' -f $Key, $escaped
# Locate the [shell_environment_policy.set] table body (up to the next header).
$tablePattern = "(?ms)^([ \t]*\[shell_environment_policy\.set\][ \t]*\r?\n)(.*?)(?=^\s*\[|\z)"
$m = [regex]::Match($Text, $tablePattern)
if ($m.Success) {
$header = $m.Groups[1].Value
$body = $m.Groups[2].Value
$keyPattern = "(?m)^[ \t]*" + [regex]::Escape($Key) + "[ \t]*=.*$"
if ($body -match $keyPattern) {
$body = [regex]::Replace($body, $keyPattern, $line, 1)
} else {
if ($body -and !$body.EndsWith("`n")) { $body += "`r`n" }
$body += $line + "`r`n"
}
return $Text.Substring(0, $m.Index) + $header + $body + $Text.Substring($m.Index + $m.Length)
}
# Table absent: append a fresh one at end of file.
if ($Text -and !$Text.EndsWith("`n")) { $Text += "`r`n" }
return $Text + "`r`n[shell_environment_policy.set]`r`n" + $line + "`r`n"
}
function Configure-Codex([string]$BaseUrl, [string]$ApiKey, [string]$Model, [string]$ProviderKey, [string]$ProviderName) {
$dir = Join-Path $HOME ".codex"
$authPath = Join-Path $dir "auth.json"
$configPath = Join-Path $dir "config.toml"
$authBackup = Backup-File $authPath
$configBackup = Backup-File $configPath
# The Codex desktop app gates on auth.json's auth_mode: while it's "chatgpt"
# the app forces its built-in ChatGPT provider and ignores model_provider in
# config.toml entirely. Switch to "apikey" and write BOTH key names the app
# and CLI have used (OPEN_API_KEY, OPENAI_API_KEY).
$auth = Load-JsonObject $authPath
Set-Prop $auth "auth_mode" "apikey"
Set-Prop $auth "OPEN_API_KEY" $ApiKey
Set-Prop $auth "OPENAI_API_KEY" $ApiKey
Save-Json $auth $authPath
# Codex validates config.toml as all-or-nothing: ONE unsupported value makes
# it discard the whole file and silently fall back to ChatGPT defaults. So a
# built-in provider ID (openai) or a stale wire_api value breaks everything.
$provider = if ($ProviderKey -and $ProviderKey -ne "openai") { $ProviderKey } else { "custom" }
$envKey = ($provider.ToUpper() -replace '[^A-Z0-9]', '_') + "_API_KEY"
$toml = if (Test-Path $configPath) { Get-Content $configPath -Raw } else { "" }
$toml = Set-TomlValue $toml "model_provider" $provider
$toml = Set-TomlValue $toml "model" $Model
$toml = Set-TomlValue $toml "preferred_auth_method" "apikey"
# bare (non-quoted) root key; Set-TomlValue only writes quoted strings, so
# handle the boolean here but with the same root-vs-table placement rules.
$toml = Set-TomlBareValue $toml "disable_response_storage" "true"
$sectionPattern = "(?ms)^\s*\[model_providers\." + [regex]::Escape($provider) + "\]\s*.*?(?=^\s*\[|\z)"
$section = @(
"[model_providers.$provider]"
"name = `"$ProviderName`""
"base_url = `"$(Normalize-BaseUrl $BaseUrl)`""
# Do NOT write wire_api: Codex defaults to the Responses API, and pinning
# it (chat/responses) has caused config rejection or 404s per gateway.
"env_key = `"$envKey`""
) -join "`r`n"
$section += "`r`n"
if ($toml -match $sectionPattern) { $toml = [regex]::Replace($toml, $sectionPattern, $section, 1) }
else {
if ($toml -and !$toml.EndsWith("`n")) { $toml += "`r`n" }
$toml += "`r`n$section"
}
# Keep the key in [shell_environment_policy.set] too, so shells Codex spawns
# for tools inherit it.
$toml = Set-TomlEnvPolicyValue $toml $envKey $ApiKey
Ensure-Parent $configPath
[IO.File]::WriteAllText($configPath, $toml, (New-Object Text.UTF8Encoding($false)))
# env_key is resolved against the REAL process environment at Codex startup,
# not the config's shell policy block. Persist a User env var so the provider
# can find the key. (Takes effect only after the app is fully restarted.)
# Windows persists via the registry; Linux/macOS append an export to the
# user's shell rc (detected by an existing config file) since there is no
# equivalent user-wide registry.
if ($script:IsWindows) {
[Environment]::SetEnvironmentVariable($envKey, $ApiKey, "User")
[Environment]::SetEnvironmentVariable($envKey, $ApiKey, "Process")
} else {
$rcFile = @("$HOME/.bashrc", "$HOME/.zshrc", "$HOME/.profile") | Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $rcFile) { $rcFile = "$HOME/.profile" }
$exportLine = "export $envKey=`"$ApiKey`""
$rcText = if (Test-Path $rcFile) { Get-Content $rcFile -Raw } else { "" }
if ($rcText -notmatch [regex]::Escape($envKey)) {
if ($rcText -and -not $rcText.EndsWith("`n")) { $rcText += "`n" }
[IO.File]::AppendAllText($rcFile, "`n# Added by AI Config Manager`n$exportLine`n", (New-Object Text.UTF8Encoding($false)))
}
Write-Host " Persisted API key in $rcFile (restart your shell or run: source $rcFile)" -ForegroundColor DarkGray
}
return @(
@{ Path=$authPath; Backup=$authBackup }
@{ Path=$configPath; Backup=$configBackup }
)
}
# Merge a live-fetched list with a preset's curated fallback (deduped, sorted).
# Used so a gateway always shows its known-good models even when the live list
# is partial, and so a failed live fetch degrades to the curated list.
# NOTE: `return ,@(...)` — the comma protects the empty-array case, which
# PowerShell otherwise unrolls to $null on its way out of the function.
function Merge-Models {
param($Live, $Curated)
return ,@( @($Live) + @($Curated) | Where-Object { $_ } | Sort-Object -Unique )
}
# Fetch the live model list for a preset, returning per-client lists.
# Presets with modelsApiUrl (AgentRouter) hit the public pricing JSON and split
# models by supported_endpoint_types; all other presets (EuroModels, Custom)
# share one OpenAI-compatible /v1/models endpoint, so the same list is offered
# to both clients. The claude block's baseUrl is for the Anthropic-compatible
# root and has no model-list endpoint of its own, so we fetch from the opencode
# (OpenAI-compatible) base URL instead.
function Fetch-PresetModels {
param($Preset, [string]$ApiKey)
if ($Preset.modelsApiUrl) {
$pricing = Get-AgentRouterPricingModels $Preset.modelsApiUrl
$claude = @($pricing | Where-Object { $_.supported_endpoint_types -contains "anthropic" } | ForEach-Object { [string]$_.model_name })
$opencode = @($pricing | Where-Object { $_.supported_endpoint_types -contains "openai" } | ForEach-Object { [string]$_.model_name })
return [PSCustomObject]@{ claude = $claude; opencode = $opencode }
}
$list = Get-LiveModels $Preset.opencode.baseUrl $ApiKey
return [PSCustomObject]@{ claude = $list; opencode = $list }
}
# ---------- model picker ----------
function Pick-Model {
param([string[]]$Models, [bool]$CanRefresh, [string]$GatewayLabel, [string]$ClientLabel)
$opts = @($Models) + "[ Enter custom model ID ]"
if ($CanRefresh) { $opts += "[ Refresh model list ]" }
$opts += "[ Back ]"
$header = @("Gateway: $GatewayLabel", "Client: $ClientLabel", "Available: $($Models.Count)")
$idx = Show-Menu -Title "Select Model" -Options $opts -Header $header
if ($idx -eq -1) { return @{ Action="Cancel"; Model=$null } }
if ($idx -lt $Models.Count) { return @{ Action="Selected"; Model=$Models[$idx] } }
$choice = $opts[$idx]
if ($choice -match "custom") {
$m = (Read-Host "Enter exact model ID").Trim()
if ($m) { return @{ Action="Selected"; Model=$m } }
return @{ Action="Cancel"; Model=$null }
}
if ($choice -match "Refresh") { return @{ Action="Refresh"; Model=$null } }
return @{ Action="Back"; Model=$null }
}
# Loops the model menu (handling Refresh) until a model is chosen or the user backs out.
function Choose-Model {
param([string[]]$InitialModels, [bool]$CanRefresh, [string]$GatewayLabel, [string]$ClientLabel, $Preset, [string]$ApiKey, [string]$Client)
$models = $InitialModels
while ($true) {
$pick = Pick-Model $models $CanRefresh $GatewayLabel $ClientLabel
switch ($pick.Action) {
"Selected" { return $pick.Model }
"Refresh" {
try {
$fresh = Fetch-PresetModels $Preset $ApiKey
$models = Merge-Models $fresh.$Client $Preset.$Client.curatedModels
} catch {
Write-Host ""
Write-Host "Refresh failed: $($_.Exception.Message)" -ForegroundColor Red
Pause-Screen
}
continue
}
default { return $null } # Back / Cancel
}
}
}
# ---------- current config view ----------
function Show-Current {
Clear-Host
Write-Banner "Current Configuration"
$claudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
$cp = Join-Path $claudeDir "settings.json"
Write-Host " Claude Code: $cp" -ForegroundColor Gray
$c = $null
if (Test-Path $cp) {
try {
$c = Get-Content $cp -Raw | ConvertFrom-Json
Write-Host " Base URL: $($c.env.ANTHROPIC_BASE_URL)"
Write-Host " Model: $($c.model)"
Write-Host " API Key: $(Mask-Key ([string]$c.env.ANTHROPIC_AUTH_TOKEN))"
} catch { Write-Host " Could not parse config." -ForegroundColor Yellow }
} else { Write-Host " No config found." -ForegroundColor DarkGray }
# Claude Code also reads OS env vars; show what it actually inherits, and flag any divergence.
$osBase = $env:ANTHROPIC_BASE_URL
if ($osBase) {
$cfgBase = if ($null -eq $c) { "" } else { [string]$c.env.ANTHROPIC_BASE_URL }
$same = ($osBase -eq $cfgBase)
$osTag = if ($same) { "matches settings.json" } else { "DIFFERS from settings.json" }
$osColor = if ($same) { "DarkGray" } else { "Yellow" }
Write-Host " OS env: ANTHROPIC_BASE_URL=$osBase ($osTag)" -ForegroundColor $osColor
if ($env:ANTHROPIC_MODEL) { Write-Host " ANTHROPIC_MODEL=$($env:ANTHROPIC_MODEL)" -ForegroundColor DarkGray }
}
Write-Separator
$osVars = @("ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_MODEL", "OPENAI_API_KEY")
Write-Host " Windows environment variables" -ForegroundColor Gray
foreach ($name in $osVars) {
$value = [Environment]::GetEnvironmentVariable($name)
if ($value) { Write-Host " $name=$(if ($name -match 'KEY|TOKEN') { Mask-Key $value } else { $value })" }
}
Write-Separator
Write-Host " Claude Desktop: 3P gateway config" -ForegroundColor Gray
$cdDir = Get-ClaudeDesktopConfigDir
$cdMeta = Join-Path $cdDir "configLibrary/_meta.json"
if (Test-Path $cdMeta) {
try {
$cdM = Get-Content $cdMeta -Raw | ConvertFrom-Json
$cdId = [string]$cdM.appliedId
$cdCfgPath = Join-Path $cdDir "configLibrary/$cdId.json"
if ($cdId -and (Test-Path $cdCfgPath)) {
$cdCfg = Get-Content $cdCfgPath -Raw | ConvertFrom-Json
Write-Host " Config: $cdCfgPath"
Write-Host " Base URL: $($cdCfg.inferenceGatewayBaseUrl)"
Write-Host " Auth scheme: $($cdCfg.inferenceGatewayAuthScheme)"
Write-Host " API Key: $(Mask-Key ([string]$cdCfg.inferenceGatewayApiKey))"
$models = @($cdCfg.inferenceModels | Where-Object { $_ })
if ($models.Count -gt 0) { Write-Host " Models: $($models -join ', ')" }
} else {
Write-Host " No active config entry (appliedId missing or file absent)." -ForegroundColor DarkGray
}
} catch { Write-Host " Could not parse Claude Desktop config." -ForegroundColor Yellow }
} else {
Write-Host " No configLibrary found (Claude Desktop not installed or not launched)." -ForegroundColor DarkGray
}
Write-Separator
$op = Join-Path $HOME ".config/opencode/opencode.json"
Write-Host " OpenCode: $op" -ForegroundColor Gray
if (Test-Path $op) {
try {
$o = Get-Content $op -Raw | ConvertFrom-Json
$allProvs = @($o.provider.PSObject.Properties)
$prefix = ($o.model -split "/")[0]
$active = $allProvs | Where-Object { $_.Name -eq $prefix }
if ($active) {
Write-Host " Provider: $($active.Name) (active)"
Write-Host " Base URL: $($active.Value.options.baseURL)"
Write-Host " Model: $($o.model)"
Write-Host " API Key: $(Mask-Key ([string]$active.Value.options.apiKey))"
$others = @($allProvs | Where-Object { $_.Name -ne $prefix })
if ($others.Count -gt 0) {
$names = ($others | ForEach-Object { $_.Name }) -join ", "
Write-Host " Also configured (inactive): $names" -ForegroundColor DarkGray
}
} else {
Write-Host " Model: $($o.model)" -ForegroundColor Yellow
Write-Host " No provider matches model prefix '$prefix'." -ForegroundColor Yellow
}
} catch { Write-Host " Could not parse config." -ForegroundColor Yellow }
} else { Write-Host " No config found." -ForegroundColor DarkGray }
$codexDir = Join-Path $HOME ".codex"
$codexAuth = Join-Path $codexDir "auth.json"
$codexConfig = Join-Path $codexDir "config.toml"
Write-Separator
Write-Host " Codex: $codexDir" -ForegroundColor Gray
if (Test-Path $codexAuth) {
try {
$ca = Get-Content $codexAuth -Raw | ConvertFrom-Json
$key = $ca.OPENAI_API_KEY
if (!$key -and $ca.tokens) { $key = $ca.tokens.access_token }
Write-Host " auth.json API Key: $(Mask-Key ([string]$key))"
} catch { Write-Host " Could not parse auth.json." -ForegroundColor Yellow }
} else { Write-Host " No auth.json found." -ForegroundColor DarkGray }
if (Test-Path $codexConfig) {
Write-Host " config.toml: $codexConfig"
$toml = Get-Content $codexConfig -Raw
$modelLine = [regex]::Match($toml, '(?m)^\s*model\s*=\s*"([^"]+)"').Groups[1].Value
$providerLine = [regex]::Match($toml, '(?m)^\s*model_provider\s*=\s*"([^"]+)"').Groups[1].Value
if ($modelLine) { Write-Host " Model: $modelLine" }
if ($providerLine) { Write-Host " Provider: $providerLine" }
} else { Write-Host " No config.toml found." -ForegroundColor DarkGray }
$hermesCandidates = @(
(Join-Path $HOME ".hermes/config.toml"),
(Join-Path $HOME ".config/hermes/config.toml"),
(Join-Path $HOME ".config/hermes/config.json")
) | Where-Object { Test-Path $_ }
if ($hermesCandidates.Count -gt 0) {
Write-Separator
Write-Host " Hermes config: $($hermesCandidates -join ', ')" -ForegroundColor DarkGray
}
Pause-Screen
}
# ---------- backup restore ----------
# Map a tool name to the config file path(s) the writers touch. Used by
# Restore-Backup to find which *.backup-* files belong to which tool.
function Get-ToolConfigPaths([string]$Tool) {
$claudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
switch ($Tool) {
"Claude Code" { return ,(Join-Path $claudeDir "settings.json") }
"OpenCode" { return ,(Join-Path $HOME ".config/opencode/opencode.json") }
"Codex" { Write-Output (Join-Path $HOME ".codex/auth.json"); return (Join-Path $HOME ".codex/config.toml") }
"Claude Desktop" {
$dir = Get-ClaudeDesktopConfigDir
$metaPath = Join-Path $dir "configLibrary/_meta.json"
if (Test-Path $metaPath) {
try {
$appliedId = [string]((Get-Content $metaPath -Raw | ConvertFrom-Json).appliedId)
if ($appliedId) { return ,(Join-Path $dir "configLibrary/$appliedId.json") }
} catch { }
}
return @()
}
default { return @() }
}
}
# Given a target config path, return the newest matching "*.backup-*" file.
function Get-LatestBackup([string]$TargetPath) {
$pattern = "$TargetPath.backup-*"
$backups = @(Get-ChildItem -Path $pattern -File -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match "^[^\\/]+\.backup-\d{8}-\d{6}-\d+$" } |
Sort-Object LastWriteTime -Descending)
if ($backups.Count -eq 0) { return $null }
return $backups[0]
}
function Restore-Backup {
$toolIdx = Show-Menu -Title "Restore Last Backup" -Options @(
"Claude Code",
"OpenCode",
"Codex",
"Claude Desktop",
"Back"
)
if ($toolIdx -eq -1 -or $toolIdx -eq 4) { return }
$tool = @("Claude Code", "OpenCode", "Codex", "Claude Desktop")[$toolIdx]
$paths = @(Get-ToolConfigPaths $tool)
if ($paths.Count -eq 0) {
Write-Host ""
Write-Host "No config path known for $tool (Claude Desktop configLibrary not found)." -ForegroundColor Yellow
Pause-Screen
return
}
# Collect the newest backup across all of this tool's config files.
$latest = $null
$latestTarget = $null
foreach ($p in $paths) {
$b = Get-LatestBackup $p
if ($b -and ($null -eq $latest -or $b.LastWriteTime -gt $latest.LastWriteTime)) {
$latest = $b
$latestTarget = $p
}
}
if ($null -eq $latest) {
Write-Host ""
Write-Host "No backups found for $tool." -ForegroundColor Yellow
Write-Host "Configurations are backed up automatically before every write."
Pause-Screen
return
}
Clear-Host
Write-Banner "Restore Backup - $tool"
Write-Host " Backup: $($latest.FullName)" -ForegroundColor Gray
Write-Host " Target: $latestTarget" -ForegroundColor Gray
Write-Host " Dated: $($latest.LastWriteTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor DarkGray
Write-Host ""
$confirm = Show-Menu -Title "Confirm restore" -Options @(
"Restore this backup",
"Cancel"
)
if ($confirm -ne 0) { return }
try {
# Back up the current file first so the restore itself is reversible.
$currentBackup = Backup-File $latestTarget
Copy-Item $latest.FullName $latestTarget -Force
Write-Host ""
Write-Host "[OK] Restored $tool" -ForegroundColor Green
Write-Host " Target: $latestTarget"
if ($currentBackup) { Write-Host " Prior state backed up: $currentBackup" -ForegroundColor DarkGray }
Write-Host ""
Write-Host "Restart the tool for changes to take effect." -ForegroundColor Cyan
} catch {
Write-Host ""
Write-Host "Restore failed: $($_.Exception.Message)" -ForegroundColor Red
}
Pause-Screen
}
# ---------- presets ----------
# Validate one preset's structure so a malformed entry fails with a useful
# message instead of null-dereferencing downstream. Returns nothing; throws on
# the first problem.
function Assert-PresetValid($Preset) {
$label = if ($Preset.label) { [string]$Preset.label } else { "<untitled>" }
$base = "Preset '$label' is invalid:"
if (-not $Preset.id) { throw "$base missing 'id'." }
foreach ($client in @("claude", "opencode")) {
$block = $Preset.PSObject.Properties[$client]
if ($null -eq $block -or $null -eq $block.Value) { throw "$base missing '$client' block." }
if ([string]::IsNullOrWhiteSpace([string]$block.Value.baseUrl)) { throw "$base '$client.baseUrl' is empty." }
}
if ([string]::IsNullOrWhiteSpace([string]$Preset.opencode.providerKey)) { throw "$base 'opencode.providerKey' is empty." }
if ([string]::IsNullOrWhiteSpace([string]$Preset.opencode.npmPackage)) { throw "$base 'opencode.npmPackage' is empty." }
}
function Load-Presets {
$path = Join-Path $PSScriptRoot "AI-Config-Presets.json"
if (!(Test-Path $path)) {
Write-Host "Preset file not found: $path" -ForegroundColor Red
exit 1
}
try { $presets = @((Get-Content $path -Raw | ConvertFrom-Json).presets) }
catch {
Write-Host "Preset file is invalid JSON: $path" -ForegroundColor Red
exit 1
}
foreach ($p in $presets) { Assert-PresetValid $p }
return $presets
}
function New-CustomPreset([string]$Url) {
[PSCustomObject]@{
id = "custom"
label = "Custom"
dashboard = $null
fetchModels = $true
claude = [PSCustomObject]@{ baseUrl = $Url; curatedModels = @() }
opencode = [PSCustomObject]@{ baseUrl = $Url; providerKey = "custom"; providerName = "Custom"; npmPackage = "@ai-sdk/openai-compatible"; curatedModels = @() }
}
}
# ---------- self-test ----------
# Offline checks for the non-trivial helpers (scroll math, TOML/JSON writers,
# model merging, URL handling, backup, validation). Run without a TTY:
# powershell -File .\AI-Config-Manager.ps1 -SelfTest
if ($SelfTest) {
function Assert-Equal($a, $b, $msg) {