# SmithAPI One-Click Client Setup Script (Windows PowerShell 5.1 & 7+) # Usage: # curl.exe --ssl-no-revoke -fsSL https://smithapi.com/setup.ps1 | Out-String | iex # Set-Item Env:SMITHAPI_KEY 'sk-...'; curl.exe --ssl-no-revoke -fsSL https://smithapi.com/setup.ps1 | Out-String | iex param( [string]$Key = "", [string]$BaseUrl = "", [string]$Only = "", [switch]$All, [switch]$Yes, [switch]$DryRun, [switch]$SkipVerify, [switch]$OpenCcSwitch, [switch]$NoColor, [switch]$Uninstall, [switch]$Help ) $ErrorActionPreference = "Stop" try { [Console]::InputEncoding = [System.Text.Encoding]::UTF8 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $OutputEncoding = [System.Text.Encoding]::UTF8 } catch {} try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch {} try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 12288 } catch {} $I18nB64 = "eyJiYW5uZXJfdGl0bGUiOiIgIOKaoSBTbWl0aEFQSSDkuIDplK7lrqLmiLfnq6/phY3nva7lt6XlhbciLCJiYW5uZXJfZ3ciOiIgIOe9keWFs+WcsOWdgDogezB9IiwiYmFubmVyX21vZGVfYXBwbHkiOiIgIOi/kOihjOaooeW8jzog6Ieq5Yqo5o6i5rWLIMK3IOaXoOaNn+WQiOW5tu+8iOaUueWKqOWJjeiHquWKqOWkh+S7vSAuYmFrLXNtaXRoYXBpLSrvvIkiLCJiYW5uZXJfbW9kZV9kcnkiOiIgIOi/kOihjOaooeW8jzog6aKE5ryU5qih5byPIMK3IOWPquivu+mihOiniOS4jeS/ruaUueejgeebmOaWh+S7tiIsImJhbm5lcl9tb2RlX3VuIjoiICDov5DooYzmqKHlvI86IOWNuOi9vea4heeQhiDCtyDku4Xnp7vpmaQgU21pdGhBUEkg5omY566h6YWN572uIiwic3RlcDFfaGVhZCI6IlsxLzNdIOWvhumSpeS4jue9keWFs+ajgOa1iyIsInN0ZXAyX2hlYWQiOiJbMi8zXSDmnKzlnLDnjq/looPmjqLmtYvkuI7phY3nva4iLCJzdGVwM19oZWFkIjoiWzMvM10g5o+Q56S65LiO5b+r6YCf6aqM6K+BIiwidXNhZ2UiOiLnlKjms5U6IGN1cmwuZXhlIC0tc3NsLW5vLXJldm9rZSAtZnNTTCBodHRwczovL3NtaXRoYXBpLmNvbS9zZXR1cC5wczEgfCBPdXQtU3RyaW5nIHwgaWV4IiwiY2xpcF9hdXRvIjoiICBb4pyTXSDlt7Lku47liarotLTmnb/oh6rliqjor4bliKsgQVBJIEtleTogezB9Iiwia2V5X3Byb21wdCI6IiAg6K+357KY6LS05L2g55qEIFNtaXRoQVBJIEtleSAoc2stLi4uKSIsIm5vX2tleSI6IuacquaPkOS+myBBUEkgS2V544CC6K+35YWI5aSN5Yi2IHNrLS4uLiDlr4bpkqXlkI7ph43ot5HvvIzmiJbkvKDlhaXlj4LmlbAgLUtleSBzay0uLi4iLCJiYWRfa2V5IjoiQVBJIEtleSDmoLzlvI/ml6DmlYggKOW6lOS7pSBzay0g5byA5aS0KSIsImJhZF9rZXlfY29uZmlybSI6IiAgWyFdIOi+k+WFpeeahOWvhumSpeagvOW8j+S4jeWDj+agh+WHhiBzay0uLi4gS2V5ICh7MH0p77yM5LuN6KaB57un57ut5ZCXPyBbeS9OXSIsImNhbmNlbGxlZCI6IuW3suWPlua2iOOAgiIsImF1dGhfZmFpbCI6IiAgWyFdIOe9keWFs+agoemqjOWksei0pTogQVBJIEtleSDml6DmlYjmiJbmnKrlkK/nlKggKEhUVFAgezB9KSIsImZvcmNlX2NvbmZpcm0iOiIgIOaYr+WQpuS7jeimgeW8uuWItuWGmeWFpeacrOWcsOmFjee9rj8gW3kvTl0iLCJwcm9iZV9za2lwIjoiICBbIV0g5Zyo57q/5o6i5rWLIC92MS9tb2RlbHMg6Lez6L+HICh7MH0p77yM5bCG5L2/55So5qCH5YeG6buY6K6k5qih5Z6L5YiX6KGo44CCIiwiY2ZnX2hlYWQiOiIgIFvinJNdIOWvhumSpeagoemqjDogezB9ICB8ICDnvZHlhbM6IHsxfSIsImJhbF9oZWFkIjoiICBb4pyTXSDlvZPliY3lj6/nlKjpop3luqY6IHswfSIsIm1vZF9oZWFkIjoiICBb4pyTXSDmqKHlnovliJfooaggKHswfSDkuKopOiB7MX0iLCJ1bmluc3RhbGxfaGVhZCI6IiAgW+KGul0g5q2j5Zyo5riF55CGIFNtaXRoQVBJIOmFjee9riAoezB9KS4uLiIsImRvbmVfbGlzdCI6IiAg5bey5aSE55CG55qE6YWN572u55uu5qCHOiDlhbEgezB9IOmhuSIsInNraXBwZWRfbGlzdCI6IiAgW+KXi10g5pyq5a6J6KOF5bey6Lez6L+HICh7MH0g6aG5KTogezF9ICAo5LygIC1BbGwg5Y+v5by65Yi25YWo6YOo55Sf5oiQKSIsIm5vbmVfZm91bmQiOiIgIFvil4tdIOacquWPkeeOsOmcgOimgeS/ruaUueeahOebruagh+eOr+WigyAo5Y+v5LygIC1BbGwg5by65Yi25YaZ5YWl5omA5pyJ5Y+X5pSv5oyB6YWN572uKeOAgiIsIndhcm5pbmdzX2hlYWQiOiIgIOazqOaEj+S6i+mhuToiLCJndWlfaGVhZCI6IiAg4pWt4pSA4pSAIOahjOmdoi9JREUg5a6i5oi356uv5b+r5o235aGr5YaZ5Y+C5pWwIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgCIsImd1aV90YWlsIjoiICDilbDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAiLCJndWlfZm91bmQiOiIgIOKUgiDmo4DmtYvliLDlrqLmiLfnq686IHswfSIsImd1aV91cmwiOiIgIOKUgiBPcGVuQUkg5YW85a65IEJhc2UgVVJMOiB7MH0vdjEgKENoZXJyeSBTdHVkaW8g5aGrIHswfSkiLCJndWlfa2V5IjoiICDilIIgQVBJIEtleTogezB9ICjlt7LlnKjliarotLTmnb/miJbmjqfliLblj7DlpI3liLYpIiwibmV4dF9oZWFkIjoiICDkuIvkuIDmraU6IiwibmV4dF8xIjoiICAgIHswfS4g546v5aKD5Y+Y6YeP5bey5YaZ5YWlIFdpbmRvd3Mg55So5oi35Y+Y6YeP5LiO6YWN572u5paH5Lu277yM6YeN5byA57uI56uv5ZCO6Ieq5Yqo55Sf5pWIIiwibmV4dF8yIjoiICAgIHswfS4g6aqM6K+BIENsYXVkZSBDb2RlOiBjbGF1ZGUgLXAgXCLlm57lpI0gT0tcIiIsIm5leHRfMyI6IiAgICB7MH0uIOmqjOivgSBEU0g6IGRzaCB0dWkgLS1wYXRjaCAkZW52OlVTRVJQUk9GSUxFXFwuZHNoXFxwYXRjaF9zbWl0aGFwaS55YW1sIiwibmV4dF93YiI6IiAgICB7MH0uIOmHjeWQryBXb3JrQnVkZHkg5qGM6Z2i56uv5Y2z5Y+v5Zyo5qih5Z6L5YiX6KGo55yL5YiwIFNtaXRoQVBJIMK3IOaooeWeiyIsIm5leHRfdW4iOiIgICAg5aaC6ZyA5Zue5rua5riF55CGOiDph43mlrDov5DooYzohJrmnKzlubbpmYTliqAgLVVuaW5zdGFsbCIsIndhcm5fYW50X2tleSI6IuW3suenu+mZpCB7MH0g5Lit5Yay56qB55qEIGVudi5BTlRIUk9QSUNfQVBJX0tFWSIsIndhcm5fb2xkX2FudCI6IuajgOa1i+WIsOeUqOaIt+eOr+Wig+WPmOmHj+S4reWtmOWcqOaXp+eahCBBTlRIUk9QSUNfQVBJX0tFWe+8jOW7uuiurua4heeQhuS7peWFjeS4jiBDbGF1ZGUgQ29kZSDnmoQgQU5USFJPUElDX0FVVEhfVE9LRU4g5Yay56qBIiwiY2NfbGF1bmNoZWQiOiLlt7LpgJrov4cgY2Nzd2l0Y2g6Ly8g5Y2P6K6u6Kem5Y+R5a+85YWlICjlr4bpkqXmnKrmiZPljbDliLDnu4jnq68pIiwiY2NfaGludCI6IuW3suajgOa1i+WIsOWuieijhe+8m+WPr+aJk+W8gCB7MH0vcXVpY2stc2V0dXAg5LiA6ZSu54K55Ye744CM5a+85YWlIENDIFN3aXRjaOOAjSIsImNjX2RyeSI6IuajgOa1i+WIsCBDQyBTd2l0Y2ggKGRyeS1ydW4g6Lez6L+H5ouJ6LW35Y2P6K6uKSIsImNsZWFuZWQiOiLlt7LmuIXnkIYgezB9IiwiY2xlYW5lZF93YiI6IuW3sua4heeQhiB7MH0gKOS/neeVmSB7MX0g5p2h5Y6f5pyJ5qih5Z6LKSIsInVwZGF0ZWRfY2xhdWRlIjoiezB9ICjlt7Lkv53nlZnml6LmnIkgaG9va3Mv5o+S5Lu2KSIsInVwZGF0ZWRfZHNoIjoi5Yet5o2uIHswfSArIHByb2ZpbGVzIFt7MX1dICsgezJ9IiwidXBkYXRlZF9lbnYiOiJXaW5kb3dzIOeUqOaIt+eOr+Wig+WPmOmHjyArIOmFjee9ruaWh+S7tiArIHswfSIsInVwZGF0ZWRfZ2VtaW5pIjoiezB9ICjmnKrmlLnliqggc2V0dGluZ3MuanNvbiBob29rcykiLCJ1cGRhdGVkX3diIjoiezB9ICjlt7LlhpnlhaUgezF9IOS4quaooeWei++8jOS/neeVmSB7Mn0g5p2h5Y6f5pyJKSIsIndhcm5fdW5rbm93bl9vbmx5IjoiLU9ubHkg5Lit5YyF5ZCr5pyq6K+G5Yir55qE55uu5qCHOiB7MH3vvIjlj6/pgIk6IHsxfe+8iSJ9" $I18nJson = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($I18nB64)) $I18nObj = $I18nJson | ConvertFrom-Json $Msg = @{} foreach ($p in $I18nObj.PSObject.Properties) { $Msg[$p.Name] = [string]$p.Value } function Get-Msg { param([string]$Name, [object[]]$ArgsList = @()) $tpl = $Msg[$Name] if (-not $tpl) { return $Name } if ($ArgsList.Count -gt 0) { return [string]::Format($tpl, $ArgsList) } return $tpl } if ($Help) { Write-Host "SmithAPI One-Click Setup (Windows PowerShell)" Write-Host (Get-Msg "usage") Write-Host "Parameters: -Key -BaseUrl -Only -All -Yes -DryRun -SkipVerify -OpenCcSwitch -NoColor -Uninstall" Write-Host "Targets: workbuddy, dsh, claude-code, codex, shell-env, gemini-cli, opencode, grok-cli, aider, continue, droid, openclaw, qwen-code, cc-switch" return } function Trim-Key { param([string]$Raw) if ([string]::IsNullOrWhiteSpace($Raw)) { return "" } $s = $Raw.Trim() if (($s.StartsWith('"') -and $s.EndsWith('"')) -or ($s.StartsWith("'") -and $s.EndsWith("'"))) { if ($s.Length -ge 2) { $s = $s.Substring(1, $s.Length - 2) } } return $s.Trim() } function Mask-Key { param([string]$K) if ([string]::IsNullOrEmpty($K) -or $K.Length -le 12) { return "***" } return $K.Substring(0, 7) + "...." + $K.Substring($K.Length - 4) } if ([string]::IsNullOrWhiteSpace($Key)) { if (-not [string]::IsNullOrWhiteSpace($env:SMITHAPI_KEY)) { $Key = $env:SMITHAPI_KEY } elseif (-not [string]::IsNullOrWhiteSpace($env:SMITHAPI_API_KEY)) { $Key = $env:SMITHAPI_API_KEY } } if ([string]::IsNullOrWhiteSpace($BaseUrl)) { if (-not [string]::IsNullOrWhiteSpace($env:SMITHAPI_BASE_URL)) { $BaseUrl = $env:SMITHAPI_BASE_URL } else { $BaseUrl = "https://api.smithapi.com" } } if ([string]::IsNullOrWhiteSpace($Only) -and -not [string]::IsNullOrWhiteSpace($env:SMITHAPI_ONLY)) { $Only = $env:SMITHAPI_ONLY } if (-not $All -and $env:SMITHAPI_ALL -eq "1") { $All = $true } if (-not $Yes -and $env:SMITHAPI_YES -eq "1") { $Yes = $true } if (-not $DryRun -and $env:SMITHAPI_DRY_RUN -eq "1") { $DryRun = $true } if (-not $SkipVerify -and $env:SMITHAPI_SKIP_VERIFY -eq "1") { $SkipVerify = $true } if (-not $OpenCcSwitch -and $env:SMITHAPI_OPEN_CCSWITCH -eq "1") { $OpenCcSwitch = $true } if (-not $Uninstall -and $env:SMITHAPI_UNINSTALL -eq "1") { $Uninstall = $true } $Key = Trim-Key $Key $BaseUrl = (Trim-Key $BaseUrl).TrimEnd("/") if ([string]::IsNullOrWhiteSpace($BaseUrl)) { $BaseUrl = "https://api.smithapi.com" } $SiteUrl = if ($BaseUrl.TrimEnd("/").ToLowerInvariant() -eq "https://api.smithapi.com") { "https://smithapi.com" } else { $BaseUrl } $KnownTargets = @( "claude-code", "codex", "dsh", "shell-env", "gemini-cli", "opencode", "grok-cli", "aider", "continue", "droid", "openclaw", "qwen-code", "workbuddy", "cc-switch" ) $KnownTargetSet = @{} foreach ($kt in $KnownTargets) { $KnownTargetSet[$kt] = $true } $TargetAliases = @{ "claude" = "claude-code" "gemini" = "gemini-cli" "grok" = "grok-cli" "qwen" = "qwen-code" "shell" = "shell-env" "env" = "shell-env" "wb" = "workbuddy" "ccswitch" = "cc-switch" "ccs" = "cc-switch" "factory" = "droid" "factory-droid" = "droid" } $OnlySet = @{} $UnknownOnly = New-Object System.Collections.Generic.List[string] if (-not [string]::IsNullOrWhiteSpace($Only)) { foreach ($part in ($Only -split ",")) { $p = $part.Trim().ToLowerInvariant() if ($p) { if ($TargetAliases.ContainsKey($p)) { $p = $TargetAliases[$p] } $OnlySet[$p] = $true if (-not $KnownTargetSet.ContainsKey($p) -and -not $UnknownOnly.Contains($p)) { $UnknownOnly.Add($p) } } } } $StartMark = "# >>> SmithAPI >>>" $EndMark = "# <<< SmithAPI <<<" $Timestamp = Get-Date -Format "yyyyMMdd-HHmmss" $Utf8NoBom = New-Object System.Text.UTF8Encoding($false) $UserHome = $env:USERPROFILE if ([string]::IsNullOrWhiteSpace($UserHome)) { $UserHome = $HOME } $DshHome = if (-not [string]::IsNullOrWhiteSpace($env:DSH_HOME)) { $env:DSH_HOME } else { Join-Path $UserHome ".dsh" } $WorkBuddyHome = if (-not [string]::IsNullOrWhiteSpace($env:WORKBUDDY_HOME)) { $env:WORKBUDDY_HOME.Trim() } else { Join-Path $UserHome ".workbuddy" } $AppDataDir = if (-not [string]::IsNullOrWhiteSpace($env:APPDATA)) { $env:APPDATA } else { Join-Path $UserHome "AppData\Roaming" } $LocalAppDataDir = if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) { $env:LOCALAPPDATA } else { Join-Path $UserHome "AppData\Local" } $UseColor = (-not $NoColor) -and [string]::IsNullOrEmpty($env:NO_COLOR) -and ($env:SMITHAPI_NO_COLOR -ne "1") -and ($env:TERM -ne "dumb") function Write-Tone { param([string]$Text, [string]$Color = "Gray") if ($UseColor) { Write-Host $Text -ForegroundColor $Color } else { Write-Host $Text } } Write-Host "" Write-Tone " +--------------------------------------------------------------" "Cyan" Write-Tone (Get-Msg "banner_title") "White" Write-Tone (Get-Msg "banner_gw" @($BaseUrl)) "Cyan" $modeText = if ($Uninstall) { Get-Msg "banner_mode_un" } elseif ($DryRun) { Get-Msg "banner_mode_dry" } else { Get-Msg "banner_mode_apply" } Write-Tone $modeText "Yellow" Write-Tone " +--------------------------------------------------------------" "Cyan" Write-Host "" Write-Tone (Get-Msg "step1_head") "Cyan" if (-not $Uninstall) { if ([string]::IsNullOrWhiteSpace($Key)) { $clipCandidate = "" try { $rawClip = Get-Clipboard -Format Text -Raw -ErrorAction SilentlyContinue if (-not $rawClip) { $rawClip = Get-Clipboard -ErrorAction SilentlyContinue } if ($rawClip -is [string]) { $trimmedClip = Trim-Key $rawClip if ($trimmedClip -notmatch "`n" -and $trimmedClip -match "^sk-[A-Za-z0-9._-]{12,}$") { $clipCandidate = $trimmedClip } } } catch {} if ($clipCandidate) { $maskedClip = Mask-Key $clipCandidate $Key = $clipCandidate Write-Tone (Get-Msg "clip_auto" @($maskedClip)) "Green" } elseif (-not $Yes) { $Key = Trim-Key (Read-Host (Get-Msg "key_prompt")) } } if ([string]::IsNullOrWhiteSpace($Key)) { Write-Error (Get-Msg "no_key") exit 1 } if ($Key -notmatch "^sk-[A-Za-z0-9._-]{8,}$") { if ($Yes) { Write-Error (Get-Msg "bad_key") exit 1 } $ans = Read-Host (Get-Msg "bad_key_confirm" @((Mask-Key $Key))) if ($ans -notmatch "^[Yy]$") { Write-Host (Get-Msg "cancelled") exit 1 } } } function Should-RunTarget { param([string]$Name, [bool]$Detected) if ($OnlySet.Count -gt 0) { return $OnlySet.ContainsKey($Name.ToLowerInvariant()) } if ($All) { return $true } if (-not $Detected) { [void]$SkippedTargets.Add($Name) } return $Detected } function Command-Exists { param([string]$Cmd) if (Get-Command $Cmd -ErrorAction SilentlyContinue) { return $true } $candidates = @( (Join-Path $UserHome ".local\bin\$Cmd.exe"), (Join-Path $AppDataDir "npm\$Cmd.cmd"), (Join-Path $AppDataDir "npm\$Cmd.ps1"), (Join-Path $UserHome ".bun\bin\$Cmd.exe") ) foreach ($c in $candidates) { if ($c -and (Test-Path -LiteralPath $c -PathType Leaf)) { return $true } } return $false } function ConvertTo-OrderedMap { param([object]$InputObj) if ($null -eq $InputObj) { return $null } if ($InputObj -is [System.Collections.IDictionary]) { $ord = [ordered]@{} foreach ($k in $InputObj.Keys) { $ord[[string]$k] = ConvertTo-OrderedMap $InputObj[$k] } return $ord } if ($InputObj -is [pscustomobject]) { $ord = [ordered]@{} foreach ($prop in $InputObj.PSObject.Properties) { $ord[$prop.Name] = ConvertTo-OrderedMap $prop.Value } return $ord } if ($InputObj -is [System.Collections.IEnumerable] -and -not ($InputObj -is [string])) { $list = New-Object System.Collections.ArrayList foreach ($item in $InputObj) { [void]$list.Add((ConvertTo-OrderedMap $item)) } return ,$list.ToArray() } return $InputObj } function Merge-OrderedMaps { param([System.Collections.IDictionary]$Target, [System.Collections.IDictionary]$Patch) $res = [ordered]@{} foreach ($k in $Target.Keys) { $res[$k] = $Target[$k] } foreach ($k in $Patch.Keys) { $pv = $Patch[$k] if ($res.Contains($k) -and ($res[$k] -is [System.Collections.IDictionary]) -and ($pv -is [System.Collections.IDictionary])) { $res[$k] = Merge-OrderedMaps $res[$k] $pv } else { $res[$k] = $pv } } return $res } function Read-JsonList { param([string]$Path) if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return @() } $raw = [System.IO.File]::ReadAllText($Path, $Utf8NoBom) if ([string]::IsNullOrWhiteSpace($raw) -or -not $raw.TrimStart().StartsWith("[")) { return @() } try { $parsed = $raw | ConvertFrom-Json if ($null -eq $parsed) { return @() } $out = New-Object System.Collections.Generic.List[object] foreach ($item in @($parsed)) { $out.Add((ConvertTo-OrderedMap $item)) } return ,$out.ToArray() } catch { return @() } } function Read-JsonOrdered { param([string]$Path) if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return [ordered]@{} } $raw = [System.IO.File]::ReadAllText($Path, $Utf8NoBom) if ([string]::IsNullOrWhiteSpace($raw)) { return [ordered]@{} } try { $parsed = $raw | ConvertFrom-Json $mapped = ConvertTo-OrderedMap $parsed if ($mapped -is [System.Collections.IDictionary]) { return $mapped } return [ordered]@{} } catch { return [ordered]@{} } } function Write-TextSafe { param([string]$Path, [string]$Content) if ($DryRun) { return } $parent = Split-Path -Parent $Path if ($parent -and -not (Test-Path -LiteralPath $parent)) { [void](New-Item -ItemType Directory -Path $parent -Force) } if (Test-Path -LiteralPath $Path -PathType Leaf) { Copy-Item -LiteralPath $Path -Destination "$Path.bak-smithapi-$Timestamp" -Force } $tmp = "$Path.smithapi.tmp.$PID" [System.IO.File]::WriteAllText($tmp, $Content, $Utf8NoBom) Move-Item -LiteralPath $tmp -Destination $Path -Force } function Format-TomlString { param([string]$Value) $escaped = $Value.Replace("\", "\\").Replace('"', '\"') return '"' + $escaped + '"' } function Format-PsSingleQuoted { param([string]$Value) return "'" + $Value.Replace("'", "''") + "'" } function Strip-ManagedBlock { param([string]$Text) if ([string]::IsNullOrEmpty($Text)) { return "" } $pattern = "(?m)(?:\r?\n)?[ \t]*" + [regex]::Escape($StartMark) + "[\s\S]*?" + [regex]::Escape($EndMark) + "[ \t]*(?:\r?\n)?" $cleaned = [regex]::Replace($Text, $pattern, "`n") $cleaned = [regex]::Replace($cleaned, "\n{3,}", "`n`n") return $cleaned } function Upsert-ManagedBlock { param([string]$Text, [string]$BlockBody) $cleaned = (Strip-ManagedBlock $Text).TrimEnd("`r", "`n") $block = "$StartMark`n$($BlockBody.TrimEnd("`r", "`n"))`n$EndMark" if ([string]::IsNullOrEmpty($cleaned)) { return "$block`n" } return "$cleaned`n`n$block`n" } function Strip-TomlSection { param([string]$Text, [string]$Header) $lines = $Text -split "\r?\n" $out = New-Object System.Collections.Generic.List[string] $skip = $false foreach ($ln in $lines) { $s = $ln.Trim() if ($s.StartsWith("[") -and -not $s.StartsWith("[[")) { if ($s -eq $Header) { $skip = $true continue } $skip = $false } elseif ($s.StartsWith("[[") -and $skip) { $skip = $false } if (-not $skip) { $out.Add($ln) } } return ($out -join "`n") } function Upsert-TomlRootKv { param([string]$Text, [System.Collections.IDictionary]$Updates) $lines = if ([string]::IsNullOrEmpty($Text)) { @() } else { $Text -split "\r?\n" } $firstSec = $lines.Count for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match "^\s*\[") { $firstSec = $i break } } $head = New-Object System.Collections.Generic.List[string] for ($i = 0; $i -lt $firstSec; $i++) { $head.Add($lines[$i]) } $tail = New-Object System.Collections.Generic.List[string] for ($i = $firstSec; $i -lt $lines.Count; $i++) { $tail.Add($lines[$i]) } $seen = @{} $newHead = New-Object System.Collections.Generic.List[string] foreach ($ln in $head) { $matched = $false foreach ($k in $Updates.Keys) { if ($ln -match ("^\s*" + [regex]::Escape($k) + "\s*=")) { $newHead.Add("$k = $($Updates[$k])") $seen[$k] = $true $matched = $true break } } if (-not $matched) { $newHead.Add($ln) } } $missing = New-Object System.Collections.Generic.List[string] foreach ($k in $Updates.Keys) { if (-not $seen.ContainsKey($k)) { $missing.Add("$k = $($Updates[$k])") } } if ($missing.Count -gt 0) { while ($newHead.Count -gt 0 -and [string]::IsNullOrWhiteSpace($newHead[$newHead.Count - 1])) { $newHead.RemoveAt($newHead.Count - 1) } foreach ($m in $missing) { $newHead.Add($m) } $newHead.Add("") } $all = New-Object System.Collections.Generic.List[string] foreach ($x in $newHead) { $all.Add($x) } foreach ($x in $tail) { $all.Add($x) } return (($all -join "`n").TrimEnd("`r", "`n") + "`n") } $DefaultModels = @( "claude-sonnet-5-5", "claude-opus-5-5", "gpt-6.2-astra", "gpt-6.1-sol", "gemini-4-carbon", "deepseek-v4-pro", "grok-4.7" ) function Invoke-GatewayJsonGet { param( [string]$Url, [hashtable]$Headers, [int]$TimeoutSec, [bool]$IsLocalUrl, [hashtable]$IrmExtra ) $errTag = "" try { $resp = Invoke-RestMethod -Uri $Url -Headers $Headers -Method Get -TimeoutSec $TimeoutSec @IrmExtra return @{ Status = 200; Data = $resp; Error = "" } } catch { $statusCode = 0 try { if ($_.Exception.Response) { $statusCode = [int]$_.Exception.Response.StatusCode } } catch {} if ($statusCode -gt 0) { return @{ Status = $statusCode; Data = $null; Error = $_.Exception.GetType().Name } } $errTag = $_.Exception.GetType().Name } if (Get-Command curl.exe -ErrorAction SilentlyContinue) { $curlArgs = @("--ssl-no-revoke", "-sS", "--max-time", "$TimeoutSec", "-w", "`n%{http_code}") if ($IsLocalUrl) { $curlArgs += @("--noproxy", "*") } foreach ($hk in $Headers.Keys) { $curlArgs += @("-H", "${hk}: $($Headers[$hk])") } $curlArgs += $Url $prevEap = $ErrorActionPreference try { $ErrorActionPreference = "Continue" $rawOut = (& curl.exe @curlArgs 2>$null | Out-String) if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($rawOut)) { $lines = $rawOut.TrimEnd("`r", "`n") -split "`r?`n" if ($lines.Count -ge 1) { $codeText = $lines[$lines.Count - 1].Trim() $httpCode = 0 [void][int]::TryParse($codeText, [ref]$httpCode) $bodyText = if ($lines.Count -gt 1) { ($lines[0..($lines.Count - 2)] -join "`n").Trim() } else { "" } if ($httpCode -ge 200 -and $httpCode -lt 300 -and $bodyText) { $parsed = $bodyText | ConvertFrom-Json return @{ Status = 200; Data = $parsed; Error = "" } } if ($httpCode -gt 0) { return @{ Status = $httpCode; Data = $null; Error = "HTTP $httpCode" } } } } } catch { } finally { $ErrorActionPreference = $prevEap } } return @{ Status = 0; Data = $null; Error = $errTag } } function Probe-Gateway { if ($Uninstall -or $SkipVerify) { return @{ Models = $DefaultModels; Usage = $null } } $models = New-Object System.Collections.Generic.List[string] $usageStr = $null $headers = @{ "Accept" = "application/json" "Authorization" = "Bearer $Key" "User-Agent" = "SmithAPI-Setup/1.0" } $isLocalUrl = $BaseUrl -match '^https?://(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|/|$)' $irmExtra = @{} if ($isLocalUrl -and $PSVersionTable -and $PSVersionTable.PSVersion -and $PSVersionTable.PSVersion.Major -ge 7) { $irmExtra["NoProxy"] = $true } $mRes = Invoke-GatewayJsonGet "$BaseUrl/v1/models" $headers 6 $isLocalUrl $irmExtra if ($mRes.Status -eq 200 -and $mRes.Data) { $resp = $mRes.Data $rawList = $null if ($resp -and $resp.data -and $resp.data.models) { $rawList = $resp.data.models } elseif ($resp -and $resp.data) { $rawList = $resp.data } elseif ($resp -and $resp.models) { $rawList = $resp.models } if ($rawList) { foreach ($item in $rawList) { if ($item -is [string] -and $item.Trim()) { $models.Add($item.Trim()) } elseif ($item -and $item.id) { $models.Add(([string]$item.id).Trim()) } } } } elseif ($mRes.Status -eq 401 -or $mRes.Status -eq 403) { Write-Host (Get-Msg "auth_fail" @($mRes.Status)) -ForegroundColor Red if ($Yes) { exit 1 } $ans = Read-Host (Get-Msg "force_confirm") if ($ans -notmatch "^[Yy]$") { exit 1 } } else { $skipDetail = if ($mRes.Status -gt 0) { "HTTP $($mRes.Status)" } else { [string]$mRes.Error } Write-Host (Get-Msg "probe_skip" @($skipDetail)) } $uRes = Invoke-GatewayJsonGet "$BaseUrl/v1/usage" $headers 5 $isLocalUrl $irmExtra if ($uRes.Status -eq 200 -and $uRes.Data) { $uResp = $uRes.Data $rem = $null if ($null -ne $uResp.remaining) { $rem = $uResp.remaining } elseif ($uResp.quota -and $null -ne $uResp.quota.remaining) { $rem = $uResp.quota.remaining } elseif ($null -ne $uResp.balance) { $rem = $uResp.balance } $unit = "CNY" if ($uResp.unit) { $unit = [string]$uResp.unit } elseif ($uResp.quota -and $uResp.quota.unit) { $unit = [string]$uResp.quota.unit } if ($null -ne $rem) { $usageStr = if ($unit.ToUpperInvariant() -eq "CNY") { "CNY " + ([double]$rem).ToString("0.00") } else { "$unit $rem" } } } $dedup = New-Object System.Collections.Generic.List[string] $seen = @{} foreach ($m in $models) { if (-not $seen.ContainsKey($m)) { $seen[$m] = $true $dedup.Add($m) } } if ($dedup.Count -eq 0) { return @{ Models = $DefaultModels; Usage = $usageStr } } return @{ Models = $dedup.ToArray(); Usage = $usageStr } } function Pick-BestModel { param([string[]]$Models, [string[]]$Prefixes, [string]$Fallback) foreach ($p in $Prefixes) { foreach ($m in $Models) { if ($m.ToLowerInvariant().StartsWith($p)) { return $m } } } if ($Models.Count -gt 0) { return $Models[0] } return $Fallback } $UpdatedList = New-Object System.Collections.Generic.List[object] $WarningList = New-Object System.Collections.Generic.List[string] $GuiList = New-Object System.Collections.Generic.List[string] $SkippedTargets = New-Object System.Collections.Generic.List[string] $ConfiguredTargets = @{} if ($UnknownOnly.Count -gt 0) { $WarningList.Add((Get-Msg "warn_unknown_only" @(($UnknownOnly -join ", "), ($KnownTargets -join ", ")))) } function Short-HomePath { param([string]$Text) if ([string]::IsNullOrEmpty($Text) -or [string]::IsNullOrEmpty($UserHome)) { return $Text } $trimmedHome = $UserHome.TrimEnd("\", "/") if ($trimmedHome.Length -gt 1) { return $Text.Replace($trimmedHome, "~") } return $Text } function Add-Done { param([string]$Target, [string]$Detail) $shortDetail = Short-HomePath $Detail $UpdatedList.Add([pscustomobject]@{ Target = $Target; Detail = $shortDetail; Dry = [bool]$DryRun }) $ConfiguredTargets[$Target] = $true } $probe = Probe-Gateway $Models = [string[]]$probe.Models $UsageStr = $probe.Usage if (-not $Uninstall) { Write-Tone (Get-Msg "cfg_head" @((Mask-Key $Key), $BaseUrl)) "Green" if ($UsageStr) { Write-Tone (Get-Msg "bal_head" @($UsageStr)) "Green" } $sampleCount = [Math]::Min(5, $Models.Count) Write-Tone (Get-Msg "mod_head" @($Models.Count, ($Models[0..($sampleCount-1)] -join ", "))) "Cyan" } else { Write-Tone (Get-Msg "uninstall_head" @($BaseUrl)) "Yellow" } # 1. Claude Code $customClaudeDir = if (-not [string]::IsNullOrWhiteSpace($env:CLAUDE_CONFIG_DIR)) { $env:CLAUDE_CONFIG_DIR.Trim() } else { "" } $claudeDir = if ($customClaudeDir) { $customClaudeDir } else { Join-Path $UserHome ".claude" } $claudeJson = if ($customClaudeDir) { Join-Path $claudeDir ".claude.json" } else { Join-Path $UserHome ".claude.json" } if (Should-RunTarget "claude-code" ((Command-Exists "claude") -or (Test-Path $claudeDir) -or (Test-Path $claudeJson))) { $settingsPath = Join-Path $claudeDir "settings.json" $data = Read-JsonOrdered $settingsPath if ($Uninstall) { if ($data.Contains("env") -and ($data["env"] -is [System.Collections.IDictionary])) { $envMap = $data["env"] if (([string]$envMap["ANTHROPIC_BASE_URL"]).TrimEnd("/") -eq $BaseUrl) { $envMap.Remove("ANTHROPIC_BASE_URL") $envMap.Remove("ANTHROPIC_AUTH_TOKEN") $envMap.Remove("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC") Write-TextSafe $settingsPath (($data | ConvertTo-Json -Depth 32) + "`n") Add-Done "Claude Code" (Get-Msg "cleaned" @($settingsPath)) } } } else { if (-not $data.Contains("env") -or -not ($data["env"] -is [System.Collections.IDictionary])) { $data["env"] = [ordered]@{} } $envMap = $data["env"] $envMap["ANTHROPIC_BASE_URL"] = $BaseUrl $envMap["ANTHROPIC_AUTH_TOKEN"] = $Key $envMap["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] = "1" if ($envMap.Contains("ANTHROPIC_API_KEY")) { $envMap.Remove("ANTHROPIC_API_KEY") $WarningList.Add((Get-Msg "warn_ant_key" @($settingsPath))) } if (-not $data.Contains('$schema')) { $data['$schema'] = "https://json.schemastore.org/claude-code-settings.json" } Write-TextSafe $settingsPath (($data | ConvertTo-Json -Depth 32) + "`n") $cj = Read-JsonOrdered $claudeJson if ($cj["hasCompletedOnboarding"] -ne $true) { $cj["hasCompletedOnboarding"] = $true Write-TextSafe $claudeJson (($cj | ConvertTo-Json -Depth 32) + "`n") } Add-Done "Claude Code" (Get-Msg "updated_claude" @($settingsPath)) } } # 2. Codex CLI $codexDir = if (-not [string]::IsNullOrWhiteSpace($env:CODEX_HOME)) { $env:CODEX_HOME } else { Join-Path $UserHome ".codex" } if (Should-RunTarget "codex" ((Command-Exists "codex") -or (Test-Path $codexDir))) { $cfgPath = Join-Path $codexDir "config.toml" $authPath = Join-Path $codexDir "auth.json" $origToml = if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { [System.IO.File]::ReadAllText($cfgPath, $Utf8NoBom) } else { "" } if ($Uninstall) { if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { $cl = Strip-TomlSection (Strip-ManagedBlock $origToml) "[model_providers.smithapi]" $cl = [regex]::Replace($cl, '(?m)^model_provider\s*=\s*"smithapi"\s*\r?\n?', "") Write-TextSafe $cfgPath $cl } if (Test-Path -LiteralPath $authPath -PathType Leaf) { $ad = Read-JsonOrdered $authPath $ad.Remove("OPENAI_API_KEY") Write-TextSafe $authPath (($ad | ConvertTo-Json -Depth 32) + "`n") } Add-Done "Codex CLI" (Get-Msg "cleaned" @($cfgPath)) } else { $bestOpenai = Pick-BestModel $Models @("gpt-6", "gpt-5", "codex") "gpt-6.1-sol" $cleaned = Strip-TomlSection (Strip-ManagedBlock $origToml) "[model_providers.smithapi]" $cleaned = Upsert-TomlRootKv $cleaned ([ordered]@{ "model_provider" = '"smithapi"' "model" = (Format-TomlString $bestOpenai) "web_search" = '"live"' "disable_response_storage" = "true" }) $provBlock = @( "[model_providers.smithapi]", 'name = "SmithAPI"', ("base_url = " + (Format-TomlString ($BaseUrl + "/v1"))), 'wire_api = "responses"', "requires_openai_auth = false", ("experimental_bearer_token = " + (Format-TomlString $Key)), 'http_headers = { "x-openai-actor-authorization" = "local-image-extension" }' ) -join "`n" Write-TextSafe $cfgPath (Upsert-ManagedBlock $cleaned $provBlock) $authObj = Read-JsonOrdered $authPath $authObj["OPENAI_API_KEY"] = $Key Write-TextSafe $authPath (($authObj | ConvertTo-Json -Depth 32) + "`n") Add-Done "Codex CLI" "$cfgPath + $authPath (model=$bestOpenai)" } } # 3. DSH (DeepSeek Harness) function Upsert-DshCredentials { param([string]$Path, [string]$KeyVal) if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { if ($Uninstall) { return } $txt = "version: 1`nrefs:`n SMITHAPI_API_KEY: " + (Format-TomlString $KeyVal) + "`n" Write-TextSafe $Path $txt return } $lines = New-Object System.Collections.Generic.List[string] foreach ($ln in ([System.IO.File]::ReadAllText($Path, $Utf8NoBom) -split "\r?\n")) { $lines.Add($ln) } $refsIdx = -1 for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match "^refs\s*:\s*(?:#.*)?$") { $refsIdx = $i; break } } if ($Uninstall) { if ($refsIdx -lt 0) { return } $out = New-Object System.Collections.Generic.List[string] $inRefs = $false for ($i = 0; $i -lt $lines.Count; $i++) { $ln = $lines[$i] if ($i -eq $refsIdx) { $inRefs = $true; $out.Add($ln); continue } if ($inRefs) { if ([string]::IsNullOrWhiteSpace($ln) -or $ln.StartsWith(" ") -or $ln.StartsWith("`t")) { if ($ln -match "^\s+SMITHAPI_API_KEY\s*:") { continue } $out.Add($ln); continue } $inRefs = $false } $out.Add($ln) } Write-TextSafe $Path (($out -join "`n").TrimEnd("`r", "`n") + "`n") return } if ($refsIdx -lt 0) { if ($lines.Count -gt 0 -and -not [string]::IsNullOrWhiteSpace($lines[$lines.Count - 1])) { $lines.Add("") } $lines.Add("refs:") $lines.Add(" SMITHAPI_API_KEY: " + (Format-TomlString $KeyVal)) Write-TextSafe $Path (($lines -join "`n").TrimEnd("`r", "`n") + "`n") return } $childIndent = " " $keyIdx = -1 for ($j = $refsIdx + 1; $j -lt $lines.Count; $j++) { $ln = $lines[$j] if ([string]::IsNullOrWhiteSpace($ln) -or $ln.TrimStart().StartsWith("#")) { continue } if ($ln -match "^([ \t]+)\S") { $childIndent = $Matches[1] if ($ln -match "^[ \t]+SMITHAPI_API_KEY\s*:") { $keyIdx = $j; break } } else { break } } $targetLn = $childIndent + "SMITHAPI_API_KEY: " + (Format-TomlString $KeyVal) if ($keyIdx -ge 0) { $lines[$keyIdx] = $targetLn } else { $lines.Insert($refsIdx + 1, $targetLn) } Write-TextSafe $Path (($lines -join "`n").TrimEnd("`r", "`n") + "`n") } function Render-DshProviderBlock { param([string]$Indent, [string[]]$ModelsArr, [bool]$IncludeMarkers = $true) $i1 = $Indent $i2 = $Indent + " " $i3 = $Indent + " " $i4 = $Indent + " " $oai = @($ModelsArr | Where-Object { -not $_.ToLowerInvariant().StartsWith("claude") } | Select-Object -First 6) if ($oai.Count -eq 0) { $oai = @("gpt-6.2-astra", "deepseek-v4-pro", "gemini-4-carbon", "grok-4.7") } $cld = @($ModelsArr | Where-Object { $_.ToLowerInvariant().StartsWith("claude") } | Select-Object -First 4) if ($cld.Count -eq 0) { $cld = @("claude-sonnet-5-5", "claude-opus-5-5") } $buf = New-Object System.Collections.Generic.List[string] if ($IncludeMarkers) { $buf.Add("$i1$StartMark") } $buf.Add("${i1}smithapi:") $buf.Add("${i2}displayName: `"SmithAPI`"") $buf.Add("${i2}apiKeyEnv: SMITHAPI_API_KEY") $buf.Add("${i2}api: openai-completions") $buf.Add("${i2}baseURL: " + (Format-TomlString ($BaseUrl + "/v1"))) $buf.Add("${i2}models:") foreach ($m in $oai) { $qm = Format-TomlString $m $buf.Add("${i3}- id: $qm") $buf.Add("${i4}name: $qm") } $buf.Add("${i1}smithapi-claude:") $buf.Add("${i2}displayName: `"SmithAPI Claude`"") $buf.Add("${i2}apiKeyEnv: SMITHAPI_API_KEY") $buf.Add("${i2}api: anthropic-messages") $buf.Add("${i2}baseURL: " + (Format-TomlString $BaseUrl)) $buf.Add("${i2}models:") foreach ($m in $cld) { $qm = Format-TomlString $m $buf.Add("${i3}- id: $qm") $buf.Add("${i4}name: $qm") } if ($IncludeMarkers) { $buf.Add("$i1$EndMark") } return ($buf -join "`n") } function Patch-DshCordisFile { param([string]$Path, [string[]]$ModelsArr) $orig = if (Test-Path -LiteralPath $Path -PathType Leaf) { [System.IO.File]::ReadAllText($Path, $Utf8NoBom) } else { "" } $cleaned = Strip-ManagedBlock $orig if ($Uninstall) { if ((Test-Path -LiteralPath $Path -PathType Leaf) -and $cleaned -ne $orig) { Write-TextSafe $Path $cleaned return $true } return $false } $lines = New-Object System.Collections.Generic.List[string] foreach ($ln in ($cleaned -split "\r?\n")) { $lines.Add($ln) } $llmIdx = -1; $llmInd = 0 for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match "^(\s*)(?:-\s*)?id\s*:\s*['`"]?llm-pi-ai['`"]?\s*(?:#.*)?$") { $llmIdx = $i; $llmInd = $Matches[1].Length; break } } if ($llmIdx -ge 0) { $cfgIdx = -1; $cfgInd = 0; $provIdx = -1; $provInd = 0; $endIdx = $lines.Count for ($j = $llmIdx + 1; $j -lt $lines.Count; $j++) { $ln = $lines[$j]; $s = $ln.Trim() if (-not $s -or $s.StartsWith("#")) { continue } $curInd = $ln.Length - $ln.TrimStart(" ").Length if ($ln -match "^\s*-\s+" -and $curInd -le $llmInd) { $endIdx = $j; break } if ($cfgIdx -lt 0 -and $ln -match "^(\s*)config\s*:\s*(?:#.*)?$") { $cfgIdx = $j; $cfgInd = $Matches[1].Length; continue } if ($cfgIdx -ge 0 -and $curInd -le $cfgInd -and -not $s.StartsWith("-")) { $endIdx = $j; break } if ($cfgIdx -ge 0 -and $ln -match "^(\s*)providers\s*:\s*(\{\s*\})?\s*(?:#.*)?$") { $provIdx = $j; $provInd = $Matches[1].Length if ($Matches[2]) { $lines[$j] = (" " * $provInd) + "providers:" } break } } if ($provIdx -ge 0) { $childLen = $provInd + 2 for ($k = $provIdx + 1; $k -lt $endIdx; $k++) { $s = $lines[$k].Trim() if (-not $s -or $s.StartsWith("#")) { continue } $ki = $lines[$k].Length - $lines[$k].TrimStart(" ").Length if ($ki -gt $provInd) { $childLen = $ki } break } $blk = (Render-DshProviderBlock (" " * $childLen) $ModelsArr $true) -split "\r?\n" for ($b = $blk.Count - 1; $b -ge 0; $b--) { $lines.Insert($provIdx + 1, $blk[$b]) } Write-TextSafe $Path (($lines -join "`n").TrimEnd("`r", "`n") + "`n") return $true } if ($cfgIdx -ge 0) { $pInd = " " * ($cfgInd + 2); $cInd = " " * ($cfgInd + 4) $blk = @("${pInd}providers:") + ((Render-DshProviderBlock $cInd $ModelsArr $true) -split "\r?\n") for ($b = $blk.Count - 1; $b -ge 0; $b--) { $lines.Insert($cfgIdx + 1, $blk[$b]) } Write-TextSafe $Path (($lines -join "`n").TrimEnd("`r", "`n") + "`n") return $true } $cIndS = " " * ($llmInd + 2); $pIndS = " " * ($llmInd + 4); $eIndS = " " * ($llmInd + 6) $blk = @("${cIndS}config:", "${pIndS}providers:") + ((Render-DshProviderBlock $eIndS $ModelsArr $true) -split "\r?\n") for ($b = $blk.Count - 1; $b -ge 0; $b--) { $lines.Insert($llmIdx + 1, $blk[$b]) } Write-TextSafe $Path (($lines -join "`n").TrimEnd("`r", "`n") + "`n") return $true } $inner = Render-DshProviderBlock " " $ModelsArr $false $body = "- id: llm-pi-ai`n config:`n providers:`n$inner" Write-TextSafe $Path (Upsert-ManagedBlock $cleaned $body) return $true } function Upsert-EnvFile { param([string]$Path, [System.Collections.IDictionary]$KvMap) if ($Uninstall) { if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return } $lines = [System.IO.File]::ReadAllText($Path, $Utf8NoBom) -split "\r?\n" $out = New-Object System.Collections.Generic.List[string] foreach ($ln in $lines) { $hit = $false foreach ($k in $KvMap.Keys) { if ($ln -match ("^\s*" + [regex]::Escape($k) + "\s*=")) { $hit = $true; break } } if (-not $hit) { $out.Add($ln) } } Write-TextSafe $Path (($out -join "`n").TrimEnd("`r", "`n") + "`n") return } $lines = if (Test-Path -LiteralPath $Path -PathType Leaf) { [System.IO.File]::ReadAllText($Path, $Utf8NoBom) -split "\r?\n" } else { @() } $seen = @{}; $out = New-Object System.Collections.Generic.List[string] foreach ($ln in $lines) { $rep = $false foreach ($k in $KvMap.Keys) { if ($ln -match ("^\s*" + [regex]::Escape($k) + "\s*=")) { $out.Add("$k=$($KvMap[$k])"); $seen[$k] = $true; $rep = $true; break } } if (-not $rep) { $out.Add($ln) } } foreach ($k in $KvMap.Keys) { if (-not $seen.ContainsKey($k)) { $out.Add("$k=$($KvMap[$k])") } } Write-TextSafe $Path (($out -join "`n").TrimEnd("`r", "`n") + "`n") } if (Should-RunTarget "dsh" ((Command-Exists "dsh") -or (Command-Exists "dsh-tui") -or (Test-Path $DshHome))) { $credPath = Join-Path $DshHome ".credentials.yaml" Upsert-DshCredentials $credPath $Key $dshEnv = Join-Path $DshHome ".env" if (Test-Path -LiteralPath $dshEnv -PathType Leaf) { Upsert-EnvFile $dshEnv ([ordered]@{ "SMITHAPI_API_KEY" = $Key; "SMITHAPI_BASE_URL" = $BaseUrl }) } $profilesDir = Join-Path $DshHome "profiles" $patchedProfs = New-Object System.Collections.Generic.List[string] if (Test-Path -LiteralPath $profilesDir -PathType Container) { foreach ($prof in (Get-ChildItem -LiteralPath $profilesDir -Directory | Sort-Object Name)) { $pf = Join-Path $prof.FullName "cordis.patch.yml" if ((Test-Path -LiteralPath $pf -PathType Leaf) -or ($prof.Name -in @("default", "tui", "desktop", "web", "headless"))) { if (Patch-DshCordisFile $pf $Models) { $patchedProfs.Add($prof.Name) } } } } elseif (-not $Uninstall) { $pf = Join-Path (Join-Path $profilesDir "tui") "cordis.patch.yml" if (Patch-DshCordisFile $pf $Models) { $patchedProfs.Add("tui") } } $patchOverlay = Join-Path $DshHome "patch_smithapi.yaml" if ($Uninstall) { if ((Test-Path -LiteralPath $patchOverlay -PathType Leaf) -and -not $DryRun) { Copy-Item -LiteralPath $patchOverlay -Destination "$patchOverlay.bak-smithapi-$Timestamp" -Force Remove-Item -LiteralPath $patchOverlay -Force } Add-Done "DSH" (Get-Msg "cleaned" @($credPath)) } else { $bestDsh = Pick-BestModel $Models @("deepseek", "gpt-6", "claude") $Models[0] $innerProv = Render-DshProviderBlock " " $Models $false $overlayTxt = "# SmithAPI DSH Patch`n- id: llm-pi-ai`n config:`n providers:`n$innerProv`n- id: agent-default-model`n config:`n provider: smithapi`n model: " + (Format-TomlString $bestDsh) + "`n" Write-TextSafe $patchOverlay $overlayTxt $pNote = if ($patchedProfs.Count -gt 0) { $patchedProfs -join ", " } else { "none" } Add-Done "DSH" (Get-Msg "updated_dsh" @($credPath, $pNote, $patchOverlay)) } } # 4. Windows User Env + PowerShell $PROFILE if (Should-RunTarget "shell-env" $true) { $envVars = [ordered]@{ "SMITHAPI_BASE_URL" = $BaseUrl "SMITHAPI_API_KEY" = $Key "ANTHROPIC_BASE_URL" = $BaseUrl "ANTHROPIC_AUTH_TOKEN" = $Key "OPENAI_BASE_URL" = "$BaseUrl/v1" "OPENAI_API_KEY" = $Key "GOOGLE_GEMINI_BASE_URL" = $BaseUrl "GEMINI_API_KEY" = $Key "GROK_MODELS_BASE_URL" = "$BaseUrl/v1" "XAI_API_KEY" = $Key "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" = "1" } if (-not $DryRun) { foreach ($k in $envVars.Keys) { $val = if ($Uninstall) { $null } else { $envVars[$k] } try { [Environment]::SetEnvironmentVariable($k, $val, "User") } catch {} try { [Environment]::SetEnvironmentVariable($k, $val, "Process") } catch {} } } if (-not $Uninstall) { try { $oldAnt = [Environment]::GetEnvironmentVariable("ANTHROPIC_API_KEY", "User") if (-not [string]::IsNullOrWhiteSpace($oldAnt)) { $WarningList.Add((Get-Msg "warn_old_ant")) } } catch {} } $profPath = $PROFILE if ($profPath -and -not [string]::IsNullOrWhiteSpace([string]$profPath)) { $origProf = if (Test-Path -LiteralPath $profPath -PathType Leaf) { [System.IO.File]::ReadAllText($profPath, $Utf8NoBom) } else { "" } if ($Uninstall) { if (Test-Path -LiteralPath $profPath -PathType Leaf) { Write-TextSafe $profPath (Strip-ManagedBlock $origProf) } } else { $psBlock = ($envVars.Keys | ForEach-Object { '$env:' + $_ + ' = ' + (Format-PsSingleQuoted $envVars[$_]) }) -join "`n" Write-TextSafe $profPath (Upsert-ManagedBlock $origProf $psBlock) } } if ($Uninstall) { Add-Done "Shell & Env" (Get-Msg "cleaned" @([string]$profPath)) } else { Add-Done "Shell & Env" (Get-Msg "updated_env" @([string]$profPath)) } } # 5. Gemini CLI $gemDir = Join-Path $UserHome ".gemini" if (Should-RunTarget "gemini-cli" ((Command-Exists "gemini") -or (Test-Path $gemDir))) { $gemEnv = Join-Path $gemDir ".env" Upsert-EnvFile $gemEnv ([ordered]@{ "GOOGLE_GEMINI_BASE_URL" = $BaseUrl; "GEMINI_API_KEY" = $Key }) Add-Done "Gemini CLI" (Get-Msg "updated_gemini" @($gemEnv)) } # 6. OpenCode $ocXdg = Join-Path (Join-Path $UserHome ".config") "opencode" $ocApp = Join-Path $AppDataDir "opencode" $ocDetected = (Command-Exists "opencode") -or (Test-Path $ocXdg) -or (Test-Path $ocApp) if (Should-RunTarget "opencode" $ocDetected) { $ocDir = if (Test-Path $ocApp) { $ocApp } else { $ocXdg } $ocCfg = Join-Path $ocDir "opencode.json" $data = Read-JsonOrdered $ocCfg if ($Uninstall) { if ($data.Contains("provider") -and ($data["provider"] -is [System.Collections.IDictionary])) { $data["provider"].Remove("smithapi") $data["provider"].Remove("smithapi-anthropic") Write-TextSafe $ocCfg (($data | ConvertTo-Json -Depth 32) + "`n") Add-Done "OpenCode" (Get-Msg "cleaned" @($ocCfg)) } } else { $oaiMap = [ordered]@{} $oaiList = @($Models | Where-Object { -not $_.ToLowerInvariant().StartsWith("claude") } | Select-Object -First 6) if ($oaiList.Count -eq 0) { $oaiList = @("gpt-6.2-astra", "deepseek-v4-pro") } foreach ($m in $oaiList) { $oaiMap[$m] = [ordered]@{ "name" = $m } } $cldMap = [ordered]@{} $cldList = @($Models | Where-Object { $_.ToLowerInvariant().StartsWith("claude") } | Select-Object -First 4) if ($cldList.Count -eq 0) { $cldList = @("claude-sonnet-5-5", "claude-opus-5-5") } foreach ($m in $cldList) { $cldMap[$m] = [ordered]@{ "name" = $m } } $patch = [ordered]@{ '$schema' = "https://opencode.ai/config.json" "provider" = [ordered]@{ "smithapi" = [ordered]@{ "npm" = "@ai-sdk/openai-compatible" "name" = "SmithAPI" "options" = [ordered]@{ "baseURL" = "$BaseUrl/v1"; "apiKey" = $Key } "models" = $oaiMap } "smithapi-anthropic" = [ordered]@{ "npm" = "@ai-sdk/anthropic" "name" = "SmithAPI Claude" "options" = [ordered]@{ "baseURL" = "$BaseUrl/v1"; "apiKey" = $Key } "models" = $cldMap } } } $merged = Merge-OrderedMaps $data $patch Write-TextSafe $ocCfg (($merged | ConvertTo-Json -Depth 32) + "`n") Add-Done "OpenCode" $ocCfg } } # 7. Grok CLI $grokDir = if (-not [string]::IsNullOrWhiteSpace($env:GROK_HOME)) { $env:GROK_HOME } else { Join-Path $UserHome ".grok" } if (Should-RunTarget "grok-cli" ((Command-Exists "grok") -or (Test-Path $grokDir))) { $grokCfg = Join-Path $grokDir "config.toml" $orig = if (Test-Path -LiteralPath $grokCfg -PathType Leaf) { [System.IO.File]::ReadAllText($grokCfg, $Utf8NoBom) } else { "" } if ($Uninstall) { if (Test-Path -LiteralPath $grokCfg -PathType Leaf) { Write-TextSafe $grokCfg (Strip-ManagedBlock $orig) Add-Done "Grok CLI" (Get-Msg "cleaned" @($grokCfg)) } } else { $bestGrok = Pick-BestModel $Models @("grok-") "grok-4.7" $cleaned = Strip-TomlSection (Strip-TomlSection (Strip-ManagedBlock $orig) "[endpoints]") "[auth]" $v1 = "$BaseUrl/v1" $blkList = New-Object System.Collections.Generic.List[string] $blkList.Add("[endpoints]") $blkList.Add("models_base_url = " + (Format-TomlString $v1)) $blkList.Add("models_list_url = " + (Format-TomlString "$v1/models")) $blkList.Add("xai_api_base_url = " + (Format-TomlString $v1)) $blkList.Add("cli_chat_proxy_base_url = " + (Format-TomlString $v1)) $blkList.Add("") $blkList.Add("[auth]") $blkList.Add('preferred_method = "api_key"') $qGrok = Format-TomlString $bestGrok $modelHdr = "[model.$qGrok]" if (-not $cleaned.Contains($modelHdr)) { $blkList.Add("") $blkList.Add($modelHdr) $blkList.Add("model = $qGrok") $blkList.Add('env_key = "XAI_API_KEY"') $blkList.Add('api_backend = "responses"') } if ($cleaned -notmatch "(?m)^\[models\]\s*$") { $blkList.Add("") $blkList.Add("[models]") $blkList.Add("default = $qGrok") } $blk = ($blkList.ToArray()) -join "`n" Write-TextSafe $grokCfg (Upsert-ManagedBlock $cleaned $blk) Add-Done "Grok CLI" "$grokCfg (model=$bestGrok)" } } # 8. Aider $aiderConf = Join-Path $UserHome ".aider.conf.yml" $aiderEnv = Join-Path $UserHome ".aider.env" if (Should-RunTarget "aider" ((Command-Exists "aider") -or (Test-Path $aiderConf) -or (Test-Path $aiderEnv))) { if ($Uninstall) { if (Test-Path -LiteralPath $aiderConf -PathType Leaf) { Write-TextSafe $aiderConf (Strip-ManagedBlock ([System.IO.File]::ReadAllText($aiderConf, $Utf8NoBom))) } Upsert-EnvFile $aiderEnv ([ordered]@{ "OPENAI_API_BASE" = "$BaseUrl/v1"; "OPENAI_API_KEY" = $Key }) Add-Done "Aider" (Get-Msg "cleaned" @($aiderConf)) } else { $orig = if (Test-Path -LiteralPath $aiderConf -PathType Leaf) { [System.IO.File]::ReadAllText($aiderConf, $Utf8NoBom) } else { "" } Write-TextSafe $aiderConf (Upsert-ManagedBlock $orig "openai-api-base: $BaseUrl/v1") Upsert-EnvFile $aiderEnv ([ordered]@{ "OPENAI_API_BASE" = "$BaseUrl/v1"; "OPENAI_API_KEY" = $Key }) Add-Done "Aider" "$aiderConf + $aiderEnv" } } # 9. Continue.dev $contDir = Join-Path $UserHome ".continue" if (Should-RunTarget "continue" (Test-Path $contDir)) { $contJson = Join-Path $contDir "config.json" $contYaml = Join-Path $contDir "config.yaml" if ((Test-Path -LiteralPath $contYaml -PathType Leaf) -and -not (Test-Path -LiteralPath $contJson -PathType Leaf)) { $origYml = [System.IO.File]::ReadAllText($contYaml, $Utf8NoBom) if ($Uninstall) { Write-TextSafe $contYaml (Strip-ManagedBlock $origYml) Add-Done "Continue" (Get-Msg "cleaned" @($contYaml)) } else { $cleanedYml = Strip-ManagedBlock $origYml if ($cleanedYml -notmatch "(?m)^models\s*:") { $cleanedYml = $cleanedYml.TrimEnd("`r", "`n") + "`nmodels:`n" } $ymlLines = New-Object System.Collections.Generic.List[string] foreach ($ln in ($cleanedYml -split "\r?\n")) { $ymlLines.Add($ln) } $mIdx = -1 for ($i = 0; $i -lt $ymlLines.Count; $i++) { if ($ymlLines[$i] -match "^models\s*:") { $mIdx = $i; break } } if ($mIdx -ge 0) { $bestYml = Pick-BestModel $Models @("claude", "gpt-6", "deepseek") $Models[0] $entry = @( " $StartMark", " - name: SmithAPI", " provider: openai", (" model: " + (Format-TomlString $bestYml)), (" apiBase: " + (Format-TomlString "$BaseUrl/v1")), (" apiKey: " + (Format-TomlString $Key)), " $EndMark" ) for ($e = $entry.Count - 1; $e -ge 0; $e--) { $ymlLines.Insert($mIdx + 1, $entry[$e]) } } Write-TextSafe $contYaml (($ymlLines -join "`n").TrimEnd("`r", "`n") + "`n") Add-Done "Continue" $contYaml } } elseif (-not $Uninstall -or (Test-Path -LiteralPath $contJson -PathType Leaf)) { $data = Read-JsonOrdered $contJson $items = @() if ($data.Contains("models") -and ($data["models"] -is [System.Collections.IEnumerable])) { foreach ($m in $data["models"]) { if (-not ($m -is [System.Collections.IDictionary] -and $m["title"] -eq "SmithAPI")) { $items += $m } } } if (-not $Uninstall) { $best = Pick-BestModel $Models @("claude", "gpt-6", "deepseek") $Models[0] $items += [ordered]@{ "title" = "SmithAPI"; "provider" = "openai"; "model" = $best; "apiBase" = "$BaseUrl/v1"; "apiKey" = $Key } } $data["models"] = $items Write-TextSafe $contJson (($data | ConvertTo-Json -Depth 32) + "`n") if ($Uninstall) { Add-Done "Continue" (Get-Msg "cleaned" @($contJson)) } else { Add-Done "Continue" $contJson } } } # 10. Factory Droid $facDir = Join-Path $UserHome ".factory" if (Should-RunTarget "droid" ((Command-Exists "droid") -or (Test-Path $facDir))) { $facCfg = Join-Path $facDir "config.json" if (-not $Uninstall -or (Test-Path -LiteralPath $facCfg -PathType Leaf)) { $data = Read-JsonOrdered $facCfg $items = @() if ($data.Contains("custom_models") -and ($data["custom_models"] -is [System.Collections.IEnumerable])) { foreach ($m in $data["custom_models"]) { if (-not ($m -is [System.Collections.IDictionary] -and $m["model_display_name"] -eq "SmithAPI")) { $items += $m } } } if (-not $Uninstall) { $best = Pick-BestModel $Models @("claude", "gpt-6", "deepseek") $Models[0] $items += [ordered]@{ "model_display_name" = "SmithAPI"; "model" = $best; "base_url" = "$BaseUrl/v1"; "api_key" = $Key; "provider" = "generic-chat-completion-api" } } $data["custom_models"] = $items Write-TextSafe $facCfg (($data | ConvertTo-Json -Depth 32) + "`n") if ($Uninstall) { Add-Done "Factory Droid" (Get-Msg "cleaned" @($facCfg)) } else { Add-Done "Factory Droid" $facCfg } } } # 11. OpenClaw $clawDir = Join-Path $UserHome ".openclaw" if (Should-RunTarget "openclaw" ((Command-Exists "openclaw") -or (Test-Path $clawDir))) { $clawCfg = Join-Path $clawDir "openclaw.json" $data = Read-JsonOrdered $clawCfg if ($Uninstall) { if ($data.Contains("models") -and ($data["models"] -is [System.Collections.IDictionary])) { $mObj = $data["models"] if ($mObj.Contains("providers") -and ($mObj["providers"] -is [System.Collections.IDictionary])) { $mObj["providers"].Remove("smithapi") Write-TextSafe $clawCfg (($data | ConvertTo-Json -Depth 32) + "`n") Add-Done "OpenClaw" (Get-Msg "cleaned" @($clawCfg)) } } } else { $mList = @() foreach ($m in ($Models | Select-Object -First 8)) { $mList += [ordered]@{ "id" = $m; "name" = $m } } $patch = [ordered]@{ "models" = [ordered]@{ "providers" = [ordered]@{ "smithapi" = [ordered]@{ "baseUrl" = "$BaseUrl/v1" "apiKey" = $Key "api" = "openai-completions" "models" = $mList } } } } $merged = Merge-OrderedMaps $data $patch Write-TextSafe $clawCfg (($merged | ConvertTo-Json -Depth 32) + "`n") Add-Done "OpenClaw" $clawCfg } } # 11b. Qwen Code $qwenDir = Join-Path $UserHome ".qwen" if (Should-RunTarget "qwen-code" ((Command-Exists "qwen") -or (Test-Path $qwenDir))) { $qwenEnv = Join-Path $qwenDir ".env" Upsert-EnvFile $qwenEnv ([ordered]@{ "OPENAI_BASE_URL" = "$BaseUrl/v1"; "OPENAI_API_KEY" = $Key }) if ($Uninstall) { Add-Done "Qwen Code" (Get-Msg "cleaned" @($qwenEnv)) } else { Add-Done "Qwen Code" $qwenEnv } } # 11c. WorkBuddy $wbNamePrefix = "SmithAPI " + [char]0x00B7 + " " $wbDetected = (Test-Path $WorkBuddyHome) -or (Test-Path (Join-Path $AppDataDir "WorkBuddy")) -or (Test-Path (Join-Path $LocalAppDataDir "WorkBuddy")) -or (Test-Path (Join-Path $LocalAppDataDir "Programs\WorkBuddy")) if (Should-RunTarget "workbuddy" $wbDetected) { $wbCfg = Join-Path $WorkBuddyHome "models.json" if (-not $Uninstall -or (Test-Path -LiteralPath $wbCfg -PathType Leaf)) { $existingWb = @(Read-JsonList $wbCfg) $keptWb = New-Object System.Collections.Generic.List[object] foreach ($item in $existingWb) { $nm = "" if ($item -is [System.Collections.IDictionary] -and $item.Contains("name")) { $nm = [string]$item["name"] } if (-not $nm.StartsWith($wbNamePrefix)) { $keptWb.Add($item) } } if ($Uninstall) { if ($keptWb.Count -ne $existingWb.Count) { $keptArr = $keptWb.ToArray() $jsonTxt = (ConvertTo-Json -InputObject @($keptArr) -Depth 32) + "`n" Write-TextSafe $wbCfg $jsonTxt Add-Done "WorkBuddy" (Get-Msg "cleaned_wb" @($wbCfg, $keptWb.Count)) } } else { $v1Url = "$BaseUrl/v1" $seenLower = @{} $picked = New-Object System.Collections.Generic.List[string] foreach ($m in $Models) { $cm = ([string]$m).Trim() if (-not $cm) { continue } $low = $cm.ToLowerInvariant() if (-not $seenLower.ContainsKey($low)) { $seenLower[$low] = $true $picked.Add($cm) if ($picked.Count -ge 12) { break } } } if ($picked.Count -eq 0) { foreach ($m in $DefaultModels) { $picked.Add($m) } } $mergedWb = New-Object System.Collections.Generic.List[object] foreach ($item in $keptWb) { $mergedWb.Add($item) } $addedCnt = 0 foreach ($m in $picked) { $lowM = $m.ToLowerInvariant() $imgs = ($lowM -match "claude|gpt-|gemini|grok|vl|vision|doubao|kimi-k") $reason = ($lowM -match "opus|sonnet|gpt-6|gpt-5|o3|o4|deepseek|grok|gemini|kimi|glm|qwen|thinking|reason") $mergedWb.Add([ordered]@{ "id" = $m "name" = "$wbNamePrefix$m" "vendor" = "Custom" "url" = $v1Url "apiKey" = $Key "supportsToolCall" = $true "supportsImages" = [bool]$imgs "supportsReasoning" = [bool]$reason "useCustomProtocol" = $false }) $addedCnt++ } $outArr = $mergedWb.ToArray() $jsonOut = (ConvertTo-Json -InputObject @($outArr) -Depth 32) + "`n" Write-TextSafe $wbCfg $jsonOut Add-Done "WorkBuddy" (Get-Msg "updated_wb" @($wbCfg, $addedCnt, $keptWb.Count)) } } } # 12. CC Switch $ccDetected = (Test-Path (Join-Path $UserHome ".cc-switch")) -or (Test-Path (Join-Path $LocalAppDataDir "CC Switch")) -or (Test-Path (Join-Path $LocalAppDataDir "Programs\CC Switch")) -or [bool]$OpenCcSwitch if (-not $Uninstall -and (Should-RunTarget "cc-switch" $ccDetected)) { if ($DryRun) { Add-Done "CC Switch" (Get-Msg "cc_dry") } else { if ([bool]$OpenCcSwitch) { $usageScript = "({`n request: {`n url: `"{{baseUrl}}`".replace(/\/+$/g, `"`").replace(/\/v1$/g, `"`") + `"/v1/usage`",`n method: `"GET`",`n headers: { `"Authorization`": `"Bearer {{apiKey}}`" }`n },`n extractor: function(response) {`n const remaining = response?.remaining ?? response?.quota?.remaining ?? response?.balance;`n const unit = response?.unit ?? response?.quota?.unit ?? `"CNY`";`n return { isValid: response?.is_active ?? response?.isValid ?? true, remaining, unit };`n }`n})" $usageB64 = [Convert]::ToBase64String($Utf8NoBom.GetBytes($usageScript)) $pairs = @( "resource=provider", "app=claude", "name=" + [Uri]::EscapeDataString("SmithAPI"), "homepage=" + [Uri]::EscapeDataString($SiteUrl), "endpoint=" + [Uri]::EscapeDataString($BaseUrl), "apiKey=" + [Uri]::EscapeDataString($Key), "configFormat=json", "usageEnabled=true", "usageScript=" + [Uri]::EscapeDataString($usageB64), "usageAutoInterval=30" ) $deeplink = "ccswitch://v1/import?" + ($pairs -join "&") try { Start-Process $deeplink Add-Done "CC Switch" (Get-Msg "cc_launched") } catch { Add-Done "CC Switch" (Get-Msg "cc_hint" @($SiteUrl)) } } else { Add-Done "CC Switch" (Get-Msg "cc_hint" @($SiteUrl)) } } } # 13. GUI summary (read-only) if (-not $Uninstall) { $guiFound = New-Object System.Collections.Generic.List[string] if ((Test-Path (Join-Path $UserHome ".cursor")) -or (Test-Path (Join-Path $AppDataDir "Cursor"))) { $guiFound.Add("Cursor") } if ((Test-Path (Join-Path $UserHome ".codeium\windsurf")) -or (Test-Path (Join-Path $LocalAppDataDir "Programs\Windsurf"))) { $guiFound.Add("Windsurf") } if (Test-Path (Join-Path $AppDataDir "CherryStudio")) { $guiFound.Add("Cherry Studio") } if ((Test-Path (Join-Path $UserHome ".vscode\extensions")) -or (Test-Path (Join-Path $UserHome ".cursor\extensions"))) { $guiFound.Add("Cline / Roo Code") } if (Test-Path (Join-Path $AppDataDir "Claude")) { $guiFound.Add("Claude Desktop") } if ($guiFound.Count -gt 0) { $GuiList.Add((Get-Msg "gui_found" @($guiFound -join ", "))) $GuiList.Add((Get-Msg "gui_url" @($BaseUrl))) $GuiList.Add((Get-Msg "gui_key" @((Mask-Key $Key)))) } } Write-Host "" Write-Tone (Get-Msg "step2_head") "Cyan" if ($UpdatedList.Count -gt 0) { Write-Tone (Get-Msg "done_list" @($UpdatedList.Count)) "White" $maxW = 0 foreach ($row in $UpdatedList) { if ($row.Target.Length -gt $maxW) { $maxW = $row.Target.Length } } foreach ($row in $UpdatedList) { $padTarget = $row.Target.PadRight($maxW) $tag = if ($row.Dry) { "[dry-run] " } else { "" } Write-Tone (" [OK] {0}{1} -> {2}" -f $tag, $padTarget, $row.Detail) "Green" } } else { Write-Tone (Get-Msg "none_found") "DarkGray" } if ($SkippedTargets.Count -gt 0) { Write-Tone (Get-Msg "skipped_list" @($SkippedTargets.Count, ($SkippedTargets -join ", "))) "DarkGray" } if ($WarningList.Count -gt 0 -or $GuiList.Count -gt 0 -or (-not $DryRun -and -not $Uninstall)) { Write-Host "" Write-Tone (Get-Msg "step3_head") "Cyan" } if ($WarningList.Count -gt 0) { Write-Tone (Get-Msg "warnings_head") "Yellow" foreach ($w in $WarningList) { Write-Tone " [!] $w" "Yellow" } } if ($GuiList.Count -gt 0) { Write-Tone (Get-Msg "gui_head") "Cyan" foreach ($g in $GuiList) { Write-Tone $g "Gray" } Write-Tone (Get-Msg "gui_tail") "Cyan" } if (-not $DryRun -and -not $Uninstall) { Write-Tone (Get-Msg "next_head") "White" $stepIdx = 1 Write-Tone (Get-Msg "next_1" @($stepIdx)) "Gray" $stepIdx++ if ($ConfiguredTargets.ContainsKey("Claude Code")) { Write-Tone (Get-Msg "next_2" @($stepIdx)) "Gray" $stepIdx++ } if ($ConfiguredTargets.ContainsKey("DSH")) { Write-Tone (Get-Msg "next_3" @($stepIdx)) "Gray" $stepIdx++ } if ($ConfiguredTargets.ContainsKey("WorkBuddy")) { Write-Tone (Get-Msg "next_wb" @($stepIdx)) "Yellow" $stepIdx++ } Write-Tone (Get-Msg "next_un") "DarkGray" } Write-Host ""