# Claude Desktop Universal Installer for Self-Hosted New API (Windows) # Default Gateway: https://api.chuhai365.cc # Supports: Windows PowerShell 5.1 & PowerShell 7 (x64 / x86 / ARM64) # Supports: Local -File, double-click .cmd, and remote "irm | iex" # # Quick usage (remote one-liner): # $env:NEWAPI_API_KEY='sk-xxx'; irm https://claude.chuhai365.cc/desktop-install.ps1 | iex # irm https://claude.chuhai365.cc/desktop-install.ps1 | iex # & ([scriptblock]::Create((irm https://claude.chuhai365.cc/desktop-install.ps1))) -ApiKey 'sk-xxx' # # Local usage: # powershell -NoProfile -ExecutionPolicy Bypass -File .\ClaudeDesktop-NewAPI.ps1 -ApiKey 'sk-xxx' # powershell -NoProfile -ExecutionPolicy Bypass -File .\ClaudeDesktop-NewAPI.ps1 -Preview # powershell -NoProfile -ExecutionPolicy Bypass -File .\ClaudeDesktop-NewAPI.ps1 -Status # powershell -NoProfile -ExecutionPolicy Bypass -File .\ClaudeDesktop-NewAPI.ps1 -Uninstall # # Note: Pure ASCII source (no UTF-8 BOM) so Windows PowerShell 5.1 parses it safely # both locally (-File under GBK/ANSI codepage) and remotely (irm | iex without charset). # No top-level param() block so "irm ... | iex" never fails with a ParserError. Set-StrictMode -Version 1.0 $ErrorActionPreference = 'Stop' try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) } catch { } try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 } catch { } try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 12288 } catch { } # ---------------------------------------------------------------- Defaults & CLI parsing $script:ScriptVersion = '2.0.0' $script:DefaultBaseUrl = 'https://api.chuhai365.cc' $script:DefaultDisplayName = 'Chuhai365' $script:PolicySubPath = 'SOFTWARE\Policies\Claude' $script:MinVersion3p = '1.2581.0' $script:MinVersionFull = '2.19675.0' $script:BypassMinVersion = '2.42304.0' $script:DownloadUrl = 'https://claude.com/download' # Known Claude Desktop 3P policy values that belong to gateway/3P setups. # We only touch values in our plan or conflicting 3P keys from previous installers; # unrelated enterprise GPO values (e.g. forceLoginOrgUUID) are never deleted. $script:Conflicting3pKeys = @( 'inferenceCredentialHelper', 'inferenceCredentialHelperTtlSec', 'inferenceIdpClientId', 'inferenceIdpIssuer', 'inferenceIdpScopes', 'inferenceBedrockRegion', 'inferenceVertexRegion', 'chatTabEnabled', 'chatAdvancedFileAnalysisEnabled', 'coworkTabEnabled' ) $script:Opt = [pscustomobject]@{ ApiKey = '' BaseUrl = if ($env:NEWAPI_BASE_URL) { [string]$env:NEWAPI_BASE_URL } else { $script:DefaultBaseUrl } DisplayName = if ($env:NEWAPI_DISPLAY_NAME) { [string]$env:NEWAPI_DISPLAY_NAME } else { $script:DefaultDisplayName } Models = @() Folders = @() Preview = $false Status = $false Uninstall = $false SwitchToOfficial = $false SwitchToGateway = $false CurrentUser = $false NoRestart = $false NoProbe = $false Offline = $false KeepPermissionPrompts = $false KeepAutoMode = $false Prefer1M = $false AllowAutoUpdates = $false RestrictCoworkNetwork = $false NoElevate = $false AssumeYes = $false Pause = $false Quiet = $false LoadOnly = $false Help = $false BadArgs = @() } if ($env:NEWAPI_YES -match '^(?i)(1|true|yes)$') { $script:Opt.AssumeYes = $true } if ($env:NEWAPI_QUIET -match '^(?i)(1|true|yes)$') { $script:Opt.Quiet = $true } if ($env:NEWAPI_CURRENT_USER -match '^(?i)(1|true|yes)$') { $script:Opt.CurrentUser = $true } if ($env:NEWAPI_OFFLINE -match '^(?i)(1|true|yes)$') { $script:Opt.Offline = $true } if ($env:NEWAPI_NO_PROBE -match '^(?i)(1|true|yes)$') { $script:Opt.NoProbe = $true } if ($env:NEWAPI_PREFER_1M -match '^(?i)(1|true|yes)$') { $script:Opt.Prefer1M = $true } function Parse-CliArgs([object[]]$RawArgs) { if (-not $RawArgs -or $RawArgs.Count -eq 0) { return } for ($i = 0; $i -lt $RawArgs.Count; $i++) { $arg = [string]$RawArgs[$i] if ([string]::IsNullOrWhiteSpace($arg)) { continue } # Support -Key:value or -Key=value forms as well as "-Key value" $name = $arg $inlineVal = $null if ($arg -match '^(--?[A-Za-z0-9_-]+)[:=](.*)$') { $name = $Matches[1] $inlineVal = $Matches[2] } switch -Regex ($name) { '^--?(?i)(ApiKey|Key)$' { if ($null -ne $inlineVal) { $script:Opt.ApiKey = $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.ApiKey = [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)(BaseUrl|Gateway|Url)$' { if ($null -ne $inlineVal) { $script:Opt.BaseUrl = $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.BaseUrl = [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)DisplayName$' { if ($null -ne $inlineVal) { $script:Opt.DisplayName = $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.DisplayName = [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)Models?$' { if ($null -ne $inlineVal) { $script:Opt.Models += $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.Models += [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)Folders?$' { if ($null -ne $inlineVal) { $script:Opt.Folders += $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.Folders += [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)(Preview|DryRun|WhatIf)$' { $script:Opt.Preview = $true } '^--?(?i)(Apply|Install|StopClaude)$' { <# default install behavior; accepted for compatibility #> } '^--?(?i)Status$' { $script:Opt.Status = $true } '^--?(?i)Uninstall$' { $script:Opt.Uninstall = $true } '^--?(?i)(SwitchToOfficial|Logout|1p)$' { $script:Opt.SwitchToOfficial = $true } '^--?(?i)(SwitchToGateway|Login|3p)$' { $script:Opt.SwitchToGateway = $true } '^--?(?i)CurrentUser$' { $script:Opt.CurrentUser = $true } '^--?(?i)(NoRestart|KeepRunning)$' { $script:Opt.NoRestart = $true } '^--?(?i)Probe$' { $script:Opt.NoProbe = $false } '^--?(?i)(NoProbe|SkipProbe)$' { $script:Opt.NoProbe = $true } '^--?(?i)(Offline|SkipCheck)$' { $script:Opt.Offline = $true } '^--?(?i)KeepPermissionPrompts$' { $script:Opt.KeepPermissionPrompts = $true } '^--?(?i)KeepAutoMode$' { $script:Opt.KeepAutoMode = $true } '^--?(?i)Prefer1M$' { $script:Opt.Prefer1M = $true } '^--?(?i)AllowAutoUpdates$' { $script:Opt.AllowAutoUpdates = $true } '^--?(?i)RestrictCoworkNetwork$' { $script:Opt.RestrictCoworkNetwork = $true } '^--?(?i)NoElevate$' { $script:Opt.NoElevate = $true } '^--?(?i)(Yes|Y)$' { $script:Opt.AssumeYes = $true } '^--?(?i)Pause$' { $script:Opt.Pause = $true } '^--?(?i)Quiet$' { $script:Opt.Quiet = $true } '^--?(?i)LoadOnly$' { $script:Opt.LoadOnly = $true } '^--?(?i)(Help|H|\?)$' { $script:Opt.Help = $true } default { $script:Opt.BadArgs += $arg } } } } # ---------------------------------------------------------------- Paths (folder-redirection safe) function Resolve-SpecialPath([string]$Kind, [string]$FallbackEnv, [string]$FallbackSub) { try { $p = [Environment]::GetFolderPath($Kind) if (-not [string]::IsNullOrWhiteSpace($p)) { return $p } } catch { } if ($FallbackEnv) { $ev = [Environment]::GetEnvironmentVariable($FallbackEnv) if (-not [string]::IsNullOrWhiteSpace($ev)) { return $ev } } $homeDir = [Environment]::GetEnvironmentVariable('USERPROFILE') if (-not $homeDir) { $homeDir = $env:USERPROFILE } if ($FallbackSub -and $homeDir) { return (Join-Path $homeDir $FallbackSub) } return [string]$homeDir } $script:UserProfileDir = Resolve-SpecialPath 'UserProfile' 'USERPROFILE' '' $script:LocalAppData = Resolve-SpecialPath 'LocalApplicationData' 'LOCALAPPDATA' 'AppData\Local' $script:RoamingAppData = Resolve-SpecialPath 'ApplicationData' 'APPDATA' 'AppData\Roaming' $script:C3pDir = Join-Path $script:LocalAppData 'Claude-3p' $script:ConfigFile = Join-Path $script:C3pDir 'claude_desktop_config.json' $script:StateDir = Join-Path $script:C3pDir '.newapi-gateway' $script:StateFile = Join-Path $script:StateDir 'state.json' # ---------------------------------------------------------------- Output helpers (UTF-8 safe via \uXXXX) function U([string]$Escaped) { if ([string]::IsNullOrEmpty($Escaped)) { return '' } return [regex]::Unescape($Escaped) } function Say([string]$m) { Write-Host (" " + $m) } function Say-Step([string]$m) { Write-Host ''; Write-Host ("==> " + $m) -ForegroundColor Cyan } function Say-Ok([string]$m) { Write-Host (" [OK] " + $m) -ForegroundColor Green } function Say-Warn([string]$m) { Write-Host (" [!] " + $m) -ForegroundColor Yellow } function Say-Err([string]$m) { Write-Host (" [X] " + $m) -ForegroundColor Red } function Fail([string]$m) { throw ('NEWAPI_FAIL::' + $m) } function Done([string]$m) { if ($m) { Say-Ok $m }; throw 'NEWAPI_DONE::' } function Mask-Secret([string]$s) { if ([string]::IsNullOrEmpty($s)) { return (U '(\u672a\u63d0\u4f9b)') } if ($s.Length -le 12) { return '****' } return ($s.Substring(0, 8) + '...' + $s.Substring($s.Length - 4)) } function Test-IsAdmin { try { $id = [Security.Principal.WindowsIdentity]::GetCurrent() return (New-Object Security.Principal.WindowsPrincipal($id)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } catch { return $false } } function Get-CurrentSid { try { return [string]([Security.Principal.WindowsIdentity]::GetCurrent().User.Value) } catch { return '' } } function Test-InteractiveConsole { try { if ($script:Opt.Quiet) { return $false } if (-not [Environment]::UserInteractive) { return $false } if ([Console]::IsInputRedirected) { return $false } return $true } catch { return $false } } function Confirm-YesNo([string]$Prompt, [bool]$DefaultYes = $true) { if ($script:Opt.AssumeYes) { return $true } if (-not (Test-InteractiveConsole)) { return $null } $suffix = if ($DefaultYes) { ' [Y/n]: ' } else { ' [y/N]: ' } $ans = '' try { $ans = Read-Host ($Prompt + $suffix) } catch { return $null } $ans = ([string]$ans).Trim() if ([string]::IsNullOrEmpty($ans)) { return $DefaultYes } if ($ans -match '^(?i)(y|yes)$') { return $true } if ($ans -match '^(?i)(n|no)$') { return $false } return $DefaultYes } function Compare-DottedVersion([string]$a, [string]$b) { if (-not $a -or -not $b) { return $null } $pa = @(); $pb = @() foreach ($s in ($a.Trim() -split '\.')) { $n = 0 if ([int]::TryParse($s, [ref]$n)) { $pa += $n } else { return $null } } foreach ($s in ($b.Trim() -split '\.')) { $n = 0 if ([int]::TryParse($s, [ref]$n)) { $pb += $n } else { return $null } } if ($pa.Count -eq 0 -or $pb.Count -eq 0) { return $null } $len = [Math]::Max($pa.Count, $pb.Count) for ($i = 0; $i -lt $len; $i++) { $x = if ($i -lt $pa.Count) { $pa[$i] } else { 0 } $y = if ($i -lt $pb.Count) { $pb[$i] } else { 0 } if ($x -lt $y) { return -1 } if ($x -gt $y) { return 1 } } return 0 } function Test-VersionAtLeast([string]$Version, [string]$Minimum) { $cmp = Compare-DottedVersion $Version $Minimum if ($null -eq $cmp) { return $false } return ($cmp -ge 0) } function Get-NativeRegExePath { if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { $sysnative = Join-Path $env:WINDIR 'Sysnative\reg.exe' if (Test-Path -LiteralPath $sysnative -PathType Leaf) { return $sysnative } } $sys32 = Join-Path $env:WINDIR 'System32\reg.exe' if (Test-Path -LiteralPath $sys32 -PathType Leaf) { return $sys32 } return 'reg.exe' } function Get-64BitPowerShellPath { # Prefer 64-bit host so elevated child never runs inside WOW64. if ([Environment]::Is64BitOperatingSystem -and -not [Environment]::Is64BitProcess) { $sysnativePs = Join-Path $env:WINDIR 'Sysnative\WindowsPowerShell\v1.0\powershell.exe' if (Test-Path -LiteralPath $sysnativePs -PathType Leaf) { return $sysnativePs } } try { $curExe = [string](Get-Process -Id $PID -ErrorAction Stop).Path if ($curExe -and (Test-Path -LiteralPath $curExe -PathType Leaf)) { return $curExe } } catch { } $ps51 = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' if (Test-Path -LiteralPath $ps51 -PathType Leaf) { return $ps51 } return 'powershell.exe' } function Show-Usage { $title = U 'Claude \u684c\u9762\u7248 New API \u901a\u7528\u63a5\u5165\u811a\u672c v' Write-Host ($title + $script:ScriptVersion) -ForegroundColor Cyan Write-Host ((U ' \u9ed8\u8ba4\u7f51\u5173: ') + $script:DefaultBaseUrl) Write-Host '' Write-Host (U '\u5e38\u7528\u7528\u6cd5:') -ForegroundColor Yellow Write-Host (U ' 1) \u4e00\u952e\u5b89\u88c5 (\u5e26\u5ba2\u6237\u5bc6\u94a5):') Write-Host ' powershell -NoProfile -ExecutionPolicy Bypass -File .\ClaudeDesktop-NewAPI.ps1 -ApiKey sk-xxx' Write-Host (U ' 2) \u8fdc\u7a0b\u4e00\u6761\u547d\u4ee4 (\u590d\u5236\u7ed9\u5ba2\u6237):') Write-Host ' $env:NEWAPI_API_KEY=''sk-xxx''; irm https://claude.chuhai365.cc/desktop-install.ps1 | iex' Write-Host (U ' 3) \u53ea\u9884\u89c8\u4e0d\u5199\u5165: -Preview') Write-Host (U ' 4) \u67e5\u770b\u5f53\u524d\u72b6\u6001: -Status') Write-Host (U ' 5) \u5207\u56de\u5b98\u65b9 Claude.ai: -SwitchToOfficial (\u6216 -Logout)') Write-Host (U ' 6) \u5207\u56de New API \u7f51\u5173: -SwitchToGateway (\u6216 -Login)') Write-Host (U ' 7) \u5b8c\u5168\u5378\u8f7d\u5e76\u8fd8\u539f: -Uninstall') Write-Host '' Write-Host (U '\u53ef\u9009\u53c2\u6570:') -ForegroundColor Yellow Write-Host (U ' -ApiKey \u6307\u5b9a New API \u5bc6\u94a5 (\u4e5f\u53ef\u8bbe\u7f6e\u73af\u5883\u53d8\u91cf NEWAPI_API_KEY)') Write-Host ((U ' -BaseUrl \u81ea\u5b9a\u4e49\u7f51\u5173\u5730\u5740 (\u9ed8\u8ba4 ') + $script:DefaultBaseUrl + ')') Write-Host ((U ' -DisplayName App \u5de6\u4e0b\u89d2\u663e\u793a\u540d\u79f0 (\u9ed8\u8ba4 ') + $script:DefaultDisplayName + ')') Write-Host (U ' -Models \u624b\u52a8\u6307\u5b9a\u6a21\u578b ID \u6e05\u5355 (\u9ed8\u8ba4\u81ea\u52a8\u4ece /v1/models \u83b7\u53d6)') Write-Host (U ' -Folder \u9884\u7f6e\u5de5\u4f5c\u533a\u76ee\u5f55 (\u53ef\u91cd\u590d\u4f20\u5165\u591a\u4e2a)') Write-Host (U ' -CurrentUser \u4ec5\u5199\u5165\u5f53\u524d\u7528\u6237 HKCU (\u9ed8\u8ba4\u5199\u5165\u6574\u673a HKLM)') Write-Host (U ' -NoRestart \u4e0d\u81ea\u52a8\u91cd\u542f Claude \u684c\u9762\u7248') Write-Host (U ' -NoProbe \u8df3\u8fc7 /v1/messages \u5b9e\u6d4b\u63a2\u9488') Write-Host (U ' -Offline \u79bb\u7ebf\u6a21\u5f0f (\u8df3\u8fc7\u8054\u7f51\u6821\u9a8c\u5e76\u4f7f\u7528\u5185\u7f6e\u6a21\u578b\u5217\u8868)') Write-Host (U ' -Prefer1M \u9ed8\u8ba4\u4f18\u5148\u663e\u793a 1M \u4e0a\u4e0b\u6587\u6a21\u578b') Write-Host (U ' -KeepPermissionPrompts \u4e0d\u9884\u5199 Code \u9ed8\u8ba4 Bypass \u6743\u9650\u6a21\u5f0f') Write-Host (U ' -KeepAutoMode \u4fdd\u7559 Code Auto \u6a21\u5f0f (\u4e0d\u5173\u95ed autoModeEnabled)') Write-Host (U ' -AllowAutoUpdates \u4e0d\u7981\u7528 Claude \u81ea\u52a8\u66f4\u65b0') Write-Host (U ' -RestrictCoworkNetwork \u4e0d\u653e\u5f00 Cowork / Code \u7f51\u7edc\u51fa\u7f51\u9650\u5236') Write-Host (U ' -NoElevate \u4e0d\u81ea\u52a8\u5f39\u51fa UAC \u7ba1\u7406\u5458\u63d0\u6743') Write-Host (U ' -Yes \u81ea\u52a8\u786e\u8ba4\u4ea4\u4e92\u63d0\u793a') } # ---------------------------------------------------------------- Surgical Raw-Span JSON Editor # Never re-serializes customer claude_desktop_config.json via PS 5.1 ConvertTo-Json, # because PS 5.1 JavaScriptSerializer corrupts backslashes right after non-ASCII chars # (e.g. C:\Users\\mcp -> invalid JSON) and mangles user mcpServers. function Skip-JsonSpace([string]$s, [int]$i) { while ($i -lt $s.Length -and (' ' + "`t`r`n").IndexOf($s[$i]) -ge 0) { $i++ } return $i } function Skip-JsonString([string]$s, [int]$i) { if ($i -ge $s.Length -or $s[$i] -ne [char]34) { return -1 } $i++ while ($i -lt $s.Length) { $ch = $s[$i] if ([int]$ch -lt 32) { return -1 } if ($ch -eq [char]92) { $i++ if ($i -ge $s.Length) { return -1 } $esc = $s[$i] if ($esc -ceq 'u') { if (($i + 4) -ge $s.Length) { return -1 } if ($s.Substring($i + 1, 4) -cnotmatch '^[0-9a-fA-F]{4}$') { return -1 } $i += 4 } elseif ('"\/bfnrt'.IndexOf($esc) -lt 0) { return -1 } $i++ continue } if ($ch -eq [char]34) { return ($i + 1) } $i++ } return -1 } function Skip-JsonValue([string]$s, [int]$i, [int]$depth = 0) { if ($depth -gt 256) { return -1 } $i = Skip-JsonSpace $s $i if ($i -ge $s.Length) { return -1 } $ch = $s[$i] if ($ch -eq [char]34) { return (Skip-JsonString $s $i) } if ($ch -eq '{' -or $ch -eq '[') { $isObj = ($ch -eq '{') $close = if ($isObj) { '}' } else { ']' } $i = Skip-JsonSpace $s ($i + 1) if ($i -lt $s.Length -and $s[$i] -eq $close) { return ($i + 1) } while ($true) { if ($isObj) { $i = Skip-JsonString $s $i if ($i -lt 0) { return -1 } $i = Skip-JsonSpace $s $i if ($i -ge $s.Length -or $s[$i] -ne ':') { return -1 } $i++ } $i = Skip-JsonValue $s $i ($depth + 1) if ($i -lt 0) { return -1 } $i = Skip-JsonSpace $s $i if ($i -ge $s.Length) { return -1 } if ($s[$i] -eq $close) { return ($i + 1) } if ($s[$i] -ne ',') { return -1 } $i = Skip-JsonSpace $s ($i + 1) if ($i -ge $s.Length -or $s[$i] -eq $close) { return -1 } } } foreach ($lit in @('true', 'false', 'null')) { if (($i + $lit.Length) -le $s.Length -and $s.Substring($i, $lit.Length) -ceq $lit) { return ($i + $lit.Length) } } $m = [regex]::Match($s.Substring($i), '^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?') if ($m.Success) { return ($i + $m.Length) } return -1 } function Test-JsonObjectText([string]$s) { if ([string]::IsNullOrWhiteSpace($s)) { return $false } $i = 0 if ($s[0] -eq [char]0xFEFF) { $i = 1 } $i = Skip-JsonSpace $s $i if ($i -ge $s.Length -or $s[$i] -ne '{') { return $false } $end = Skip-JsonValue $s $i 0 if ($end -lt 0) { return $false } return ((Skip-JsonSpace $s $end) -eq $s.Length) } function Repair-JsonInvalidEscapes([string]$s) { if ([string]::IsNullOrEmpty($s)) { return $s } if ($s[0] -eq [char]0xFEFF) { $s = $s.Substring(1) } $sb = New-Object System.Text.StringBuilder ($s.Length + 16) $inStr = $false $i = 0 $n = $s.Length $hex = '0123456789abcdefABCDEF' while ($i -lt $n) { $ch = $s[$i] if (-not $inStr) { [void]$sb.Append($ch) if ($ch -eq [char]34) { $inStr = $true } $i++; continue } if ($ch -eq [char]92) { if (($i + 1) -ge $n) { [void]$sb.Append('\\'); $i++; continue } $nxt = $s[$i + 1] if ('"\/bfnrt'.IndexOf($nxt) -ge 0) { [void]$sb.Append($ch); [void]$sb.Append($nxt); $i += 2; continue } if ($nxt -ceq 'u' -and ($i + 5) -lt $n) { $ok = $true foreach ($k in 2, 3, 4, 5) { if ($hex.IndexOf($s[$i + $k]) -lt 0) { $ok = $false; break } } if ($ok) { [void]$sb.Append($s.Substring($i, 6)); $i += 6; continue } } # Invalid escape like \C or \U from prior PS 5.1 bug -> double the backslash [void]$sb.Append('\\'); $i++; continue } if ($ch -eq [char]34) { $inStr = $false } [void]$sb.Append($ch) $i++ } return $sb.ToString() } function Decode-JsonString([string]$raw) { if ([string]::IsNullOrEmpty($raw) -or $raw.Length -lt 2 -or $raw[0] -ne [char]34 -or $raw[$raw.Length - 1] -ne [char]34) { throw 'Not a JSON string literal' } $sb = New-Object System.Text.StringBuilder for ($i = 1; $i -lt ($raw.Length - 1); $i++) { $ch = $raw[$i] if ($ch -ne [char]92) { [void]$sb.Append($ch); continue } $i++ switch -CaseSensitive ([string]$raw[$i]) { 'u' { [void]$sb.Append([char][Convert]::ToInt32($raw.Substring($i + 1, 4), 16)); $i += 4 } 'b' { [void]$sb.Append([char]8) } 'f' { [void]$sb.Append([char]12) } 'n' { [void]$sb.Append([char]10) } 'r' { [void]$sb.Append([char]13) } 't' { [void]$sb.Append([char]9) } default { [void]$sb.Append($raw[$i]) } } } return $sb.ToString() } function Encode-JsonString([string]$text) { $sb = New-Object System.Text.StringBuilder [void]$sb.Append([char]34) foreach ($ch in $text.ToCharArray()) { $code = [int]$ch if ($ch -eq [char]34 -or $ch -eq [char]92) { [void]$sb.Append([char]92); [void]$sb.Append($ch) } elseif ($code -eq 8) { [void]$sb.Append('\b') } elseif ($code -eq 12) { [void]$sb.Append('\f') } elseif ($code -eq 10) { [void]$sb.Append('\n') } elseif ($code -eq 13) { [void]$sb.Append('\r') } elseif ($code -eq 9) { [void]$sb.Append('\t') } elseif ($code -lt 32) { [void]$sb.Append(('\u{0:x4}' -f $code)) } else { [void]$sb.Append($ch) } } [void]$sb.Append([char]34) return $sb.ToString() } function Get-JsonObjectMembers([string]$s) { $list = @() $i = 0 if ($s.Length -gt 0 -and $s[0] -eq [char]0xFEFF) { $i = 1 } $i = Skip-JsonSpace $s $i if ($i -ge $s.Length -or $s[$i] -ne '{') { throw 'JSON value is not an object' } $i = Skip-JsonSpace $s ($i + 1) while ($i -lt $s.Length -and $s[$i] -ne '}') { $start = $i $keyEnd = Skip-JsonString $s $i if ($keyEnd -lt 0) { throw 'Invalid JSON key' } $key = Decode-JsonString ($s.Substring($i, $keyEnd - $i)) $i = Skip-JsonSpace $s $keyEnd if ($i -ge $s.Length -or $s[$i] -ne ':') { throw 'Missing JSON colon' } $valStart = Skip-JsonSpace $s ($i + 1) $valEnd = Skip-JsonValue $s $valStart 0 if ($valEnd -lt 0) { throw 'Invalid JSON value' } $sep = Skip-JsonSpace $s $valEnd $list += [pscustomobject]@{ Key = $key Start = $start ValueStart = $valStart End = $valEnd Separator = $sep Raw = $s.Substring($valStart, $valEnd - $valStart) } if ($sep -ge $s.Length) { throw 'Unclosed JSON object' } if ($s[$sep] -eq '}') { return $list } if ($s[$sep] -ne ',') { throw 'Invalid JSON separator' } $i = Skip-JsonSpace $s ($sep + 1) } return $list } function Get-JsonMember([string]$s, [string]$Key) { $found = @(Get-JsonObjectMembers $s | Where-Object { [string]::Equals($_.Key, $Key, [StringComparison]::Ordinal) }) if ($found.Count -gt 1) { throw ('Duplicate JSON key: ' + $Key) } if ($found.Count -eq 1) { return $found[0] } return $null } function Get-JsonPathRaw([string]$s, [string[]]$Path) { $raw = $s foreach ($k in $Path) { if (-not (Test-JsonObjectText $raw)) { return $null } $m = Get-JsonMember $raw $k if ($null -eq $m) { return $null } $raw = [string]$m.Raw } return $raw } function Set-JsonPathRaw([string]$s, [string[]]$Path, [string]$RawValue, [switch]$Remove) { if (-not $Path -or $Path.Count -eq 0) { throw 'Empty JSON path' } $members = @(Get-JsonObjectMembers $s) $member = Get-JsonMember $s $Path[0] if ($Path.Count -gt 1) { if ($null -eq $member -and $Remove) { return $s } $child = if ($null -eq $member) { '{}' } else { [string]$member.Raw } if (-not (Test-JsonObjectText $child)) { if ($Remove) { return $s } $child = '{}' } $subPath = [string[]]$Path[1..($Path.Count - 1)] $newChild = Set-JsonPathRaw $child $subPath $RawValue -Remove:$Remove if ($Remove -and $null -ne $member) { # Drop empty intermediate objects created solely during cleanup if now empty if (@(Get-JsonObjectMembers $newChild).Count -eq 0 -and $newChild -cne $child) { return (Set-JsonPathRaw $s @($Path[0]) '' -Remove) } } $RawValue = $newChild } elseif ($Remove) { if ($null -eq $member) { return $s } if ($s[$member.Separator] -eq ',') { return $s.Remove($member.Start, $member.Separator + 1 - $member.Start) } $prev = $null foreach ($peer in $members) { if ($peer.Start -lt $member.Start) { $prev = $peer } } if ($null -ne $prev) { return $s.Remove($prev.Separator, $member.End - $prev.Separator) } return $s.Remove($member.Start, $member.End - $member.Start) } if ($null -ne $member) { return ($s.Substring(0, $member.ValueStart) + $RawValue + $s.Substring($member.End)) } $brace = $s.IndexOf('{') $comma = if ($members.Count -gt 0) { ',' } else { '' } return ($s.Substring(0, $brace + 1) + (Encode-JsonString $Path[0]) + ':' + $RawValue + $comma + $s.Substring($brace + 1)) } function Write-TextFileAtomic([string]$Path, [string]$Text, [bool]$Utf8Bom = $false) { $dir = Split-Path -Parent $Path if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } $tmp = $Path + '.' + [Guid]::NewGuid().ToString('N') + '.tmp' $made = $false try { $enc = New-Object System.Text.UTF8Encoding($Utf8Bom) $bytes = $enc.GetBytes($Text) $fs = [IO.File]::Open($tmp, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) $made = $true try { if ($Utf8Bom) { $preamble = $enc.GetPreamble() if ($preamble.Length -gt 0) { $fs.Write($preamble, 0, $preamble.Length) } } $fs.Write($bytes, 0, $bytes.Length) $fs.Flush() } finally { $fs.Dispose() } if ([IO.File]::Exists($Path)) { # Must pass [NullString]::Value (not $null, which PS coerces to "") try { [IO.File]::Replace($tmp, $Path, [NullString]::Value) } catch { [IO.File]::Delete($Path); [IO.File]::Move($tmp, $Path) } } else { [IO.File]::Move($tmp, $Path) } $made = $false } finally { if ($made -and [IO.File]::Exists($tmp)) { try { [IO.File]::Delete($tmp) } catch { } } } } function Read-Utf8TextStrict([string]$Path) { $bytes = [IO.File]::ReadAllBytes($Path) $text = [Text.Encoding]::UTF8.GetString($bytes) if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) } return $text } # ---------------------------------------------------------------- Claude Desktop Discovery & Lifecycle function Get-ClassicClaudeExes { $found = @() $pf64 = [Environment]::GetEnvironmentVariable('ProgramW6432') $pf = [Environment]::GetEnvironmentVariable('ProgramFiles') $pf86 = [Environment]::GetEnvironmentVariable('ProgramFiles(x86)') $candidates = @() if ($script:LocalAppData) { $candidates += (Join-Path $script:LocalAppData 'AnthropicClaude\Claude.exe') $candidates += (Join-Path $script:LocalAppData 'AnthropicClaude\app-*\Claude.exe') $candidates += (Join-Path $script:LocalAppData 'Programs\Claude\Claude.exe') $candidates += (Join-Path $script:LocalAppData 'Programs\Claude\app-*\Claude.exe') } foreach ($dir in @($pf64, $pf, $pf86)) { if ([string]::IsNullOrWhiteSpace($dir)) { continue } $c = Join-Path $dir 'Claude\Claude.exe' if ($candidates -notcontains $c) { $candidates += $c } } foreach ($pattern in $candidates) { foreach ($item in @(Get-Item -Path $pattern -ErrorAction SilentlyContinue)) { if ($item -and -not $item.PSIsContainer) { $full = [IO.Path]::GetFullPath([string]$item.FullName) if ($found -notcontains $full) { $found += $full } } } } return $found } function Find-ClaudeDesktop { $app = [pscustomobject]@{ Installed = $false Exe = '' AppId = '' Packaged = $false PackageFamilyName = '' InstallLocation = '' AppVersion = '' Kind = '' Roots = @() ClassicExes = @() DualInstall = $false } $classicExes = @(Get-ClassicClaudeExes) $app.ClassicExes = $classicExes $classicFirst = if ($classicExes.Count -gt 0) { Get-Item -LiteralPath $classicExes[0] -ErrorAction SilentlyContinue } else { $null } $appId = '' try { $startApp = @(Get-StartApps -ErrorAction Stop) | Where-Object { $_.Name -match '(?i)^Claude( Desktop)?$' -or $_.AppID -match '(?i)(Anthropic.*Claude|Claude.*Anthropic)' } | Select-Object -First 1 if ($startApp -and $startApp.AppID) { $appId = [string]$startApp.AppID $app.Installed = $true } } catch { } $pkg = $null try { $all = @(Get-AppxPackage -ErrorAction Stop) $pkg = @($all | Where-Object { ([string]$_.Name -match '(?i)(Anthropic.*Claude|Claude.*Anthropic|^Claude$)') -or ([string]$_.PackageFamilyName -match '(?i)(Anthropic.*Claude|Claude.*Anthropic|^Claude_)') } | Sort-Object Version -Descending) | Select-Object -First 1 } catch { $pkg = $null } $roots = @() if ($pkg) { $app.Installed = $true $app.Packaged = $true $app.Kind = 'MSIX' $app.PackageFamilyName = [string]$pkg.PackageFamilyName $app.InstallLocation = [string]$pkg.InstallLocation $app.AppVersion = [string]$pkg.Version $applicationId = '' $applicationExe = '' try { $manifest = Get-AppxPackageManifest -Package $pkg -ErrorAction Stop $applications = @($manifest.Package.Applications.Application) $application = $applications | Where-Object { ([string]$_.Id -eq 'Claude') -or ([string]$_.Executable -match '(?i)(^|\\)Claude\.exe$') } | Select-Object -First 1 if (-not $application -and $applications.Count -eq 1) { $application = $applications[0] } if ($application) { $applicationId = [string]$application.Id $applicationExe = [string]$application.Executable } } catch { } if ($app.PackageFamilyName -and $applicationId) { $appId = $app.PackageFamilyName + '!' + $applicationId } foreach ($rel in @($applicationExe, 'app\Claude.exe')) { if ($app.Exe -or -not $rel -or -not $app.InstallLocation) { continue } $cand = Join-Path $app.InstallLocation $rel if (Test-Path -LiteralPath $cand -PathType Leaf) { $app.Exe = [IO.Path]::GetFullPath($cand) } } if ($app.InstallLocation) { $roots += [IO.Path]::GetFullPath($app.InstallLocation) } if ($classicExes.Count -gt 0) { $app.DualInstall = $true } } elseif ($classicFirst) { $app.Installed = $true $app.Packaged = $false $app.Kind = (U '\u4f20\u7edf\u5b89\u88c5') $app.Exe = [IO.Path]::GetFullPath([string]$classicFirst.FullName) try { $v = [string]$classicFirst.VersionInfo.ProductVersion if (-not $v) { $v = [string]$classicFirst.VersionInfo.FileVersion } $app.AppVersion = $v.Trim() } catch { } } # Include ALL classic roots too so dual-install stops both copies cleanly. foreach ($ce in $classicExes) { $d = Split-Path -Parent $ce if ((Split-Path -Leaf $d) -match '^app-') { $d = Split-Path -Parent $d } $r = [IO.Path]::GetFullPath($d) if ($roots -notcontains $r) { $roots += $r } } $app.Roots = @($roots) $app.AppId = $appId return $app } function Get-ConfigPaths($app) { $paths = @($script:ConfigFile) if ($app -and $app.Packaged -and $app.PackageFamilyName -and $script:LocalAppData) { $priv = Join-Path $script:LocalAppData ('Packages\{0}\LocalCache\Local\Claude-3p\claude_desktop_config.json' -f $app.PackageFamilyName) if ((Test-Path -LiteralPath $priv -PathType Leaf) -and ($paths -notcontains $priv)) { $paths += $priv } } return $paths } function Test-LegacyDataFolderPending { if (-not $script:RoamingAppData -or -not $script:C3pDir) { return $false } $legacy = Join-Path $script:RoamingAppData 'Claude-3p' if ([string]::Equals($legacy, $script:C3pDir, [StringComparison]::OrdinalIgnoreCase)) { return $false } return ((Test-Path -LiteralPath $legacy -PathType Container) -and -not (Test-Path -LiteralPath $script:C3pDir -PathType Container)) } function Get-ClaudeAppProcesses($app) { $state = [pscustomobject]@{ Target = @(); Unverified = 0; EnumerationFailed = $false } $roots = @($app.Roots | Where-Object { $_ }) if ($roots.Count -eq 0) { if ($app.Installed) { $state.EnumerationFailed = $true } return $state } try { $currentSession = [Diagnostics.Process]::GetCurrentProcess().SessionId $processes = @(Get-Process -ErrorAction Stop | Where-Object { $_.ProcessName -eq 'Claude' }) } catch { $state.EnumerationFailed = $true return $state } foreach ($p in $processes) { try { try { if ($null -ne $p.SessionId -and $p.SessionId -ne $currentSession) { continue } } catch { } if ($p.HasExited) { continue } $path = [string]$p.Path if ([string]::IsNullOrWhiteSpace($path)) { throw 'path unavailable' } $full = [IO.Path]::GetFullPath($path) foreach ($root in $roots) { $prefix = $root.TrimEnd('\', '/') + '\' if ($full.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { $state.Target += $p break } } } catch { try { $p.Refresh() } catch { } $exited = $false try { $exited = $p.HasExited } catch { } if (-not $exited) { $state.Unverified++ } } } return $state } function Stop-ClaudeApp($app) { $procs = Get-ClaudeAppProcesses $app foreach ($p in @($procs.Target)) { try { if (-not $p.HasExited) { $p.Kill() } } catch { } } $deadline = (Get-Date).AddSeconds(10) do { Start-Sleep -Milliseconds 300 $procs = Get-ClaudeAppProcesses $app } while (@($procs.Target).Count -gt 0 -and (Get-Date) -lt $deadline) return (@($procs.Target).Count -eq 0) } function Start-ClaudeApp($app, [string[]]$ExtraArgs = @()) { if ($app.Packaged -and $app.AppId -and $ExtraArgs.Count -eq 0) { try { Start-Process ('shell:AppsFolder\' + $app.AppId) -ErrorAction Stop; return $true } catch { } } if ($app.Packaged -and $ExtraArgs.Count -eq 0) { return $false } if ($app.Exe -and (Test-Path -LiteralPath $app.Exe -PathType Leaf)) { if ((Test-IsAdmin) -and $ExtraArgs.Count -eq 0 -and -not $app.Packaged) { # De-elevate classic EXE via Explorer so drag-and-drop works normally. $explorer = Join-Path $env:WINDIR 'explorer.exe' if (Test-Path -LiteralPath $explorer -PathType Leaf) { try { Start-Process -FilePath $explorer -ArgumentList ('"' + $app.Exe + '"') -ErrorAction Stop; return $true } catch { } } } try { if ($ExtraArgs.Count -gt 0) { Start-Process -FilePath $app.Exe -ArgumentList $ExtraArgs -ErrorAction Stop } else { Start-Process -FilePath $app.Exe -ErrorAction Stop } return $true } catch { } } if ($app.AppId) { try { Start-Process ('shell:AppsFolder\' + $app.AppId) -ErrorAction Stop; return $true } catch { } } return $false } # ---------------------------------------------------------------- App Log 3P Verification function Get-ClaudeLogCandidates($app) { $dirs = @() if ($app -and $app.Packaged -and $app.PackageFamilyName -and $script:LocalAppData) { $pkgBase = Join-Path $script:LocalAppData ('Packages\' + $app.PackageFamilyName + '\LocalCache') $dirs += (Join-Path $pkgBase 'Local') $dirs += (Join-Path $pkgBase 'Roaming') } if ($script:LocalAppData) { $dirs += $script:LocalAppData } if ($script:RoamingAppData) { $dirs += $script:RoamingAppData } $packagesRoot = Join-Path $script:LocalAppData 'Packages' if (Test-Path -LiteralPath $packagesRoot -PathType Container) { foreach ($d in @(Get-ChildItem -LiteralPath $packagesRoot -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '(?i)(^Claude_|Anthropic.*Claude|Claude.*Anthropic)' })) { $dirs += (Join-Path $d.FullName 'LocalCache\Local') $dirs += (Join-Path $d.FullName 'LocalCache\Roaming') } } $paths = @() foreach ($d in $dirs) { if ([string]::IsNullOrWhiteSpace($d)) { continue } foreach ($leaf in 'Claude-3p\logs\main.log', 'Claude\logs\main.log') { $p = Join-Path $d $leaf if ($paths -notcontains $p) { $paths += $p } } } return $paths } function Test-GatewayModeInLog($app, [datetime]$Since) { $result = [pscustomobject]@{ Active = $false Degraded = $false AnyLogFound = $false Log = '' Line = '' Timestamp = [datetime]::MinValue } $anyTime = ($Since -eq [datetime]::MinValue) $floor = if ($anyTime) { [datetime]::MinValue } else { [datetime]::new($Since.Year, $Since.Month, $Since.Day, $Since.Hour, $Since.Minute, $Since.Second, $Since.Kind) } foreach ($p in @(Get-ClaudeLogCandidates $app)) { if (-not (Test-Path -LiteralPath $p -PathType Leaf)) { continue } $result.AnyLogFound = $true $tail = @() try { $tail = @(Get-Content -LiteralPath $p -Tail 400 -ErrorAction Stop) } catch { continue } # Scan from newest to oldest so we always report the most recent startup. for ($i = $tail.Count - 1; $i -ge 0; $i--) { $text = [string]$tail[$i] $isStrong = ($text -match '\[custom-3p\]\s+3P mode active') $isHost = ($text -match '\[custom-3p\]\s+inference\s+apiHost=') if (-not $isStrong -and -not $isHost) { continue } $stamp = $null if ($text -match '^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') { try { $stamp = [datetime]::ParseExact($Matches[1], 'yyyy-MM-dd HH:mm:ss', [Globalization.CultureInfo]::InvariantCulture) } catch { $stamp = $null } } if (-not $anyTime -and ($null -eq $stamp -or $stamp -lt $floor)) { continue } $ts = if ($null -ne $stamp) { $stamp } else { [datetime]::MinValue } if (-not $result.Active -or $ts -ge $result.Timestamp) { $result.Active = $true $result.Log = $p $result.Line = $text.Trim() $result.Degraded = ($text -match '(?i)degraded') $result.Timestamp = $ts } break } } return $result } function Wait-GatewayModeConfirmed($app, [datetime]$Since, [int]$Seconds = 20) { $deadline = (Get-Date).AddSeconds($Seconds) do { $r = Test-GatewayModeInLog $app $Since if ($r.Active) { return $r } Start-Sleep -Seconds 2 } while ((Get-Date) -lt $deadline) return (Test-GatewayModeInLog $app $Since) } # ---------------------------------------------------------------- 64-bit Registry Policy Engine function Open-PolicyBaseKey([string]$HiveLabel) { $hive = if ($HiveLabel -eq 'HKLM') { [Microsoft.Win32.RegistryHive]::LocalMachine } else { [Microsoft.Win32.RegistryHive]::CurrentUser } $view = if ([Environment]::Is64BitOperatingSystem) { [Microsoft.Win32.RegistryView]::Registry64 } else { [Microsoft.Win32.RegistryView]::Default } return [Microsoft.Win32.RegistryKey]::OpenBaseKey($hive, $view) } function Get-PolicyTarget([string]$HiveLabel) { return [pscustomobject]@{ HiveLabel = $HiveLabel SubPath = $script:PolicySubPath WinPath = ($HiveLabel + '\' + $script:PolicySubPath) PsPath = ($HiveLabel + ':\' + $script:PolicySubPath) } } function Test-AccessDenied($exception) { $e = $exception while ($null -ne $e) { if ($e -is [System.Security.SecurityException] -or $e -is [System.UnauthorizedAccessException]) { return $true } $e = $e.InnerException } return $false } function Test-PolicyKeyState($Target) { $base = $null; $key = $null try { $base = Open-PolicyBaseKey $Target.HiveLabel $key = $base.OpenSubKey($Target.SubPath, $false) if ($null -eq $key) { return 'absent' } return 'present' } catch { return 'unknown' } finally { if ($key) { try { $key.Close() } catch { } } if ($base) { try { $base.Close() } catch { } } } } function Test-PolicyWritable($Target) { $base = $null try { $base = Open-PolicyBaseKey $Target.HiveLabel $sub = $Target.SubPath $exists = $false $k = $null try { $k = $base.OpenSubKey($sub, $false); $exists = ($null -ne $k) } catch { $exists = $false } finally { if ($k) { $k.Close() } } if ($exists) { $attempts = @( { param($b, $s) $b.OpenSubKey($s, $true) }, { param($b, $s) $b.OpenSubKey($s, [Microsoft.Win32.RegistryKeyPermissionCheck]::Default, [System.Security.AccessControl.RegistryRights]::SetValue) }, { param($b, $s) $b.OpenSubKey($s, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, ([System.Security.AccessControl.RegistryRights]::TakeOwnership -bor [System.Security.AccessControl.RegistryRights]::ChangePermissions -bor [System.Security.AccessControl.RegistryRights]::ReadKey)) } ) foreach ($fn in $attempts) { $tk = $null try { $tk = (& $fn $base $sub); return $true } catch { if (-not (Test-AccessDenied $_.Exception)) { return $true } } finally { if ($tk) { $tk.Close() } } } return $false } $ancestor = Split-Path -Parent $sub while ($true) { $ak = $null; $has = $false try { $ak = $base.OpenSubKey($ancestor, $false); $has = ($null -ne $ak) } catch { $has = $false } finally { if ($ak) { $ak.Close() } } if ($has) { $ck = $null try { $ck = $base.OpenSubKey($ancestor, [Microsoft.Win32.RegistryKeyPermissionCheck]::Default, [System.Security.AccessControl.RegistryRights]::CreateSubKey) return $true } catch { return (-not (Test-AccessDenied $_.Exception)) } finally { if ($ck) { $ck.Close() } } } if (-not $ancestor) { return $true } $ancestor = Split-Path -Parent $ancestor } } catch { return $false } finally { if ($base) { try { $base.Close() } catch { } } } } function Get-PolicyValueOnKey($Key, [string]$Name) { if ($null -eq $Key) { return $null } $actual = $null foreach ($n in @($Key.GetValueNames())) { if ($n -ieq $Name) { $actual = $n; break } } if ($null -eq $actual) { return $null } $data = $Key.GetValue($actual, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) return [pscustomobject]@{ Name = [string]$actual Kind = [string]$Key.GetValueKind($actual) Data = $data } } function Get-PolicyValues($Target) { $list = @() $base = $null; $key = $null try { $base = Open-PolicyBaseKey $Target.HiveLabel $key = $base.OpenSubKey($Target.SubPath, $false) if ($null -eq $key) { return $list } foreach ($n in @($key.GetValueNames())) { $list += [pscustomobject]@{ Name = [string]$n Kind = [string]$key.GetValueKind($n) Data = $key.GetValue($n, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } } } catch { } finally { if ($key) { try { $key.Close() } catch { } } if ($base) { try { $base.Close() } catch { } } } return $list } function Test-PolicyMatchesOnKey($Key, $Plan, [string[]]$MustBeAbsent = @()) { if ($null -eq $Key) { return $false } foreach ($name in @($Plan.Keys)) { $item = $Plan[$name] $cur = Get-PolicyValueOnKey $Key $name if (-not $cur) { return $false } if (-not [string]::Equals([string]$cur.Kind, [string]$item.Kind, [StringComparison]::OrdinalIgnoreCase)) { return $false } if (-not [string]::Equals([string]$cur.Data, [string]$item.Data, [StringComparison]::Ordinal)) { return $false } } foreach ($absentName in @($MustBeAbsent)) { if (Get-PolicyValueOnKey $Key $absentName) { return $false } } return $true } function Write-PolicyValuesOnKey($Key, $Plan, [string[]]$DeleteNames = @()) { foreach ($del in @($DeleteNames)) { $prev = Get-PolicyValueOnKey $Key $del if ($prev) { $Key.DeleteValue([string]$prev.Name, $false) } } foreach ($name in @($Plan.Keys)) { $item = $Plan[$name] $kind = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$item.Kind, $true) $data = $item.Data if ($kind -eq [Microsoft.Win32.RegistryValueKind]::DWord) { $data = [int]$data } $targetName = [string]$name $prev = Get-PolicyValueOnKey $Key $name if ($prev) { $targetName = [string]$prev.Name } $Key.SetValue($targetName, $data, $kind) } } function Repair-PolicyAcl($Target) { $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User if (-not $sid) { return $false } $rights = [System.Security.AccessControl.RegistryRights]::TakeOwnership -bor [System.Security.AccessControl.RegistryRights]::ChangePermissions -bor [System.Security.AccessControl.RegistryRights]::ReadKey $base = $null; $key = $null try { $base = Open-PolicyBaseKey $Target.HiveLabel $key = $base.OpenSubKey($Target.SubPath, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, $rights) if (-not $key) { return $false } $acl = $null try { $acl = $key.GetAccessControl() } catch { $acl = $null } if (-not $acl) { $acl = Get-Acl -Path $Target.PsPath } try { $acl.SetOwner($sid); $key.SetAccessControl($acl) } catch { try { Set-Acl -Path $Target.PsPath -AclObject $acl } catch { } } try { $acl = $key.GetAccessControl() } catch { $acl = $null } if (-not $acl) { $acl = Get-Acl -Path $Target.PsPath } $inherit = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit $rule = New-Object System.Security.AccessControl.RegistryAccessRule( $sid, [System.Security.AccessControl.RegistryRights]::FullControl, $inherit, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow ) $acl.AddAccessRule($rule) try { $key.SetAccessControl($acl) } catch { Set-Acl -Path $Target.PsPath -AclObject $acl } return $true } catch { return $false } finally { if ($key) { try { $key.Close() } catch { } } if ($base) { try { $base.Close() } catch { } } } } function Write-PolicyValuesViaRegExe($Target, $Plan, [string[]]$DeleteNames = @()) { $regExe = Get-NativeRegExePath $hiveName = if ($Target.HiveLabel -eq 'HKLM') { 'HKEY_LOCAL_MACHINE' } else { 'HKEY_CURRENT_USER' } $lines = New-Object System.Collections.Generic.List[string] [void]$lines.Add('Windows Registry Editor Version 5.00') [void]$lines.Add('') [void]$lines.Add('[' + $hiveName + '\' + $Target.SubPath + ']') foreach ($del in @($DeleteNames)) { [void]$lines.Add(('"{0}"=-' -f $del)) } foreach ($name in @($Plan.Keys)) { $item = $Plan[$name] if ([string]$item.Kind -eq 'DWord') { [void]$lines.Add(('"{0}"=dword:{1}' -f $name, ([int]$item.Data).ToString('x8'))) } else { $text = ([string]$item.Data).Replace('\', '\\').Replace('"', '\"') [void]$lines.Add(('"{0}"="{1}"' -f $name, $text)) } } $tmp = Join-Path ([IO.Path]::GetTempPath()) ('claude-newapi-' + [Guid]::NewGuid().ToString('N') + '.reg') try { [IO.File]::WriteAllText($tmp, ($lines -join "`r`n") + "`r`n", [Text.Encoding]::Unicode) $regArgs = @('import', $tmp) if ([Environment]::Is64BitOperatingSystem) { $regArgs += '/reg:64' } $out = & $regExe @regArgs 2>&1 if ($LASTEXITCODE -ne 0) { throw ('reg.exe import failed (exit ' + $LASTEXITCODE + '): ' + ($out -join ' ')) } } finally { try { if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction Stop } } catch { } } } function Restore-RecordedValueOnKey($Key, $Rec) { $name = [string]$Rec.Name $cur = Get-PolicyValueOnKey $Key $name if ([bool]$Rec.Existed) { $kind = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$Rec.PrevKind, $true) $data = $Rec.PrevData if ([bool]$Rec.PrevDataIsBase64) { $data = [Convert]::FromBase64String([string]$Rec.PrevData) } elseif ($kind -eq [Microsoft.Win32.RegistryValueKind]::DWord) { $data = [int]$data } elseif ($kind -eq [Microsoft.Win32.RegistryValueKind]::QWord) { $data = [long]$data } elseif ($kind -eq [Microsoft.Win32.RegistryValueKind]::MultiString) { $data = [string[]]@($data) } $restoreName = if ($Rec.PrevName) { [string]$Rec.PrevName } else { $name } if ($cur -and $cur.Name -cne $restoreName) { $Key.DeleteValue([string]$cur.Name, $false) } $Key.SetValue($restoreName, $data, $kind) return ('restored:' + $restoreName) } if ($cur) { $Key.DeleteValue([string]$cur.Name, $false) return ('deleted:' + [string]$cur.Name) } return 'absent' } # 4-tier registry write preserving foreign GPO values across all tiers, with backup & rollback. function Invoke-PolicyApplyDirect([string]$HiveLabel, $Plan, $State, [string[]]$DeleteNames = @()) { $target = Get-PolicyTarget $HiveLabel if ($HiveLabel -eq 'HKLM' -and -not (Test-IsAdmin)) { throw (U '\u5199\u5165 HKLM \u9700\u8981\u7ba1\u7406\u5458\u6743\u9650\u3002') } $regExe = Get-NativeRegExePath $keyState = Test-PolicyKeyState $target $existed = ($keyState -eq 'present') if ($existed -and -not ([string]$State.AppliedAt)) { $State.KeyExistedBefore = $true } # Snapshot all current values before touching anything (for state tracking + foreign preservation). $existingValues = @(Get-PolicyValues $target) $allTouchedNames = @() foreach ($n in @($Plan.Keys)) { $allTouchedNames += [string]$n } foreach ($d in @($DeleteNames)) { if ($allTouchedNames -notcontains $d) { $allTouchedNames += [string]$d } } $foreignValues = @() foreach ($ev in $existingValues) { $isManaged = $false foreach ($tn in $allTouchedNames) { if ($ev.Name -ieq $tn) { $isManaged = $true; break } } if (-not $isManaged) { foreach ($sv in @($State.Values)) { if ([string]$sv.Name -ieq $ev.Name) { $isManaged = $true; break } } } if (-not $isManaged) { $foreignValues += $ev } } # Export .reg backup when foreign values exist (avoid creating extra plaintext API key copies on re-run). $shouldBackup = $existed -and (-not [string]$State.BackupFile) -and ((-not [string]$State.AppliedAt) -or ($foreignValues.Count -gt 0)) if ($shouldBackup) { try { New-Item -ItemType Directory -Path $script:StateDir -Force | Out-Null $backup = Join-Path $script:StateDir ('registry-backup-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff') + '.reg') $expArgs = @('export', $target.WinPath, $backup, '/y') if ([Environment]::Is64BitOperatingSystem) { $expArgs += '/reg:64' } $null = & $regExe @expArgs 2>&1 if ($LASTEXITCODE -eq 0 -and (Test-Path -LiteralPath $backup -PathType Leaf)) { $State.BackupFile = $backup Say ((U '\u6ce8\u518c\u8868\u7b56\u7565\u5df2\u5907\u4efd\u5230: ') + $backup) } } catch { } } # Record pre-install value states for every key we touch or clear. $recorded = @($State.Values) foreach ($name in $allTouchedNames) { $found = $null foreach ($r in $recorded) { if ([string]$r.Name -ieq $name) { $found = $r; break } } if ($null -eq $found) { $prev = $null foreach ($ev in $existingValues) { if ($ev.Name -ieq $name) { $prev = $ev; break } } # Only record DeleteNames if they actually existed before. $inPlan = $false foreach ($pk in @($Plan.Keys)) { if ($pk -ieq $name) { $inPlan = $true; break } } if (-not $inPlan -and $null -eq $prev) { continue } $rec = [pscustomobject]@{ Name = $name Existed = [bool]($null -ne $prev) PrevName = '' PrevKind = '' PrevData = $null PrevDataIsBase64 = $false } if ($prev) { $rec.PrevName = [string]$prev.Name $rec.PrevKind = [string]$prev.Kind if ($prev.Data -is [byte[]]) { $rec.PrevData = [Convert]::ToBase64String($prev.Data) $rec.PrevDataIsBase64 = $true } else { $rec.PrevData = $prev.Data } } $recorded += $rec } } $State.Values = @($recorded) # Restore/remove values that our script previously wrote but are no longer in this run's plan. $extraToRestore = @() if ([string]$State.AppliedAt) { $kept = @() foreach ($rec in $recorded) { $stillTouched = $false foreach ($tn in $allTouchedNames) { if ($tn -ieq [string]$rec.Name) { $stillTouched = $true; break } } if ($stillTouched) { $kept += $rec; continue } $extraToRestore += $rec } $State.Values = @($kept) } $errors = @() $written = $false $mustBeAbsent = @() foreach ($d in @($DeleteNames)) { $inPlan = $false foreach ($pk in @($Plan.Keys)) { if ($pk -ieq $d) { $inPlan = $true; break } } if (-not $inPlan) { $mustBeAbsent += $d } } # Tier 1: Direct 64-bit .NET registry write try { $base = Open-PolicyBaseKey $HiveLabel try { $key = $base.CreateSubKey($target.SubPath) try { Write-PolicyValuesOnKey $key $Plan $mustBeAbsent foreach ($rec in $extraToRestore) { $null = Restore-RecordedValueOnKey $key $rec } if (-not (Test-PolicyMatchesOnKey $key $Plan $mustBeAbsent)) { throw 'readback mismatch' } $written = $true } finally { if ($key) { $key.Close() } } } finally { if ($base) { $base.Close() } } } catch { $errors += ('direct: ' + $_.Exception.Message) } # Tier 2: Repair ACL (Admin) + retry if (-not $written -and $existed -and (Test-IsAdmin)) { $null = Repair-PolicyAcl $target try { $base = Open-PolicyBaseKey $HiveLabel try { $key = $base.CreateSubKey($target.SubPath) try { Write-PolicyValuesOnKey $key $Plan $mustBeAbsent foreach ($rec in $extraToRestore) { $null = Restore-RecordedValueOnKey $key $rec } if (-not (Test-PolicyMatchesOnKey $key $Plan $mustBeAbsent)) { throw 'readback mismatch' } $written = $true Say-Ok (U '\u5df2\u4fee\u590d\u6ce8\u518c\u8868\u7b56\u7565\u9879\u6743\u9650') } finally { if ($key) { $key.Close() } } } finally { if ($base) { $base.Close() } } } catch { $errors += ('acl-repair: ' + $_.Exception.Message) } } # Tier 3: Recreate subkey from parent while preserving any foreign GPO values if (-not $written -and (Test-IsAdmin)) { try { $parentPath = Split-Path -Parent $target.SubPath $leaf = Split-Path -Leaf $target.SubPath $base = Open-PolicyBaseKey $HiveLabel try { $parent = $base.OpenSubKey($parentPath, $true) if (-not $parent) { $sw = $base.OpenSubKey('SOFTWARE', $true) try { $parent = $sw.CreateSubKey('Policies', $true) } finally { if ($sw) { $sw.Close() } } } try { try { $parent.DeleteSubKeyTree($leaf, $false) } catch { try { $parent.DeleteSubKey($leaf, $false) } catch { } } $key = $parent.CreateSubKey($leaf, $true) try { # Re-write preserved foreign GPO values first foreach ($fv in $foreignValues) { $fk = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$fv.Kind, $true) $key.SetValue([string]$fv.Name, $fv.Data, $fk) } Write-PolicyValuesOnKey $key $Plan $mustBeAbsent if (-not (Test-PolicyMatchesOnKey $key $Plan $mustBeAbsent)) { throw 'readback mismatch' } $written = $true } finally { if ($key) { $key.Close() } } } finally { if ($parent) { $parent.Close() } } } finally { if ($base) { $base.Close() } } } catch { $errors += ('recreate: ' + $_.Exception.Message) } } # Tier 4: reg.exe import fallback (/reg:64) if (-not $written) { try { Write-PolicyValuesViaRegExe $target $Plan $mustBeAbsent $base = Open-PolicyBaseKey $HiveLabel try { $ro = $base.OpenSubKey($target.SubPath, $false) try { if (-not (Test-PolicyMatchesOnKey $ro $Plan $mustBeAbsent)) { throw 'import readback mismatch' } $written = $true } finally { if ($ro) { $ro.Close() } } } finally { if ($base) { $base.Close() } } } catch { $errors += ('reg.exe: ' + $_.Exception.Message) } } if (-not $written) { if ([string]$State.BackupFile -and (Test-Path -LiteralPath ([string]$State.BackupFile))) { try { $impArgs = @('import', [string]$State.BackupFile) if ([Environment]::Is64BitOperatingSystem) { $impArgs += '/reg:64' } $null = & $regExe @impArgs 2>&1 Say-Warn (U '\u5199\u5165\u5931\u8d25\uff0c\u5df2\u7528\u5907\u4efd\u8fd8\u539f\u6ce8\u518c\u8868\u7b56\u7565\u3002') } catch { } } throw ((U '\u6ce8\u518c\u8868\u7b56\u7565\u5199\u5165\u5931\u8d25: ') + ($errors -join '; ')) } } function Invoke-PolicyUninstallDirect($State) { $hiveLabel = [string]$State.Hive $target = Get-PolicyTarget $hiveLabel if ($hiveLabel -eq 'HKLM' -and -not (Test-IsAdmin)) { throw (U '\u8fd8\u539f HKLM \u9700\u8981\u7ba1\u7406\u5458\u6743\u9650\u3002') } $regExe = Get-NativeRegExePath $base = Open-PolicyBaseKey $hiveLabel try { $key = $null try { $key = $base.OpenSubKey($target.SubPath, $true) } catch { $key = $null } if (-not $key) { $ro = $null try { $ro = $base.OpenSubKey($target.SubPath, $false) } catch { $ro = $null } if (-not $ro) { Say ((U '\u6ce8\u518c\u8868\u7b56\u7565\u9879\u4e0d\u5b58\u5728\uff0c\u65e0\u9700\u8fd8\u539f: ') + $target.WinPath); return } $ro.Close() if (Test-IsAdmin) { $null = Repair-PolicyAcl $target } try { $key = $base.OpenSubKey($target.SubPath, $true) } catch { $key = $null } if (-not $key) { # Fallback via reg.exe $ro = $base.OpenSubKey($target.SubPath, $false) $restorePlan = [ordered]@{} try { foreach ($v in @($State.Values)) { $cur = Get-PolicyValueOnKey $ro ([string]$v.Name) if ([bool]$v.Existed -and ([string]$v.PrevKind -eq 'String' -or [string]$v.PrevKind -eq 'DWord')) { $rn = if ($v.PrevName) { [string]$v.PrevName } else { [string]$v.Name } $restorePlan[$rn] = [pscustomobject]@{ Kind = [string]$v.PrevKind; Data = $v.PrevData } } elseif ($cur) { $delArgs = @('delete', $target.WinPath, '/v', [string]$cur.Name, '/f') if ([Environment]::Is64BitOperatingSystem) { $delArgs += '/reg:64' } $null = & $regExe @delArgs 2>&1 Say-Ok ((U '\u5df2\u5220\u9664: ') + [string]$cur.Name) } } } finally { $ro.Close() } if ($restorePlan.Count -gt 0) { Write-PolicyValuesViaRegExe $target $restorePlan @() Say-Ok (U '\u5df2\u8fd8\u539f\u539f\u503c') } return } } $empty = $false try { foreach ($v in @($State.Values)) { $outcome = Restore-RecordedValueOnKey $key $v if ($outcome.StartsWith('restored:')) { Say-Ok ((U '\u5df2\u8fd8\u539f\u539f\u503c: ') + $outcome.Substring(9)) } elseif ($outcome.StartsWith('deleted:')) { Say-Ok ((U '\u5df2\u5220\u9664: ') + $outcome.Substring(8)) } } $empty = ($key.ValueCount -eq 0 -and $key.SubKeyCount -eq 0) } finally { $key.Close() } if ($empty -and -not [bool]$State.KeyExistedBefore) { try { $base.DeleteSubKey($target.SubPath, $false) Say ((U '\u5df2\u5220\u9664\u7a7a\u7684\u7b56\u7565\u9879: ') + $target.WinPath) } catch { } } } finally { if ($base) { $base.Close() } } } # ---------------------------------------------------------------- Privilege-Separated Elevated Registry Worker # Works identically for local -File, .cmd double-click, AND "irm | iex" (where $PSCommandPath is empty). # Only the privileged Registry apply/uninstall operation runs elevated; user files & App restart run as real user. function Import-ProtectedDataSupport { $typeName = 'System.Security.Cryptography.ProtectedData' if (@([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetType($typeName, $false) }).Count -gt 0) { return $true } foreach ($asm in 'System.Security.Cryptography.ProtectedData', 'System.Security') { try { Add-Type -AssemblyName $asm -ErrorAction Stop } catch { } if (@([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetType($typeName, $false) }).Count -gt 0) { return $true } } return $false } function Protect-PayloadFile([string]$JsonText) { $path = Join-Path ([IO.Path]::GetTempPath()) ('claude-newapi-payload-' + [Guid]::NewGuid().ToString('N') + '.dpapi') try { if (-not (Import-ProtectedDataSupport)) { throw 'ProtectedData unavailable' } $bytes = [Security.Cryptography.ProtectedData]::Protect( [Text.Encoding]::UTF8.GetBytes($JsonText), $null, [Security.Cryptography.DataProtectionScope]::LocalMachine ) [IO.File]::WriteAllBytes($path, $bytes) return $path } catch { try { if (Test-Path -LiteralPath $path) { Remove-Item -LiteralPath $path -Force } } catch { } return '' } } function Get-ElevatedRegistryWorkerSource { return @' param( [Parameter(Mandatory=$true)][string]$PayloadFile, [Parameter(Mandatory=$true)][string]$ResultFile, [Parameter(Mandatory=$true)][string]$LogFile ) Set-StrictMode -Version 1.0 $ErrorActionPreference = 'Stop' $logLines = New-Object System.Collections.Generic.List[string] function Log([string]$m) { [void]$logLines.Add($m) } function Import-Dpapi { $t = 'System.Security.Cryptography.ProtectedData' if (@([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetType($t, $false) }).Count -gt 0) { return $true } foreach ($a in 'System.Security.Cryptography.ProtectedData', 'System.Security') { try { Add-Type -AssemblyName $a -ErrorAction Stop } catch { } if (@([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GetType($t, $false) }).Count -gt 0) { return $true } } return $false } function Open-Base([string]$h, [string]$callerSid) { $view = if ([Environment]::Is64BitOperatingSystem) { [Microsoft.Win32.RegistryView]::Registry64 } else { [Microsoft.Win32.RegistryView]::Default } if ($h -eq 'HKLM') { return [pscustomobject]@{ Base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $view); Prefix = ''; WinPrefix = 'HKLM'; RegHive = 'HKEY_LOCAL_MACHINE'; PsPrefix = 'HKLM:\' } } $curSid = '' try { $curSid = [string]([Security.Principal.WindowsIdentity]::GetCurrent().User.Value) } catch { } if ($callerSid -and $curSid -and ($callerSid -ne $curSid)) { return [pscustomobject]@{ Base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::Users, $view); Prefix = ($callerSid + '\'); WinPrefix = ('HKU\' + $callerSid); RegHive = ('HKEY_USERS\' + $callerSid); PsPrefix = ('Registry::HKEY_USERS\' + $callerSid + '\') } } return [pscustomobject]@{ Base = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::CurrentUser, $view); Prefix = ''; WinPrefix = 'HKCU'; RegHive = 'HKEY_CURRENT_USER'; PsPrefix = 'HKCU:\' } } function Get-Val($k, [string]$n) { if (-not $k) { return $null } $act = $null foreach ($x in @($k.GetValueNames())) { if ($x -ieq $n) { $act = $x; break } } if (-not $act) { return $null } return [pscustomobject]@{ Name=[string]$act; Kind=[string]$k.GetValueKind($act); Data=$k.GetValue($act, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } } function Repair-Acl([string]$h, [string]$sub, [string]$callerSid) { $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User if (-not $sid) { return $false } $rights = [Security.AccessControl.RegistryRights]::TakeOwnership -bor [Security.AccessControl.RegistryRights]::ChangePermissions -bor [Security.AccessControl.RegistryRights]::ReadKey $ctx = $null; $k = $null try { $ctx = Open-Base $h $callerSid $fullSub = $ctx.Prefix + $sub $k = $ctx.Base.OpenSubKey($fullSub, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, $rights) if (-not $k) { return $false } $ps = $ctx.PsPrefix + $sub $acl = $null try { $acl = $k.GetAccessControl() } catch { $acl = Get-Acl -Path $ps } try { $acl.SetOwner($sid); $k.SetAccessControl($acl) } catch { try { Set-Acl -Path $ps -AclObject $acl } catch { } } try { $acl = $k.GetAccessControl() } catch { $acl = Get-Acl -Path $ps } $inh = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit $rule = New-Object Security.AccessControl.RegistryAccessRule($sid, [Security.AccessControl.RegistryRights]::FullControl, $inh, [Security.AccessControl.PropagationFlags]::None, [Security.AccessControl.AccessControlType]::Allow) $acl.AddAccessRule($rule) try { $k.SetAccessControl($acl) } catch { Set-Acl -Path $ps -AclObject $acl } return $true } catch { return $false } finally { if ($k) { $k.Close() }; if ($ctx -and $ctx.Base) { $ctx.Base.Close() } } } function Write-ViaReg([string]$regHive, [string]$sub, $items, [string[]]$dels) { $lines = New-Object System.Collections.Generic.List[string] [void]$lines.Add('Windows Registry Editor Version 5.00') [void]$lines.Add('') [void]$lines.Add('[' + $regHive + '\' + $sub + ']') foreach ($d in @($dels)) { [void]$lines.Add(('"{0}"=-' -f $d)) } foreach ($it in @($items)) { if ([string]$it.Kind -eq 'DWord') { [void]$lines.Add(('"{0}"=dword:{1}' -f $it.Name, ([int]$it.Data).ToString('x8'))) } else { [void]$lines.Add(('"{0}"="{1}"' -f $it.Name, ([string]$it.Data).Replace('\','\\').Replace('"','\"'))) } } $tmp = Join-Path ([IO.Path]::GetTempPath()) ('claude-newapi-w-' + [Guid]::NewGuid().ToString('N') + '.reg') try { [IO.File]::WriteAllText($tmp, ($lines -join "`r`n") + "`r`n", [Text.Encoding]::Unicode) $ra = @('import', $tmp) if ([Environment]::Is64BitOperatingSystem) { $ra += '/reg:64' } $out = & reg.exe @ra 2>&1 if ($LASTEXITCODE -ne 0) { throw ('reg.exe import exit ' + $LASTEXITCODE + ': ' + ($out -join ' ')) } } finally { try { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue } catch { } } } function Restore-One($k, $rec) { $cur = Get-Val $k ([string]$rec.Name) if ([bool]$rec.Existed) { $kd = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$rec.PrevKind, $true) $dv = $rec.PrevData if ([bool]$rec.PrevDataIsBase64) { $dv = [Convert]::FromBase64String([string]$rec.PrevData) } elseif ($kd -eq [Microsoft.Win32.RegistryValueKind]::DWord) { $dv = [int]$dv } elseif ($kd -eq [Microsoft.Win32.RegistryValueKind]::QWord) { $dv = [long]$dv } elseif ($kd -eq [Microsoft.Win32.RegistryValueKind]::MultiString) { $dv = [string[]]@($dv) } $rn = if ($rec.PrevName) { [string]$rec.PrevName } else { [string]$rec.Name } if ($cur -and $cur.Name -cne $rn) { $k.DeleteValue([string]$cur.Name, $false) } $k.SetValue($rn, $dv, $kd) Log ('[OK] restored: ' + $rn) } elseif ($cur) { $k.DeleteValue([string]$cur.Name, $false) Log ('[OK] deleted: ' + [string]$cur.Name) } } $rc = 0 $resultObj = [ordered]@{ Ok = $false; BackupFile = ''; Error = '' } try { if (-not (Import-Dpapi)) { throw 'ProtectedData unavailable in elevated worker' } $plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($PayloadFile), $null, [Security.Cryptography.DataProtectionScope]::LocalMachine) $req = ([Text.Encoding]::UTF8.GetString($plain)) | ConvertFrom-Json $h = [string]$req.Hive $sub = [string]$req.SubPath $callerSid = if ($req.PSObject.Properties['CallerSid']) { [string]$req.CallerSid } else { '' } $ctx0 = Open-Base $h $callerSid $fullSub = $ctx0.Prefix + $sub $win = $ctx0.WinPrefix + '\' + $sub $regHive = $ctx0.RegHive $ctx0.Base.Close() if ($req.Action -eq 'apply') { $items = @($req.Plan) $dels = @($req.DeleteNames) $restores = @($req.ExtraRestores) $foreign = @() $ctx = Open-Base $h $callerSid $existed = $false try { $ro = $ctx.Base.OpenSubKey($fullSub, $false) if ($ro) { $existed = $true foreach ($vn in @($ro.GetValueNames())) { $known = $false foreach ($it in $items) { if ([string]$it.Name -ieq $vn) { $known = $true; break } } foreach ($dn in $dels) { if ($dn -ieq $vn) { $known = $true; break } } foreach ($rr in $restores) { if ([string]$rr.Name -ieq $vn) { $known = $true; break } } if (-not $known) { $foreign += [pscustomobject]@{ Name=[string]$vn; Kind=[string]$ro.GetValueKind($vn); Data=$ro.GetValue($vn, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } } } $ro.Close() } } finally { $ctx.Base.Close() } if ($existed -and [string]$req.BackupPath) { try { $bd = Split-Path -Parent ([string]$req.BackupPath) if ($bd -and -not (Test-Path -LiteralPath $bd)) { New-Item -ItemType Directory -Path $bd -Force | Out-Null } $ea = @('export', $win, [string]$req.BackupPath, '/y') if ([Environment]::Is64BitOperatingSystem) { $ea += '/reg:64' } $null = & reg.exe @ea 2>&1 if ($LASTEXITCODE -eq 0 -and (Test-Path -LiteralPath ([string]$req.BackupPath))) { $resultObj.BackupFile = [string]$req.BackupPath Log ('Backup saved: ' + [string]$req.BackupPath) } } catch { } } $errs = @(); $ok = $false foreach ($tier in 1, 2, 3, 4) { if ($ok) { break } try { if ($tier -eq 2) { if (-not $existed) { continue }; $null = Repair-Acl $h $sub $callerSid } if ($tier -eq 1 -or $tier -eq 2) { $ctx = Open-Base $h $callerSid try { $k = $ctx.Base.CreateSubKey($fullSub) try { foreach ($d in $dels) { $p = Get-Val $k $d; if ($p) { $k.DeleteValue([string]$p.Name, $false) } } foreach ($it in $items) { $kd = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$it.Kind, $true) $dv = if ($kd -eq [Microsoft.Win32.RegistryValueKind]::DWord) { [int]$it.Data } else { [string]$it.Data } $tn = [string]$it.Name $p = Get-Val $k $tn; if ($p) { $tn = [string]$p.Name } $k.SetValue($tn, $dv, $kd) } foreach ($rr in $restores) { Restore-One $k $rr } $ok = $true } finally { if ($k) { $k.Close() } } } finally { $ctx.Base.Close() } } elseif ($tier -eq 3) { $pp = Split-Path -Parent $fullSub; $lf = Split-Path -Leaf $fullSub $ctx = Open-Base $h $callerSid try { $par = $ctx.Base.OpenSubKey($pp, $true) if (-not $par) { $sw = $ctx.Base.OpenSubKey(($ctx.Prefix + 'SOFTWARE'), $true); try { $par = $sw.CreateSubKey('Policies', $true) } finally { if ($sw) { $sw.Close() } } } try { try { $par.DeleteSubKeyTree($lf, $false) } catch { try { $par.DeleteSubKey($lf, $false) } catch { } } $k = $par.CreateSubKey($lf, $true) try { foreach ($fv in $foreign) { $k.SetValue([string]$fv.Name, $fv.Data, [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$fv.Kind, $true)) } foreach ($it in $items) { $kd = [Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$it.Kind, $true) $dv = if ($kd -eq [Microsoft.Win32.RegistryValueKind]::DWord) { [int]$it.Data } else { [string]$it.Data } $k.SetValue([string]$it.Name, $dv, $kd) } $ok = $true } finally { if ($k) { $k.Close() } } } finally { if ($par) { $par.Close() } } } finally { $ctx.Base.Close() } } elseif ($tier -eq 4) { Write-ViaReg $regHive $sub $items $dels $ok = $true } } catch { $errs += ('tier' + $tier + ': ' + $_.Exception.Message) } } if (-not $ok) { if ($resultObj.BackupFile) { $ia = @('import', $resultObj.BackupFile) if ([Environment]::Is64BitOperatingSystem) { $ia += '/reg:64' } $null = & reg.exe @ia 2>&1 } throw ($errs -join '; ') } Log ('[OK] Registry policy written to ' + $win) $resultObj.Ok = $true } elseif ($req.Action -eq 'uninstall') { $vals = @($req.Values) $ctx = Open-Base $h $callerSid try { $k = $null try { $k = $ctx.Base.OpenSubKey($fullSub, $true) } catch { $k = $null } if (-not $k) { $ro = $null try { $ro = $ctx.Base.OpenSubKey($fullSub, $false) } catch { $ro = $null } if (-not $ro) { Log ('Key absent: ' + $win); $resultObj.Ok = $true } else { $ro.Close() $null = Repair-Acl $h $sub $callerSid $k = $ctx.Base.OpenSubKey($fullSub, $true) } } if ($k) { $empty = $false try { foreach ($v in $vals) { Restore-One $k $v } $empty = ($k.ValueCount -eq 0 -and $k.SubKeyCount -eq 0) } finally { $k.Close() } if ($empty -and -not [bool]$req.KeyExistedBefore) { try { $ctx.Base.DeleteSubKey($fullSub, $false); Log ('Removed empty key: ' + $win) } catch { } } $resultObj.Ok = $true } } finally { $ctx.Base.Close() } } } catch { $resultObj.Error = [string]$_.Exception.Message Log ('[X] ' + $resultObj.Error) $rc = 1 } finally { try { [IO.File]::WriteAllText($ResultFile, (ConvertTo-Json -InputObject $resultObj -Compress -Depth 5), (New-Object Text.UTF8Encoding($false))) } catch { } try { [IO.File]::WriteAllText($LogFile, ($logLines -join "`r`n"), (New-Object Text.UTF8Encoding($false))) } catch { } } exit $rc '@ } function Invoke-ElevatedRegistryWorker([hashtable]$Request) { $tag = [Guid]::NewGuid().ToString('N') $tmpDir = [IO.Path]::GetTempPath() $workerPath = Join-Path $tmpDir ('claude-newapi-worker-' + $tag + '.ps1') $resultPath = Join-Path $tmpDir ('claude-newapi-result-' + $tag + '.json') $logPath = Join-Path $tmpDir ('claude-newapi-log-' + $tag + '.txt') $payloadPath = '' try { $json = ConvertTo-Json -InputObject $Request -Compress -Depth 10 $payloadPath = Protect-PayloadFile $json if (-not $payloadPath) { return [pscustomobject]@{ Started = $false; ExitCode = -1; Ok = $false; BackupFile = ''; Error = 'Could not create DPAPI payload file'; Logs = @() } } Write-TextFileAtomic $workerPath (Get-ElevatedRegistryWorkerSource) $false $hostExe = Get-64BitPowerShellPath $argList = @( '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ('"' + $workerPath + '"'), '-PayloadFile', ('"' + $payloadPath + '"'), '-ResultFile', ('"' + $resultPath + '"'), '-LogFile', ('"' + $logPath + '"') ) $proc = $null try { $proc = Start-Process -FilePath $hostExe -ArgumentList $argList -Verb RunAs -Wait -PassThru -WindowStyle Hidden -ErrorAction Stop } catch { return [pscustomobject]@{ Started = $false; ExitCode = -1; Ok = $false; BackupFile = ''; Error = $_.Exception.Message; Logs = @() } } $exitCode = -2 try { if ($proc.HasExited -and $null -ne $proc.ExitCode) { $exitCode = [int]$proc.ExitCode } } catch { } $logs = @() if (Test-Path -LiteralPath $logPath -PathType Leaf) { try { $logs = @(Get-Content -LiteralPath $logPath -Encoding UTF8 -ErrorAction Stop) } catch { } } $res = $null if (Test-Path -LiteralPath $resultPath -PathType Leaf) { try { $res = (Read-Utf8TextStrict $resultPath) | ConvertFrom-Json } catch { $res = $null } } return [pscustomobject]@{ Started = $true ExitCode = $exitCode Ok = [bool]($res -and $res.Ok) BackupFile = if ($res -and $res.BackupFile) { [string]$res.BackupFile } else { '' } Error = if ($res -and $res.Error) { [string]$res.Error } else { '' } Logs = $logs } } finally { foreach ($f in @($payloadPath, $workerPath, $resultPath, $logPath)) { if ($f -and (Test-Path -LiteralPath $f)) { try { Remove-Item -LiteralPath $f -Force -ErrorAction Stop } catch { } } } } } # ---------------------------------------------------------------- State Management function New-State([string]$HiveLabel) { return [pscustomobject]@{ Version = 2 AppliedAt = '' BaseUrl = '' Hive = $HiveLabel PolicyPath = $script:PolicySubPath KeyExistedBefore = $false BackupFile = '' Values = @() ConfigFiles = @() } } function Load-State { if (-not (Test-Path -LiteralPath $script:StateFile -PathType Leaf)) { return $null } try { return ((Read-Utf8TextStrict $script:StateFile) | ConvertFrom-Json) } catch { return $null } } function Save-State($State) { New-Item -ItemType Directory -Path $script:StateDir -Force | Out-Null Write-TextFileAtomic $script:StateFile (ConvertTo-Json -InputObject $State -Depth 10) $false } # ---------------------------------------------------------------- Surgical Config & Bypass Preseed function Get-AccountId([string]$Dir) { $file = Join-Path $Dir 'ant-did' if (Test-Path -LiteralPath $file -PathType Leaf) { try { $b64 = (Read-Utf8TextStrict $file).Trim() $s = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b64)).Trim() if ($s -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$') { return $s.ToLowerInvariant() } } catch { } return '' } # Never create a second synthetic identity inside an MSIX private LocalCache folder. if ($Dir -like '*\Packages\*\LocalCache\*') { return '' } New-Item -ItemType Directory -Path $Dir -Force | Out-Null $guid = [Guid]::NewGuid().ToString('D').ToLowerInvariant() $encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($guid)) $stream = $null try { $stream = [IO.File]::Open($file, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) $bytes = [Text.Encoding]::UTF8.GetBytes($encoded) $stream.Write($bytes, 0, $bytes.Length) } catch { if (Test-Path -LiteralPath $file -PathType Leaf) { return (Get-AccountId $Dir) } return '' } finally { if ($stream) { $stream.Dispose() } } return $guid } function Apply-BypassSurgical([string]$JsonText, [string]$Did) { $optPath = @('preferences', 'bypassPermissionsOptInByAccount', $Did) $gatePath = @('preferences', 'bypassPermissionsGateByAccount', $Did) $draftPath = @('preferences', 'epitaxyPrefs', ('cc-landing-draft-permission-mode.' + $Did)) $optRaw = Get-JsonPathRaw $JsonText $optPath if ($optRaw -ceq 'false') { return [pscustomobject]@{ Status = 'kept-off'; Json = $JsonText; Removed = @() } } $draftRaw = Get-JsonPathRaw $JsonText $draftPath if ($null -ne $draftRaw -and $draftRaw -cne 'null') { $allowed = $false if ($draftRaw.StartsWith('"')) { try { $decoded = Decode-JsonString $draftRaw $allowed = ($decoded -ceq 'auto' -or $decoded -ceq 'bypassPermissions') } catch { $allowed = $false } } if (-not $allowed) { return [pscustomobject]@{ Status = 'kept-other-mode'; Json = $JsonText; Removed = @() } } } $out = $JsonText $out = Set-JsonPathRaw $out $optPath 'true' $out = Set-JsonPathRaw $out $gatePath 'true' $out = Set-JsonPathRaw $out $draftPath '"bypassPermissions"' # Clear per-folder saved "auto" overrides (Auto causes extra review API call on every tool use). $removed = @() $folderPath = @('preferences', 'epitaxyPrefs', ('epitaxy-folder-permission-mode-v2.' + $Did)) $folderRaw = Get-JsonPathRaw $out $folderPath if ($null -ne $folderRaw -and (Test-JsonObjectText $folderRaw)) { foreach ($entry in @(Get-JsonObjectMembers $folderRaw)) { if ($entry.Raw.StartsWith('"')) { try { if ((Decode-JsonString $entry.Raw) -ceq 'auto') { $removed += [pscustomobject]@{ Name = [string]$entry.Key; Value = 'auto' } $out = Set-JsonPathRaw $out ([string[]]($folderPath + @([string]$entry.Key))) '' -Remove } } catch { } } } } if (-not (Test-JsonObjectText $out)) { throw 'Bypass surgical JSON validation failed' } return [pscustomobject]@{ Status = 'set'; Json = $out; Removed = @($removed) } } function Undo-BypassSurgical([string]$JsonText, [string]$Did, $Removed) { $out = $JsonText $draftPath = @('preferences', 'epitaxyPrefs', ('cc-landing-draft-permission-mode.' + $Did)) $draftRaw = Get-JsonPathRaw $out $draftPath if ($null -ne $draftRaw -and $draftRaw.StartsWith('"')) { try { if ((Decode-JsonString $draftRaw) -ceq 'bypassPermissions') { $out = Set-JsonPathRaw $out $draftPath '' -Remove foreach ($map in 'bypassPermissionsOptInByAccount', 'bypassPermissionsGateByAccount') { $p = @('preferences', $map, $Did) if ((Get-JsonPathRaw $out $p) -ceq 'true') { $out = Set-JsonPathRaw $out $p '' -Remove } } } } catch { } } foreach ($x in @($Removed)) { if ($null -eq $x -or -not $x.Name) { continue } $fp = @('preferences', 'epitaxyPrefs', ('epitaxy-folder-permission-mode-v2.' + $Did), [string]$x.Name) $out = Set-JsonPathRaw $out $fp (Encode-JsonString ([string]$x.Value)) } return $out } function Set-ConfigDeploymentModeSurgical([string]$Path, [string]$Mode, [bool]$ApplyBypass, $Rec) { if ($Mode -cne '1p' -and $Mode -cne '3p') { throw ('Invalid deploymentMode: ' + $Mode) } $exists = Test-Path -LiteralPath $Path -PathType Leaf $raw = '' $resetOccurred = $false if ($exists) { $origBytes = [IO.File]::ReadAllBytes($Path) $raw = [Text.Encoding]::UTF8.GetString($origBytes) if ($raw.Length -gt 0 -and $raw[0] -eq [char]0xFEFF) { $raw = $raw.Substring(1) } if ($null -ne $Rec -and -not $Rec.BackupFile -and $origBytes.Length -gt 0) { New-Item -ItemType Directory -Path $script:StateDir -Force | Out-Null $bak = Join-Path $script:StateDir ('config-backup-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff') + '.json') [IO.File]::WriteAllBytes($bak, $origBytes) $Rec.BackupFile = $bak } } $working = '' if (-not [string]::IsNullOrWhiteSpace($raw)) { if (Test-JsonObjectText $raw) { $working = $raw } else { $repaired = Repair-JsonInvalidEscapes $raw if (Test-JsonObjectText $repaired) { $working = $repaired Say-Warn ((U '\u5df2\u81ea\u52a8\u4fee\u590d\u914d\u7f6e\u6587\u4ef6\u4e2d\u7684\u975e\u6cd5\u8f6c\u4e49\u5b57\u7b26: ') + $Path) } else { $resetOccurred = $true Say-Warn ((U '\u539f\u914d\u7f6e\u6587\u4ef6\u4e0d\u662f\u5408\u6cd5 JSON\uff0c\u5df2\u5907\u4efd\u540e\u91cd\u5efa: ') + $Path) $working = '{}' } } } else { $working = '{}' } if ($null -ne $Rec -and -not $Rec.RecordedMode) { $prevRaw = Get-JsonPathRaw $working @('deploymentMode') if ($null -ne $prevRaw -and $prevRaw.StartsWith('"')) { try { $Rec.HadMode = $true; $Rec.PrevMode = Decode-JsonString $prevRaw } catch { } } $Rec.RecordedMode = $true } $out = Set-JsonPathRaw $working @('deploymentMode') (Encode-JsonString $Mode) if (-not (Test-JsonObjectText $out)) { throw ('JSON edit failed for: ' + $Path) } $bypassNote = (U '\u672a\u5f00\u542f') if ($ApplyBypass -and $Mode -ceq '3p' -and -not $resetOccurred) { $did = if ($Rec -and $Rec.BypassDid) { [string]$Rec.BypassDid } else { Get-AccountId (Split-Path -Parent $Path) } if ($did) { try { $res = Apply-BypassSurgical $out $did $out = $res.Json if ($Rec) { $Rec.BypassDid = $did if (@($Rec.BypassRemoved).Count -eq 0) { $Rec.BypassRemoved = @($res.Removed) } } $bypassNote = $res.Status } catch { $bypassNote = (U '\u5df2\u8df3\u8fc7 (\u4fdd\u62a4\u539f\u914d\u7f6e)') } } else { $bypassNote = (U '\u672a\u5199\u5165 (\u65e0\u8d26\u6237 ID)') } } Write-TextFileAtomic $Path $out $false $verify = Read-Utf8TextStrict $Path $verRaw = Get-JsonPathRaw $verify @('deploymentMode') if (-not (Test-JsonObjectText $verify) -or $null -eq $verRaw -or -not $verRaw.StartsWith('"') -or (Decode-JsonString $verRaw) -cne $Mode) { throw ((U '\u6a21\u5f0f\u6587\u4ef6\u5199\u5165\u540e\u6821\u9a8c\u5931\u8d25: ') + $Path) } return $bypassNote } function Invoke-ConfigApply($app, $State) { if (Test-LegacyDataFolderPending) { Say-Warn ((U '\u68c0\u6d4b\u5230\u65e7\u7248\u6570\u636e\u76ee\u5f55 ') + (Join-Path $script:RoamingAppData 'Claude-3p') + (U '\uff0cApp \u4f1a\u5728\u4e0b\u6b21\u542f\u52a8\u65f6\u81ea\u52a8\u8fc1\u79fb\u4f60\u7684\u4f1a\u8bdd\u6570\u636e\u3002')) Say-Warn (U '\u672c\u6b21\u4e0d\u63d0\u524d\u521b\u5efa\u65b0\u76ee\u5f55\u3002\u9996\u6b21\u6253\u5f00 Claude \u65f6\u8bf7\u9009\u300cContinue with Gateway\u300d\uff0c\u8fc1\u79fb\u5b8c\u6210\u540e\u53ef\u518d\u8fd0\u884c\u4e00\u6b21\u811a\u672c\u8865\u5199 Bypass\u3002') return } $records = @($State.ConfigFiles) $bypassOk = (-not $script:Opt.KeepPermissionPrompts) -and ($app.Installed -and (Test-VersionAtLeast ([string]$app.AppVersion) $script:BypassMinVersion)) foreach ($path in @(Get-ConfigPaths $app)) { $rec = $null foreach ($r in $records) { if ([string]$r.Path -ieq [string]$path) { $rec = $r; break } } $isNew = ($null -eq $rec) if ($isNew) { $rec = [pscustomobject]@{ Path = [string]$path ExistedBefore = (Test-Path -LiteralPath $path -PathType Leaf) BackupFile = '' RecordedMode = $false HadMode = $false PrevMode = '' BypassDid = '' BypassRemoved = @() } } $note = Set-ConfigDeploymentModeSurgical $path '3p' $bypassOk $rec if ($isNew) { $records += $rec } Say-Ok ('deploymentMode=3p -> ' + $path + (U ' (\u9ed8\u8ba4 Bypass: ') + $note + ')') } $State.ConfigFiles = @($records) } function Invoke-ConfigUninstall($State) { foreach ($rec in @($State.ConfigFiles)) { $path = [string]$rec.Path if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { Say ((U '\u914d\u7f6e\u6587\u4ef6\u5df2\u4e0d\u5b58\u5728: ') + $path) continue } $raw = Read-Utf8TextStrict $path if (-not (Test-JsonObjectText $raw)) { Say-Warn ((U '\u914d\u7f6e\u6587\u4ef6\u65e0\u6cd5\u89e3\u6790\uff0c\u4fdd\u7559\u539f\u6837: ') + $path) continue } $out = $raw if ([bool]$rec.HadMode -and $rec.PrevMode) { $out = Set-JsonPathRaw $out @('deploymentMode') (Encode-JsonString ([string]$rec.PrevMode)) } else { $out = Set-JsonPathRaw $out @('deploymentMode') '' -Remove } if ($rec.BypassDid) { $out = Undo-BypassSurgical $out ([string]$rec.BypassDid) @($rec.BypassRemoved) } if (-not (Test-JsonObjectText $out)) { Say-Warn ((U '\u8fd8\u539f\u540e JSON \u6821\u9a8c\u5931\u8d25\uff0c\u4fdd\u7559\u539f\u6837: ') + $path) continue } if (-not [bool]$rec.ExistedBefore -and @(Get-JsonObjectMembers $out).Count -eq 0) { Remove-Item -LiteralPath $path -Force Say-Ok ((U '\u5df2\u5220\u9664\u672c\u811a\u672c\u521b\u5efa\u7684\u914d\u7f6e\u6587\u4ef6: ') + $path) } else { Write-TextFileAtomic $path $out $false Say-Ok ((U '\u5df2\u8fd8\u539f\u914d\u7f6e\u6587\u4ef6: ') + $path) } } } # ---------------------------------------------------------------- New API Model Catalog & Connectivity # Claude Desktop 3P model filter: accepts models containing claude/anthropic or Claude family tiers, # and rejects non-Anthropic vendor names (gpt, openai, gemini, doubao, deepseek, qwen, glm, etc.). function Test-ModelAcceptedByApp([string]$ModelId) { if ([string]::IsNullOrWhiteSpace($ModelId)) { return $false } $lower = $ModelId.ToLowerInvariant() -replace '\[1m\]$', '' $blocked = @( 'gpt', 'openai', 'gemini', 'google', 'doubao', 'seedance', 'deepseek', 'qwen', 'glm', 'kimi', 'moonshot', 'llama', 'mistral', 'grok', 'xai', 'minimax', 'yi-', 'baichuan', 'cohere', 'command-', 'o1', 'o3', 'o4', 'dall-e', 'whisper', 'tts-', 'embedding', 'rerank', 'flux', 'midjourney', 'sora' ) foreach ($b in $blocked) { if ($lower -match ('(^|[/\-_\.])' + [regex]::Escape($b) + '($|[/\-_\.\d])')) { return $false } if ($b.Length -ge 4 -and $lower.Contains($b)) { return $false } } foreach ($ok in 'claude', 'anthropic', 'opus', 'sonnet', 'haiku', 'fable') { if ($lower.Contains($ok)) { return $true } } return $false } function Get-ModelMetadata([string]$Id) { $clean = $Id.Trim() $base = $clean -replace '^anthropic/', '' $tier = '' $major = 0; $minor = 0 $verDisplay = '' $label = '' $m1 = $false # Match claude--[-.][-] if ($base -match '(?i)^claude-(opus|sonnet|haiku|fable)-(\d+)(?:[\-\.](\d{1,2}))?(?:-(\d{8}))?(.*)$') { $tier = $Matches[1].ToLowerInvariant() $major = [int]$Matches[2] if ($Matches[3]) { $minor = [int]$Matches[3] $verDisplay = ('{0}.{1}' -f $major, $minor) } else { $verDisplay = ('{0}' -f $major) } $tierCap = $tier.Substring(0, 1).ToUpperInvariant() + $tier.Substring(1) $suffix = '' if ($Matches[5]) { $extra = $Matches[5].Trim('-', '_', ' ') if ($extra) { $suffix = ' (' + $extra + ')' } } $label = ('Claude {0} {1}{2}' -f $tierCap, $verDisplay, $suffix) # 1M context: Opus/Sonnet/Fable >= 4.5 (and 5.x); Haiku >= 5.0 if ($tier -in @('opus', 'sonnet', 'fable')) { if ($major -ge 5 -or ($major -eq 4 -and $minor -ge 5)) { $m1 = $true } } elseif ($tier -eq 'haiku' -and $major -ge 5) { $m1 = $true } } elseif ($base -match '(?i)(opus|sonnet|haiku|fable)') { $tier = $Matches[1].ToLowerInvariant() } $tierRank = switch ($tier) { 'opus' { 40 } 'sonnet' { 30 } 'fable' { 20 } 'haiku' { 10 } default { 0 } } $sortScore = ($major * 10000) + ($minor * 100) + $tierRank return [pscustomobject]@{ Id = $clean Label = $label Tier = $tier Supports1M = $m1 SortScore = $sortScore } } # Fallback list verified against https://api.chuhai365.cc/v1/models (used only in -Offline mode or if /v1/models fails). $script:DefaultNewApiModels = @( 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-2', 'claude-haiku-5-5', 'claude-opus-4-6', 'claude-sonnet-4-6' ) function New-ModelList([string[]]$Custom, [string[]]$Discovered) { $customIds = @(@($Custom) | ForEach-Object { ([string]$_).Split(',') } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) $isCustom = ($customIds.Count -gt 0) $ids = @() $source = 'default' if ($isCustom) { $ids = $customIds $source = 'custom' } elseif ($Discovered -and @($Discovered).Count -gt 0) { $accepted = @($Discovered | Where-Object { Test-ModelAcceptedByApp ([string]$_) }) if ($accepted.Count -gt 0) { $ids = @($accepted | Sort-Object -Property @{ Expression = { (Get-ModelMetadata ([string]$_)).SortScore }; Descending = $true }, @{ Expression = { [string]$_ }; Descending = $false }) $source = 'discovered' } else { $ids = @($script:DefaultNewApiModels) $source = 'default' } } else { $ids = @($script:DefaultNewApiModels) $source = 'default' } $entries = @() $seenId = @{} $seenTier = @{} foreach ($rawId in $ids) { $id = [string]$rawId if ([string]::IsNullOrWhiteSpace($id) -or $seenId.ContainsKey($id)) { continue } $seenId[$id] = $true $meta = Get-ModelMetadata $id $e = [ordered]@{ name = $id } if ($meta.Label) { $e['labelOverride'] = $meta.Label } if ($meta.Tier) { $e['anthropicFamilyTier'] = $meta.Tier } if ($meta.Supports1M) { $e['supports1m'] = $true if ($script:Opt.Prefer1M) { $e['prefer1m'] = $true } } if ($meta.Tier -and -not $seenTier.ContainsKey($meta.Tier)) { $e['isFamilyDefault'] = $true $seenTier[$meta.Tier] = $true } $entries += , ([pscustomobject]$e) } return [pscustomobject]@{ Source = $source; Entries = $entries } } function ConvertTo-ModelsJson([object[]]$Entries) { $json = ConvertTo-Json -InputObject @($Entries) -Compress -Depth 5 # Safety guard for PS 5.1 single-element arrays if (-not $json.TrimStart().StartsWith('[')) { $json = '[' + $json + ']' } return $json } function Build-WorkspaceJson([string[]]$Folders) { $list = @() foreach ($f in @($Folders)) { $p = ([string]$f).Trim() if (-not $p) { continue } $list += [pscustomobject]@{ path = $p; isDefaultSelected = $true } } if ($list.Count -eq 0) { return '' } $json = ConvertTo-Json -InputObject @($list) -Compress -Depth 5 if (-not $json.TrimStart().StartsWith('[')) { $json = '[' + $json + ']' } return $json } function Get-HttpErrorInfo($ErrRecord) { $httpStatus = $null try { $httpStatus = [int]$ErrRecord.Exception.Response.StatusCode } catch { $httpStatus = $null } $body = '' try { if ($null -ne $ErrRecord.ErrorDetails -and $ErrRecord.ErrorDetails.Message) { $body = [string]$ErrRecord.ErrorDetails.Message } elseif ($ErrRecord.Exception.Response -is [System.Net.HttpWebResponse]) { $reader = New-Object IO.StreamReader($ErrRecord.Exception.Response.GetResponseStream()) try { $body = $reader.ReadToEnd() } finally { $reader.Dispose() } } } catch { $body = '' } $body = ($body -replace '\s+', ' ').Trim() if ($body.Length -gt 220) { $body = $body.Substring(0, 220) + '...' } return [pscustomobject]@{ StatusCode = $httpStatus Body = $body Text = if ($null -ne $httpStatus) { ('HTTP ' + $httpStatus + $(if ($body) { ' ' + $body } else { '' })) } else { ((U '\u8fde\u63a5\u5931\u8d25: ') + $ErrRecord.Exception.Message) } } } function Test-NewApiGateway([string]$BaseUrl, [string]$Key, [bool]$RunProbe) { $base = $BaseUrl.TrimEnd('/') $headers = @{ 'Authorization' = ('Bearer ' + $Key) } $res = [pscustomobject]@{ KeyState = 'unknown' # valid | invalid | expired | unknown AllModels = @() ClaudeModels = @() ProbeCode = 0 ProbeOk = $false ProbeModel = '' SubscriptionNote = '' } Say-Step ((U 'New API \u8fde\u901a\u6027\u4e0e\u5bc6\u94a5\u6821\u9a8c ') + $base) # 1. GET /v1/models (New API validates the sk-xxx token here AND returns this key's allowed models) try { $resp = Invoke-WebRequest -Uri ($base + '/v1/models') -Headers $headers -UseBasicParsing -TimeoutSec 20 $rawText = if ($resp.Content -is [byte[]]) { [Text.Encoding]::UTF8.GetString($resp.Content) } else { [string]$resp.Content } $parsed = $rawText | ConvertFrom-Json $all = @() if ($parsed -and $parsed.data) { foreach ($item in @($parsed.data)) { if ($item -and $item.id) { $all += [string]$item.id } } } $claudeOnly = @($all | Where-Object { Test-ModelAcceptedByApp $_ }) $res.KeyState = 'valid' $res.AllModels = $all $res.ClaudeModels = $claudeOnly Say-Ok ('GET /v1/models -> HTTP ' + [int]$resp.StatusCode + (U ' (\u5bc6\u94a5\u6709\u6548\uff0c\u5171 ') + $all.Count + (U ' \u4e2a\u6a21\u578b\uff0c\u5176\u4e2d Claude \u6a21\u578b ') + $claudeOnly.Count + (U ' \u4e2a)')) } catch { $info = Get-HttpErrorInfo $_ if ($info.StatusCode -eq 401 -or $info.StatusCode -eq 403) { Say-Err ('GET /v1/models -> ' + $info.Text) Say-Err (U '\u5bc6\u94a5\u65e0\u6548\u3001\u5df2\u88ab\u7981\u7528\u6216\u65e0\u6743\u9650\u3002') $res.KeyState = 'invalid' return $res } Say-Warn ('GET /v1/models -> ' + $info.Text) Say-Warn (U '\u6682\u65f6\u65e0\u6cd5\u8fde\u63a5\u5230\u7f51\u5173 (\u8bf7\u68c0\u67e5\u7f51\u7edc\u3001\u4ee3\u7406\u6216\u9632\u706b\u5899)\u3002') } # 2. Optional billing/subscription check (non-fatal; detects expired tokens early) if ($res.KeyState -eq 'valid') { try { $subResp = Invoke-WebRequest -Uri ($base + '/v1/dashboard/billing/subscription') -Headers $headers -UseBasicParsing -TimeoutSec 10 $subText = if ($subResp.Content -is [byte[]]) { [Text.Encoding]::UTF8.GetString($subResp.Content) } else { [string]$subResp.Content } $sub = $subText | ConvertFrom-Json if ($sub -and $sub.PSObject.Properties['access_until'] -and [long]$sub.access_until -gt 0) { $expUtc = ([datetime]'1970-01-01T00:00:00Z').AddSeconds([long]$sub.access_until).ToLocalTime() if ($expUtc -lt (Get-Date)) { $res.KeyState = 'expired' $res.SubscriptionNote = (U '\u8be5\u5bc6\u94a5\u5df2\u4e8e ') + $expUtc.ToString('yyyy-MM-dd HH:mm') + (U ' \u8fc7\u671f') Say-Err $res.SubscriptionNote return $res } else { $res.SubscriptionNote = (U '\u6709\u6548\u671f\u81f3: ') + $expUtc.ToString('yyyy-MM-dd HH:mm') Say (' ' + $res.SubscriptionNote) } } } catch { } } # 3. Real Anthropic /v1/messages probe (1-4 tokens on cheapest Claude model) if ($RunProbe -and $res.KeyState -eq 'valid') { $probePool = if ($res.ClaudeModels.Count -gt 0) { $res.ClaudeModels } else { $script:DefaultNewApiModels } # Prefer haiku for minimal token cost, then sonnet, then first available. $probeModel = @($probePool | Where-Object { $_ -match '(?i)haiku' }) | Select-Object -First 1 if (-not $probeModel) { $probeModel = @($probePool | Where-Object { $_ -match '(?i)sonnet' }) | Select-Object -First 1 } if (-not $probeModel) { $probeModel = $probePool[0] } $res.ProbeModel = [string]$probeModel $probeHeaders = @{ 'Authorization' = ('Bearer ' + $Key) 'anthropic-version' = '2023-06-01' 'x-app' = 'desktop' } $probeBody = ConvertTo-Json -InputObject ([ordered]@{ model = [string]$probeModel max_tokens = 4 messages = @(@{ role = 'user'; content = 'hi' }) }) -Compress -Depth 5 try { $pr = Invoke-WebRequest -Uri ($base + '/v1/messages') -Method Post -Headers $probeHeaders -ContentType 'application/json' -Body $probeBody -UseBasicParsing -TimeoutSec 40 $res.ProbeCode = [int]$pr.StatusCode $res.ProbeOk = ($res.ProbeCode -ge 200 -and $res.ProbeCode -lt 300) Say-Ok ('POST /v1/messages (' + $probeModel + ') -> HTTP ' + $res.ProbeCode + (U ' (\u63a8\u7406\u63a5\u53e3\u5b9e\u6d4b\u901a\u8fc7)')) } catch { $info = Get-HttpErrorInfo $_ $res.ProbeCode = if ($null -ne $info.StatusCode) { [int]$info.StatusCode } else { 0 } if ($res.ProbeCode -eq 401 -or $res.ProbeCode -eq 403) { Say-Err ('POST /v1/messages (' + $probeModel + ') -> ' + $info.Text) $res.KeyState = 'invalid' } elseif ($res.ProbeCode -eq 402 -or $info.Body -match '(?i)quota|insufficient|balance') { Say-Warn ('POST /v1/messages (' + $probeModel + ') -> ' + $info.Text) Say-Warn (U '\u8be5\u5bc6\u94a5\u4f59\u989d\u4e0d\u8db3\u6216\u989d\u5ea6\u5df2\u7528\u5b8c\uff0c\u8bf7\u5145\u503c\u540e\u4f7f\u7528\u3002') } else { Say-Warn ('POST /v1/messages (' + $probeModel + ') -> ' + $info.Text) Say-Warn (U '\u63a8\u7406\u63a2\u9488\u672a\u8fd4\u56de 200 (\u53ef\u80fd\u662f\u4e0a\u6e38\u4e34\u65f6\u7e41\u5fd9)\uff0c\u914d\u7f6e\u4ecd\u53ef\u7167\u5e38\u5199\u5165\u3002') } } } return $res } # ---------------------------------------------------------------- Policy Plan Builder function New-PolicyPlan([string]$BaseUrl, [string]$Key, [string]$ModelsJson, [string]$HiveLabel, [bool]$DisableAutoMode) { $plan = [ordered]@{} $plan['inferenceProvider'] = [pscustomobject]@{ Kind = 'String'; Data = 'gateway'; Secret = $false } $plan['inferenceGatewayBaseUrl'] = [pscustomobject]@{ Kind = 'String'; Data = $BaseUrl.TrimEnd('/'); Secret = $false } $plan['inferenceGatewayAuthScheme'] = [pscustomobject]@{ Kind = 'String'; Data = 'bearer'; Secret = $false } $plan['inferenceCredentialKind'] = [pscustomobject]@{ Kind = 'String'; Data = 'static'; Secret = $false } $plan['inferenceGatewayApiKey'] = [pscustomobject]@{ Kind = 'String'; Data = $Key; Secret = $true } $plan['inferenceModels'] = [pscustomobject]@{ Kind = 'String'; Data = $ModelsJson; Secret = $false } $plan['modelDiscoveryEnabled'] = [pscustomobject]@{ Kind = 'DWord'; Data = 0; Secret = $false } $plan['modelCatalogEnabled'] = [pscustomobject]@{ Kind = 'DWord'; Data = 0; Secret = $false } $plan['deploymentDisplayName'] = [pscustomobject]@{ Kind = 'String'; Data = $script:Opt.DisplayName.Trim(); Secret = $false } $plan['desktopHome'] = [pscustomobject]@{ Kind = 'String'; Data = 'standard'; Secret = $false } $plan['isClaudeCodeForDesktopEnabled'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } $plan['builtinBrowserEnabled'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } $plan['toolSearchEnabled'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } $plan['disableDeploymentModeChooser'] = [pscustomobject]@{ Kind = 'DWord'; Data = 0; Secret = $false } $plan['disableEssentialTelemetry'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } $plan['disableNonessentialTelemetry'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } $plan['disableNonessentialServices'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } $plan['skipWebFetchPreflight'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } if (-not $script:Opt.AllowAutoUpdates) { $plan['disableAutoUpdates'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } } if (-not $script:Opt.RestrictCoworkNetwork) { $plan['coworkEgressAllowedHosts'] = [pscustomobject]@{ Kind = 'String'; Data = '["*"]'; Secret = $false } } if ($HiveLabel -eq 'HKLM') { $plan['disableWslSessions'] = [pscustomobject]@{ Kind = 'DWord'; Data = 0; Secret = $false } } if ($DisableAutoMode) { $plan['autoModeEnabled'] = [pscustomobject]@{ Kind = 'DWord'; Data = 0; Secret = $false } } if ($script:Opt.Prefer1M) { $plan['modelPrefer1mContext'] = [pscustomobject]@{ Kind = 'DWord'; Data = 1; Secret = $false } } $wsJson = Build-WorkspaceJson $script:Opt.Folders if ($wsJson) { $plan['allowedWorkspaceFolders'] = [pscustomobject]@{ Kind = 'String'; Data = $wsJson; Secret = $false } } return $plan } # ---------------------------------------------------------------- Customer API Key Resolution function Clean-ApiKey([string]$Raw) { if ([string]::IsNullOrWhiteSpace($Raw)) { return '' } $k = $Raw.Trim() # Strip accidental surrounding quotes copied from chat messages if (($k.StartsWith('"') -and $k.EndsWith('"')) -or ($k.StartsWith("'") -and $k.EndsWith("'"))) { if ($k.Length -ge 2) { $k = $k.Substring(1, $k.Length - 2).Trim() } } # Remove any internal CR/LF from wrapped chat paste $k = ($k -replace '[\r\n\s]+', '') return $k } function Resolve-CustomerApiKey([bool]$AllowPrompt) { # 1. Explicit CLI argument if ($script:Opt.ApiKey) { return (Clean-ApiKey $script:Opt.ApiKey) } # 2. Environment variables foreach ($envName in 'NEWAPI_API_KEY', 'CLAUDE_API_KEY', 'ANTHROPIC_AUTH_TOKEN') { $v = [Environment]::GetEnvironmentVariable($envName) if (-not [string]::IsNullOrWhiteSpace($v)) { return (Clean-ApiKey $v) } } # 3. Optional api-key.txt sitting next to local script (convenient for per-customer zip bundles) if ($PSCommandPath) { $localKeyFile = Join-Path (Split-Path -Parent $PSCommandPath) 'api-key.txt' if (Test-Path -LiteralPath $localKeyFile -PathType Leaf) { try { $firstLine = (Read-Utf8TextStrict $localKeyFile) -split '\r?\n' | Where-Object { $_.Trim() -and -not $_.Trim().StartsWith('#') } | Select-Object -First 1 if ($firstLine) { Say ((U '\u5df2\u4ece\u540c\u76ee\u5f55 api-key.txt \u8bfb\u53d6\u5bc6\u94a5')) return (Clean-ApiKey ([string]$firstLine)) } } catch { } } } # 4. Interactive prompt if ($AllowPrompt -and (Test-InteractiveConsole)) { Write-Host '' Write-Host (U '\u8bf7\u7c98\u8d34\u4f60\u7684\u4e13\u5c5e API Key (sk-...) \u5e76\u6309\u56de\u8f66:') -ForegroundColor Yellow Write-Host (U ' (\u63d0\u793a: \u5728\u7a97\u53e3\u91cc\u70b9\u9f20\u6807\u53f3\u952e\u6216 Ctrl+V \u5373\u53ef\u7c98\u8d34\uff0c\u4e0d\u8981\u5305\u542b\u591a\u4f59\u7a7a\u683c)') -ForegroundColor DarkGray for ($attempt = 1; $attempt -le 3; $attempt++) { $entered = '' try { $entered = Read-Host 'API Key' } catch { return '' } $k = Clean-ApiKey $entered if ([string]::IsNullOrEmpty($k)) { Say-Warn (U '\u8f93\u5165\u4e3a\u7a7a\uff0c\u8bf7\u91cd\u65b0\u7c98\u8d34\u3002') continue } # Catch accidental double-paste (e.g. sk-xxxsk-xxx) if (($k -split 'sk-').Count -gt 2) { Say-Warn (U '\u68c0\u6d4b\u5230\u4f60\u53ef\u80fd\u7c98\u8d34\u4e86\u4e24\u6b21\u5bc6\u94a5\uff0c\u8bf7\u53ea\u7c98\u8d34\u4e00\u6b21\u540e\u56de\u8f66\u3002') continue } return $k } } return '' } function Show-ManualElevationHelp([string]$ActionHint) { Say-Warn (U '\u9700\u8981\u7ba1\u7406\u5458\u6743\u9650\u624d\u80fd\u5199\u5165\u6ce8\u518c\u8868\u7b56\u7565\u3002\u624b\u52a8\u64cd\u4f5c\u6b65\u9aa4:') Say (U ' 1. \u5728\u5f00\u59cb\u83dc\u5355\u641c\u7d22 PowerShell\uff0c\u53f3\u952e\u9009\u62e9\u300c\u4ee5\u7ba1\u7406\u5458\u8eab\u4efd\u8fd0\u884c\u300d(\u7528\u5e73\u65f6\u767b\u5f55\u7684\u8d26\u53f7)\u3002') if ($PSCommandPath) { Say (' 2. ' + (U '\u5728\u7ba1\u7406\u5458\u7a97\u53e3\u4e2d\u8fd0\u884c: ') + ('powershell -NoProfile -ExecutionPolicy Bypass -File "{0}" {1}' -f $PSCommandPath, $ActionHint)) } else { Say (' 2. ' + (U '\u5728\u7ba1\u7406\u5458\u7a97\u53e3\u4e2d\u91cd\u65b0\u7c98\u8d34\u521a\u624d\u7684\u5b89\u88c5\u547d\u4ee4\u3002')) } Say '' Say (U '\u5982\u679c\u516c\u53f8\u7535\u8111\u6ca1\u6709\u7ba1\u7406\u5458\u6743\u9650\uff0c\u53ef\u5728 Claude \u684c\u9762\u7248\u5185\u624b\u52a8\u914d\u7f6e:') Say ((U ' \u5e2e\u52a9 -> \u7591\u96be\u89e3\u7b54 -> \u542f\u7528\u5f00\u53d1\u8005\u6a21\u5f0f -> \u5f00\u53d1\u8005 -> \u914d\u7f6e\u7b2c\u4e09\u65b9\u63a8\u7406 -> \u7f51\u5173 -> ') + $script:Opt.BaseUrl.TrimEnd('/')) } # ---------------------------------------------------------------- Main Actions function Invoke-ApplyRegistryWithElevation([string]$HiveLabel, $Plan, $State, [string[]]$DeleteNames) { $target = Get-PolicyTarget $HiveLabel $mustBeAbsent = @() foreach ($d in @($DeleteNames)) { $inPlan = $false foreach ($pk in @($Plan.Keys)) { if ($pk -ieq $d) { $inPlan = $true; break } } if (-not $inPlan) { $mustBeAbsent += $d } } if (Test-PolicyWritable $target) { Invoke-PolicyApplyDirect $HiveLabel $Plan $State $mustBeAbsent return } if (Test-IsAdmin) { Fail ((U '\u5373\u4f7f\u5df2\u662f\u7ba1\u7406\u5458\uff0c\u4e5f\u65e0\u6cd5\u5199\u5165 ') + $target.WinPath + (U '\uff0c\u53ef\u80fd\u88ab\u516c\u53f8\u7ec4\u7b56\u7565\u9501\u5b9a\u3002')) } if ($script:Opt.NoElevate) { Show-ManualElevationHelp '' Fail (U '\u6ca1\u6709\u7ba1\u7406\u5458\u6743\u9650\uff0c\u672a\u4fee\u6539\u4efb\u4f55\u8bbe\u7f6e\u3002') } # Prepare state records in parent before elevated worker writes registry $existingValues = @(Get-PolicyValues $target) $existed = ((Test-PolicyKeyState $target) -eq 'present') if ($existed -and -not ([string]$State.AppliedAt)) { $State.KeyExistedBefore = $true } $allTouched = @() foreach ($n in @($Plan.Keys)) { $allTouched += [string]$n } foreach ($d in $mustBeAbsent) { if ($allTouched -notcontains $d) { $allTouched += [string]$d } } $recorded = @($State.Values) foreach ($name in $allTouched) { $found = $null foreach ($r in $recorded) { if ([string]$r.Name -ieq $name) { $found = $r; break } } if ($null -eq $found) { $prev = $null foreach ($ev in $existingValues) { if ($ev.Name -ieq $name) { $prev = $ev; break } } $inPlan = $false foreach ($pk in @($Plan.Keys)) { if ($pk -ieq $name) { $inPlan = $true; break } } if (-not $inPlan -and $null -eq $prev) { continue } $rec = [pscustomobject]@{ Name = $name; Existed = [bool]($null -ne $prev); PrevName = ''; PrevKind = ''; PrevData = $null; PrevDataIsBase64 = $false } if ($prev) { $rec.PrevName = [string]$prev.Name $rec.PrevKind = [string]$prev.Kind if ($prev.Data -is [byte[]]) { $rec.PrevData = [Convert]::ToBase64String($prev.Data); $rec.PrevDataIsBase64 = $true } else { $rec.PrevData = $prev.Data } } $recorded += $rec } } $extraRestores = @() if ([string]$State.AppliedAt) { $kept = @() foreach ($rec in $recorded) { $still = $false foreach ($tn in $allTouched) { if ($tn -ieq [string]$rec.Name) { $still = $true; break } } if ($still) { $kept += $rec } else { $extraRestores += $rec } } $State.Values = @($kept) } else { $State.Values = @($recorded) } $backupPath = '' if ($existed -and -not ([string]$State.BackupFile)) { New-Item -ItemType Directory -Path $script:StateDir -Force | Out-Null $backupPath = Join-Path $script:StateDir ('registry-backup-' + (Get-Date -Format 'yyyyMMdd-HHmmss-fff') + '.reg') } $planArray = @() foreach ($k in @($Plan.Keys)) { $planArray += [ordered]@{ Name = [string]$k; Kind = [string]$Plan[$k].Kind; Data = $Plan[$k].Data } } $ok = Confirm-YesNo (U '\u5199\u5165\u6ce8\u518c\u8868\u7b56\u7565\u9700\u8981\u7ba1\u7406\u5458\u6743\u9650\uff0c\u73b0\u5728\u5f39\u51fa UAC \u786e\u8ba4\u6846\u5417?') $true if (-not $ok) { Show-ManualElevationHelp '' Fail (U '\u5df2\u53d6\u6d88\u7ba1\u7406\u5458\u63d0\u6743\uff0c\u672a\u4fee\u6539\u4efb\u4f55\u8bbe\u7f6e\u3002') } Say (U '\u5373\u5c06\u5f39\u51fa Windows \u7528\u6237\u8d26\u6237\u63a7\u5236\u786e\u8ba4\u6846\uff0c\u8bf7\u70b9\u300c\u662f\u300d...') $wRes = Invoke-ElevatedRegistryWorker @{ Action = 'apply' Hive = $HiveLabel SubPath = $script:PolicySubPath CallerSid = (Get-CurrentSid) Plan = $planArray DeleteNames = $mustBeAbsent ExtraRestores = $extraRestores BackupPath = $backupPath } foreach ($ln in @($wRes.Logs)) { Say ('[Admin] ' + $ln) } if ($wRes.BackupFile) { $State.BackupFile = $wRes.BackupFile } # Independent readback verification in parent process (do not trust child exit code blindly) $verified = $false $base = $null; $ro = $null try { $base = Open-PolicyBaseKey $HiveLabel $ro = $base.OpenSubKey($script:PolicySubPath, $false) if ($ro) { $verified = Test-PolicyMatchesOnKey $ro $Plan $mustBeAbsent } } catch { $verified = $false } finally { if ($ro) { try { $ro.Close() } catch { } } if ($base) { try { $base.Close() } catch { } } } if (-not $verified) { if (-not $wRes.Started) { Show-ManualElevationHelp '' Fail (U '\u672a\u83b7\u5f97\u7ba1\u7406\u5458\u6743\u9650 (UAC \u88ab\u53d6\u6d88\u6216\u65e0\u6cd5\u542f\u52a8)\uff0c\u672a\u4fee\u6539\u4efb\u4f55\u8bbe\u7f6e\u3002') } $errDetail = if ($wRes.Error) { ': ' + $wRes.Error } else { '' } Fail ((U '\u7ba1\u7406\u5458\u5199\u5165\u6ce8\u518c\u8868\u540e\u6821\u9a8c\u672a\u901a\u8fc7') + $errDetail) } } function Invoke-UninstallRegistryWithElevation($State) { $hiveLabel = [string]$State.Hive $target = Get-PolicyTarget $hiveLabel if ((Test-PolicyKeyState $target) -eq 'absent') { Say ((U '\u6ce8\u518c\u8868\u7b56\u7565\u9879\u5df2\u4e0d\u5b58\u5728: ') + $target.WinPath) return } if (Test-PolicyWritable $target) { Invoke-PolicyUninstallDirect $State return } if ($script:Opt.NoElevate) { Show-ManualElevationHelp '-Uninstall' Fail (U '\u6ca1\u6709\u7ba1\u7406\u5458\u6743\u9650\uff0c\u672a\u8fd8\u539f\u6ce8\u518c\u8868\u7b56\u7565\u3002') } $ok = Confirm-YesNo (U '\u8fd8\u539f\u6ce8\u518c\u8868\u7b56\u7565\u9700\u8981\u7ba1\u7406\u5458\u6743\u9650\uff0c\u73b0\u5728\u5f39\u51fa UAC \u786e\u8ba4\u6846\u5417?') $true if (-not $ok) { Show-ManualElevationHelp '-Uninstall' Fail (U '\u5df2\u53d6\u6d88\u7ba1\u7406\u5458\u63d0\u6743\uff0c\u672a\u8fd8\u539f\u4efb\u4f55\u8bbe\u7f6e\u3002') } $wRes = Invoke-ElevatedRegistryWorker @{ Action = 'uninstall' Hive = $hiveLabel SubPath = $script:PolicySubPath CallerSid = (Get-CurrentSid) KeyExistedBefore = [bool]$State.KeyExistedBefore Values = @($State.Values) } foreach ($ln in @($wRes.Logs)) { Say ('[Admin] ' + $ln) } # Independent verification in parent $problems = @() $base = $null; $ro = $null try { $base = Open-PolicyBaseKey $hiveLabel $ro = $base.OpenSubKey($script:PolicySubPath, $false) if ($ro) { foreach ($v in @($State.Values)) { $cur = Get-PolicyValueOnKey $ro ([string]$v.Name) if ([bool]$v.Existed) { if (-not $cur) { $problems += ('not restored: ' + [string]$v.Name); continue } $curStr = if ($cur.Data -is [byte[]]) { [Convert]::ToBase64String($cur.Data) } else { [string]$cur.Data } if ($curStr -cne [string]$v.PrevData) { $problems += ('mismatch: ' + [string]$v.Name) } } elseif ($cur) { $problems += ('still present: ' + [string]$cur.Name) } } } } catch { $problems += $_.Exception.Message } finally { if ($ro) { try { $ro.Close() } catch { } } if ($base) { try { $base.Close() } catch { } } } if ($problems.Count -gt 0) { Fail ((U '\u6ce8\u518c\u8868\u8fd8\u539f\u6821\u9a8c\u672a\u901a\u8fc7: ') + ($problems -join '; ')) } } function Invoke-Setup { $baseUrl = $script:Opt.BaseUrl.Trim().TrimEnd('/') if ($baseUrl -notmatch '^https?://') { Fail ((U '\u7f51\u5173\u5730\u5740\u683c\u5f0f\u4e0d\u6b63\u786e: ') + $baseUrl) } Write-Host '' Write-Host ((U '=== Claude \u684c\u9762\u7248 New API \u63a5\u5165\u5de5\u5177 v') + $script:ScriptVersion + ' ===') -ForegroundColor Cyan Say-Step (U '\u73af\u5883\u68c0\u6d4b') $archNote = if ([Environment]::Is64BitOperatingSystem) { if ([Environment]::Is64BitProcess) { '64-bit OS / 64-bit PowerShell' } else { '64-bit OS / 32-bit PowerShell (Registry64 auto-enabled)' } } else { '32-bit OS' } Say ((U '\u5f53\u524d Windows \u7528\u6237: ') + $env:USERNAME + ' (' + $script:UserProfileDir + ')') Say ((U '\u8fd0\u884c\u73af\u5883: ') + 'PowerShell ' + $PSVersionTable.PSVersion.ToString() + ' | ' + $archNote + $(if (Test-IsAdmin) { ' | Admin' } else { '' })) $app = Find-ClaudeDesktop if ($app.Installed) { Say-Ok ((U 'Claude \u684c\u9762\u7248: \u5df2\u5b89\u88c5 (') + $app.Kind + (U '\uff0c\u7248\u672c ') + $(if ($app.AppVersion) { $app.AppVersion } else { U '\u672a\u77e5' }) + ')') if ($app.DualInstall) { Say-Warn (U '\u68c0\u6d4b\u5230\u7535\u8111\u4e0a\u540c\u65f6\u5b89\u88c5\u4e86 MSIX \u5546\u5e97\u7248\u548c\u4f20\u7edf EXE \u7248\u4e24\u4efd Claude\uff01') Say-Warn (U '\u5efa\u8bae\u5230\u300cWindows \u8bbe\u7f6e -> \u5e94\u7528\u300d\u5378\u8f7d\u65e7\u7684\u4f20\u7edf\u7248\uff0c\u907f\u514d\u6253\u5f00\u9519\u7248\u672c\u3002') } if ($app.AppVersion -and -not (Test-VersionAtLeast $app.AppVersion $script:MinVersion3p)) { Say-Err ((U '\u5f53\u524d Claude \u7248\u672c\u592a\u65e7 (') + $app.AppVersion + (U ')\uff0c\u4e0d\u652f\u6301\u7b2c\u4e09\u65b9\u7f51\u5173\u6a21\u5f0f (\u81f3\u5c11\u9700\u8981 ') + $script:MinVersion3p + ')!') Say ((U '\u8bf7\u5148\u5347\u7ea7\u5b98\u65b9 Claude \u684c\u9762\u7248: ') + $script:DownloadUrl) if ($app.Packaged) { Say (U '\u5546\u5e97\u7248\u53ef\u5728 Microsoft Store -> \u5e93 -> \u83b7\u53d6\u66f4\u65b0 \u4e2d\u5347\u7ea7\u3002') } if (-not $script:Opt.Preview) { $cont = Confirm-YesNo (U '\u7248\u672c\u8fc7\u65e7\uff0c\u4ecd\u8981\u5148\u9884\u5199\u914d\u7f6e (\u7b49\u5347\u7ea7 App \u540e\u81ea\u52a8\u751f\u6548) \u5417?') $false if (-not $cont) { Fail (U '\u8bf7\u5148\u5347\u7ea7 Claude \u684c\u9762\u7248\u540e\u91cd\u8bd5\u3002') } } } elseif ($app.AppVersion -and -not (Test-VersionAtLeast $app.AppVersion $script:MinVersionFull)) { Say-Warn ((U '\u5f53\u524d\u7248\u672c ') + $app.AppVersion + (U ' \u53ef\u7528\u7f51\u5173\u6a21\u5f0f\uff0c\u4f46\u5efa\u8bae\u5347\u7ea7\u5230 ') + $script:MinVersionFull + (U ' \u6216\u66f4\u65b0\u4ee5\u83b7\u5f97\u5b8c\u6574 5.5 \u601d\u8003\u5f3a\u5ea6\u548c\u529f\u80fd\u3002')) } elseif ($app.AppVersion -and -not (Test-VersionAtLeast $app.AppVersion $script:BypassMinVersion) -and -not $script:Opt.KeepPermissionPrompts) { Say-Warn ((U 'App \u7248\u672c\u4f4e\u4e8e ') + $script:BypassMinVersion + (U '\uff0c\u9ed8\u8ba4 Bypass \u9884\u5199\u5c06\u81ea\u52a8\u8df3\u8fc7\u3002')) } } else { Say-Warn (U '\u672a\u68c0\u6d4b\u5230\u5df2\u5b89\u88c5\u7684 Claude \u684c\u9762\u7248\u3002') Say ((U '\u914d\u7f6e\u53ef\u4ee5\u5148\u5199\u597d\uff0c\u4e4b\u540e\u4ece\u5b98\u7f51 ') + $script:DownloadUrl + (U ' \u5b89\u88c5\u5b98\u65b9 App \u6253\u5f00\u5373\u53ef\u81ea\u52a8\u751f\u6548\u3002')) } $legacyPending = Test-LegacyDataFolderPending if ($legacyPending) { Say-Warn ((U '\u53d1\u73b0\u65e7\u7248\u6570\u636e\u76ee\u5f55 ') + (Join-Path $script:RoamingAppData 'Claude-3p') + (U ' (\u4e0d\u4f1a\u5220\u9664\uff0c\u7531 Claude \u81ea\u884c\u8fc1\u79fb)\u3002')) } # Hive selection & HKLM shadowing check $hiveLabel = if ($script:Opt.CurrentUser) { 'HKCU' } else { 'HKLM' } $hklmVals = @(Get-PolicyValues (Get-PolicyTarget 'HKLM')) $hasHklmClaudePolicy = (@($hklmVals | Where-Object { $_.Name -match '(?i)^inference|deploymentMode|disableClaudeAiSignIn|desktopHome' }).Count -gt 0) if ($hiveLabel -eq 'HKCU' -and $hasHklmClaudePolicy) { Say-Warn (U '\u68c0\u6d4b\u5230\u672c\u673a\u5df2\u6709\u6574\u673a\u7ea7 (HKLM) Claude \u7b56\u7565\uff0c\u5b83\u4f1a\u8986\u76d6\u5f53\u524d\u7528\u6237 (HKCU) \u914d\u7f6e\uff01') Say-Warn (U '\u8bf7\u53bb\u6389 -CurrentUser \u91cd\u65b0\u8fd0\u884c\u3002') if (-not $script:Opt.Preview) { Fail (U 'HKLM \u5df2\u5b58\u5728 Claude \u7b56\u7565\u4f1a\u906e\u6321 HKCU\uff0c\u8bf7\u4f7f\u7528\u9ed8\u8ba4 HKLM \u6a21\u5f0f\u8fd0\u884c\u3002') } } # Resolve customer API key $key = Resolve-CustomerApiKey (-not $script:Opt.Preview) if (-not $key) { if ($script:Opt.Preview) { Say-Warn (U '\u672a\u63d0\u4f9b API Key (\u9884\u89c8\u6a21\u5f0f\u7ee7\u7eed)\u3002') } else { Fail (U '\u672a\u63d0\u4f9b API Key\uff0c\u65e0\u6cd5\u7ee7\u7eed\u3002\u53ef\u901a\u8fc7 -ApiKey sk-xxx \u6216 $env:NEWAPI_API_KEY \u4f20\u5165\u3002') } } elseif ($key -notlike 'sk-*') { Say-Warn (U '\u8be5\u5bc6\u94a5\u4e0d\u662f\u4ee5 sk- \u5f00\u5934\uff0c\u8bf7\u786e\u8ba4\u662f\u5426\u590d\u5236\u5b8c\u6574\u3002') } # Connectivity check + dynamic model discovery from New API $gwCheck = $null $discoveredClaude = @() if ($key -and -not $script:Opt.Offline) { $runProbe = (-not $script:Opt.NoProbe) $gwCheck = Test-NewApiGateway $baseUrl $key $runProbe if ($gwCheck.KeyState -eq 'invalid' -or $gwCheck.KeyState -eq 'expired') { if (-not $script:Opt.Preview) { Fail (U 'New API \u62d2\u7edd\u4e86\u8be5\u5bc6\u94a5\uff0c\u672a\u4fee\u6539\u672c\u673a\u4efb\u4f55\u914d\u7f6e\u3002\u8bf7\u6838\u5bf9\u5bc6\u94a5\u540e\u91cd\u8bd5\u3002') } } $discoveredClaude = @($gwCheck.ClaudeModels) } elseif ($script:Opt.Offline) { Say-Step (U '\u79bb\u7ebf\u6a21\u5f0f (\u5df2\u8df3\u8fc7\u8054\u7f51\u68c0\u67e5)') } # Build model list $modelBuild = New-ModelList $script:Opt.Models $discoveredClaude $modelEntries = @($modelBuild.Entries) $rejected = @($modelEntries | Where-Object { -not (Test-ModelAcceptedByApp ([string]$_.name)) }) if ($rejected.Count -eq $modelEntries.Count) { Fail ((U '\u6a21\u578b\u6e05\u5355\u4e2d\u6ca1\u6709 Claude \u684c\u9762\u7248\u652f\u6301\u7684 Anthropic/Claude \u6a21\u578b: ') + (($rejected | ForEach-Object { [string]$_.name }) -join ', ')) } foreach ($rm in $rejected) { Say-Warn ((U 'Claude \u684c\u9762\u7248\u4f1a\u81ea\u52a8\u4e22\u5f03\u975e Claude \u6a21\u578b: ') + [string]$rm.name) } if ($gwCheck -and $gwCheck.AllModels.Count -gt 0 -and $modelBuild.Source -eq 'custom') { foreach ($m in $modelEntries) { if ($gwCheck.AllModels -notcontains [string]$m.name) { Say-Warn ((U '\u63d0\u793a: \u8be5\u5bc6\u94a5\u5728 New API \u7684 /v1/models \u4e2d\u672a\u5217\u51fa\u6a21\u578b: ') + [string]$m.name) } } } $modelsJson = ConvertTo-ModelsJson $modelEntries $disableAutoMode = (-not $script:Opt.KeepPermissionPrompts) -and (-not $script:Opt.KeepAutoMode) $plan = New-PolicyPlan $baseUrl $key $modelsJson $hiveLabel $disableAutoMode # Preview summary Say-Step ((U '\u5c06\u5199\u5165\u7684\u6ce8\u518c\u8868\u7b56\u7565 ') + $hiveLabel + '\' + $script:PolicySubPath) foreach ($name in @($plan.Keys)) { $it = $plan[$name] $shown = if ([bool]$it.Secret) { Mask-Secret ([string]$it.Data) } else { [string]$it.Data } if ($shown.Length -gt 72) { $shown = $shown.Substring(0, 72) + '...' } Say (' {0} = [{1}] {2}' -f $name, $it.Kind, $shown) } $existingAll = @(Get-PolicyValues (Get-PolicyTarget $hiveLabel)) $conflictsPresent = @() $foreignPresent = @() foreach ($ev in $existingAll) { $inPlan = $false foreach ($pk in @($plan.Keys)) { if ($pk -ieq $ev.Name) { $inPlan = $true; break } } if ($inPlan) { continue } $isConflict = $false foreach ($ck in $script:Conflicting3pKeys) { if ($ck -ieq $ev.Name) { $isConflict = $true; break } } if ($isConflict) { $conflictsPresent += [string]$ev.Name } else { $foreignPresent += [string]$ev.Name } } if ($conflictsPresent.Count -gt 0) { Say-Warn ((U '\u5c06\u6e05\u7406\u65e7\u63a5\u5165\u5de5\u5177\u7559\u4e0b\u7684\u51b2\u7a81\u952e (\u5378\u8f7d\u65f6\u53ef\u8fd8\u539f): ') + ($conflictsPresent -join ', ')) } if ($foreignPresent.Count -gt 0) { Say ((U ' \u4fdd\u7559\u539f\u6709\u5176\u4ed6\u7b56\u7565\u952e (\u4e0d\u4f1a\u6539\u52a8): ') + ($foreignPresent -join ', ')) } $srcLabel = switch ($modelBuild.Source) { 'discovered' { U '\u81ea\u52a8\u4ece New API /v1/models \u83b7\u53d6' } 'custom' { U '\u81ea\u5b9a\u4e49 -Models \u53c2\u6570' } default { U '\u5185\u7f6e\u9ed8\u8ba4\u6e05\u5355' } } Say-Step ((U '\u6a21\u578b\u6e05\u5355 (') + $srcLabel + ')') foreach ($m in $modelEntries) { $lbl = if ($m.PSObject.Properties['labelOverride']) { ' (' + [string]$m.labelOverride + ')' } else { '' } $m1Tag = if ($m.PSObject.Properties['supports1m'] -and [bool]$m.supports1m) { ' [1M]' } else { '' } Say (' ' + [string]$m.name + $lbl + $m1Tag) } if ($script:Opt.Preview) { Say-Step (U '\u9884\u89c8\u7ed3\u675f (\u672a\u4fee\u6539\u4efb\u4f55\u8bbe\u7f6e)') Say (U '\u53bb\u6389 -Preview \u5373\u53ef\u6b63\u5f0f\u5199\u5165\u5e76\u91cd\u542f Claude \u684c\u9762\u7248\u3002') return } # Check running Claude processes before writing Say-Step (U '\u51c6\u5907\u5199\u5165\u914d\u7f6e') $procs = Get-ClaudeAppProcesses $app if ($procs.EnumerationFailed -and $app.Installed) { Fail (U '\u65e0\u6cd5\u786e\u8ba4 Claude \u684c\u9762\u7248\u662f\u5426\u5728\u8fd0\u884c\u3002\u8bf7\u5148\u4ece\u53f3\u4e0b\u89d2\u6258\u76d8\u5b8c\u5168\u9000\u51fa Claude \u540e\u91cd\u8bd5\u3002') } if ($procs.Unverified -gt 0) { Fail (U '\u6709 Claude \u8fdb\u7a0b\u65e0\u6cd5\u8bfb\u53d6\u8def\u5f84 (\u53ef\u80fd\u4ee5\u7ba1\u7406\u5458\u8eab\u4efd\u8fd0\u884c\u4e2d)\u3002\u8bf7\u5148\u4ece\u53f3\u4e0b\u89d2\u6258\u76d8\u5b8c\u5168\u9000\u51fa Claude \u540e\u91cd\u8bd5\u3002') } $wasRunning = (@($procs.Target).Count -gt 0) if ($wasRunning) { if ($script:Opt.NoRestart) { Fail (U 'Claude \u684c\u9762\u7248\u6b63\u5728\u8fd0\u884c\u3002\u8bf7\u5148\u5b8c\u5168\u9000\u51fa\uff0c\u6216\u53bb\u6389 -NoRestart \u8ba9\u811a\u672c\u81ea\u52a8\u91cd\u542f\u5b83\u3002') } Say (U '\u6b63\u5728\u5173\u95ed\u8fd0\u884c\u4e2d\u7684 Claude \u684c\u9762\u7248...') if (-not (Stop-ClaudeApp $app)) { Fail (U '\u6709 Claude \u8fdb\u7a0b\u672a\u80fd\u9000\u51fa\uff0c\u8bf7\u624b\u52a8\u4ece\u53f3\u4e0b\u89d2\u6258\u76d8\u5b8c\u5168\u9000\u51fa\u540e\u91cd\u8bd5\u3002') } Say-Ok (U '\u5df2\u5173\u95ed Claude \u684c\u9762\u7248') } # Check if we need to fall back to HKCU when user declines/cannot UAC and HKCU is clean & writable $state = Load-State if ($null -eq $state) { $state = New-State $hiveLabel } elseif ([string]$state.Hive -ne $hiveLabel -or [string]$state.PolicyPath -cne $script:PolicySubPath) { Say-Warn ((U '\u4e4b\u524d\u5199\u5728 ') + $state.Hive + (U '\uff0c\u73b0\u5728\u5207\u6362\u5230 ') + $hiveLabel + (U '\uff0c\u5148\u8fd8\u539f\u539f\u4f4d\u7f6e...')) Invoke-UninstallRegistryWithElevation $state Invoke-ConfigUninstall $state $state = New-State $hiveLabel } try { try { Invoke-ApplyRegistryWithElevation $hiveLabel $plan $state $conflictsPresent } catch { # If HKLM elevation failed/declined AND HKLM has no blocking policy AND HKCU is writable, offer HKCU fallback. $hkcuTarget = Get-PolicyTarget 'HKCU' if ($hiveLabel -eq 'HKLM' -and -not $hasHklmClaudePolicy -and (Test-PolicyWritable $hkcuTarget)) { Say-Warn (U 'HKLM \u5199\u5165\u672a\u5b8c\u6210\uff0c\u4f46\u68c0\u6d4b\u5230\u5f53\u524d\u7528\u6237 HKCU \u53ef\u514d\u7ba1\u7406\u5458\u5199\u5165\u3002') $useHkcu = Confirm-YesNo (U '\u662f\u5426\u6539\u4e3a\u5199\u5165\u5f53\u524d\u7528\u6237 HKCU (\u4e0d\u9700\u8981\u7ba1\u7406\u5458\u6743\u9650)?') $true if ($useHkcu) { $hiveLabel = 'HKCU' $state.Hive = 'HKCU' $plan = New-PolicyPlan $baseUrl $key $modelsJson 'HKCU' $disableAutoMode Invoke-PolicyApplyDirect 'HKCU' $plan $state $conflictsPresent } else { throw } } else { throw } } Say-Ok ((U '\u6ce8\u518c\u8868\u7b56\u7565\u5df2\u5199\u5165\u5e76\u6821\u9a8c: ') + $hiveLabel + '\' + $script:PolicySubPath) Invoke-ConfigApply $app $state $state.BaseUrl = $baseUrl $state.AppliedAt = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss') Save-State $state Say-Ok ((U '\u5199\u5165\u8bb0\u5f55\u5df2\u4fdd\u5b58: ') + $script:StateFile) } catch { if ($wasRunning -and -not $script:Opt.NoRestart) { try { $null = Start-ClaudeApp $app } catch { } } throw } # Restart / launch Claude Desktop as the real logged-in user and verify 3P mode in main.log if ($app.Installed -and -not $script:Opt.NoRestart) { Say-Step (U '\u542f\u52a8 Claude \u684c\u9762\u7248\u5e76\u9a8c\u8bc1\u7f51\u5173\u6a21\u5f0f') $launchAt = Get-Date if (-not (Start-ClaudeApp $app)) { Say-Warn (U '\u914d\u7f6e\u5df2\u5199\u597d\uff0c\u4f46\u672a\u80fd\u81ea\u52a8\u542f\u52a8 Claude\uff0c\u8bf7\u4ece\u5f00\u59cb\u83dc\u5355\u624b\u52a8\u6253\u5f00\u3002') } else { Say (U '\u7b49\u5f85 Claude \u542f\u52a8\u5e76\u68c0\u67e5\u65e5\u5fd7 (\u6700\u591a 20 \u79d2)...') $gwLog = Wait-GatewayModeConfirmed $app $launchAt 20 if ($gwLog.Active -and -not $gwLog.Degraded) { Say-Step (U '\u5b8c\u6210') Say-Ok (U 'Claude \u684c\u9762\u7248\u5df2\u542f\u52a8\uff0c\u65e5\u5fd7\u786e\u8ba4\u5df2\u8fdb\u5165 New API \u7f51\u5173\u6a21\u5f0f\uff01') Say (' ' + (U '\u7f51\u5173\u5730\u5740: ') + $baseUrl) Say (' ' + (U '\u5de6\u4e0b\u89d2\u663e\u793a: ') + (Split-Path -Leaf $script:UserProfileDir) + (U ' \u00b7 ') + $script:Opt.DisplayName.Trim()) Say (' ' + (U '\u65e5\u5fd7\u786e\u8ba4: ') + $gwLog.Line) } elseif ($gwLog.Active) { Say-Step (U '\u5df2\u8fdb\u5165\u7f51\u5173\u6a21\u5f0f (\u4f46\u51ed\u636e\u5f02\u5e38)') Say-Warn (U 'App \u62a5\u544a degraded / \u65e0\u6709\u6548\u51ed\u636e\uff0c\u8bf7\u6838\u5bf9 API Key \u662f\u5426\u6b63\u786e\u3002') } else { Say-Step (U '\u914d\u7f6e\u5df2\u5199\u5165\uff0c\u4f46\u6682\u672a\u5728\u65e5\u5fd7\u4e2d\u786e\u8ba4\u5230 3P \u6a21\u5f0f') Say-Warn (U '20 \u79d2\u5185\u672a\u5728 main.log \u8bfb\u5230 [custom-3p] 3P mode active\u3002') Say (U ' 1. \u8bf7\u786e\u8ba4\u7a97\u53e3\u662f\u5426\u5df2\u8fdb\u5165\u5de5\u4f5c\u754c\u9762 (\u9996\u6b21\u542f\u52a8\u53ef\u80fd\u7a0d\u6162)\u3002') Say (U ' 2. \u5982\u679c\u6253\u5f00\u7684\u662f\u5b98\u65b9\u767b\u5f55\u9875\u6216\u300c\u5730\u533a\u4e0d\u53ef\u7528\u300d\uff0c\u8bf7\u4ece\u6258\u76d8\u5b8c\u5168\u9000\u51fa\u540e\u91cd\u65b0\u6253\u5f00\uff0c\u6216\u5347\u7ea7 Claude \u684c\u9762\u7248\u3002') Say ((U ' 3. \u65e5\u5fd7\u5019\u9009\u8def\u5f84: ') + ((@(Get-ClaudeLogCandidates $app) | Select-Object -First 4) -join ' ; ')) } } } else { Say-Step (U '\u5b8c\u6210') if ($app.Installed) { Say (U '\u8bf7\u5b8c\u5168\u9000\u51fa\u5e76\u91cd\u65b0\u6253\u5f00 Claude \u684c\u9762\u7248\u5373\u53ef\u4f7f\u7528\u3002') } else { Say ((U '\u914d\u7f6e\u5df2\u9884\u5199\u5b8c\u6210\u3002\u8bf7\u524d\u5f80 ') + $script:DownloadUrl + (U ' \u5b89\u88c5\u5b98\u65b9 Claude \u684c\u9762\u7248\uff0c\u5b89\u88c5\u540e\u6253\u5f00\u5373\u7528\u3002')) } } Say '' Say (U '\u5e38\u7528\u7ba1\u7406\u547d\u4ee4: -Status (\u67e5\u770b\u72b6\u6001) | -SwitchToOfficial (\u5207\u56de\u5b98\u65b9) | -Uninstall (\u5b8c\u5168\u8fd8\u539f)') } function Invoke-ModeSwitch([string]$TargetMode) { $app = Find-ClaudeDesktop $label = if ($TargetMode -ceq '1p') { U '\u5b98\u65b9 Claude.ai \u6a21\u5f0f (1p)' } else { U 'New API \u7f51\u5173\u6a21\u5f0f (3p)' } Say-Step ((U '\u5207\u6362\u6a21\u5f0f -> ') + $label) if ($TargetMode -ceq '3p') { $hasPolicy = $false foreach ($h in 'HKLM', 'HKCU') { if (@(Get-PolicyValues (Get-PolicyTarget $h) | Where-Object { $_.Name -ieq 'inferenceProvider' }).Count -gt 0) { $hasPolicy = $true } } if (-not $hasPolicy) { Fail (U '\u672a\u68c0\u6d4b\u5230 New API \u7f51\u5173\u7b56\u7565\uff0c\u8bf7\u5148\u8fd0\u884c\u5b89\u88c5\u811a\u672c\u914d\u7f6e API Key\u3002') } } $procs = Get-ClaudeAppProcesses $app $wasRunning = (@($procs.Target).Count -gt 0) if ($wasRunning) { if ($script:Opt.NoRestart) { Fail (U 'Claude \u6b63\u5728\u8fd0\u884c\uff0c\u8bf7\u5148\u5b8c\u5168\u9000\u51fa\u6216\u53bb\u6389 -NoRestart\u3002') } if (-not (Stop-ClaudeApp $app)) { Fail (U '\u65e0\u6cd5\u5173\u95ed Claude \u8fdb\u7a0b\uff0c\u8bf7\u624b\u52a8\u4ece\u6258\u76d8\u9000\u51fa\u540e\u91cd\u8bd5\u3002') } Say-Ok (U '\u5df2\u5173\u95ed Claude \u684c\u9762\u7248') } foreach ($p in @(Get-ConfigPaths $app)) { $null = Set-ConfigDeploymentModeSurgical $p $TargetMode $false $null Say-Ok ('deploymentMode=' + $TargetMode + ' -> ' + $p) } if ($app.Installed -and -not $script:Opt.NoRestart) { $extra = if ($TargetMode -ceq '1p') { @('--claude-first-party-sign-in') } else { @() } if (Start-ClaudeApp $app $extra) { Say-Ok (U '\u5df2\u91cd\u65b0\u6253\u5f00 Claude \u684c\u9762\u7248') } } Say-Ok ((U '\u5df2\u5207\u6362\u5230: ') + $label) } function Invoke-Uninstall { Say-Step (U '\u5378\u8f7d\u5e76\u8fd8\u539f New API \u63a5\u5165\u914d\u7f6e') $state = Load-State if ($null -eq $state) { Say-Warn (U '\u672a\u627e\u5230\u672c\u811a\u672c\u7684\u5199\u5165\u8bb0\u5f55 (state.json)\uff0c\u6ca1\u6709\u9700\u8981\u8fd8\u539f\u7684\u9879\u3002') return } $app = Find-ClaudeDesktop $procs = Get-ClaudeAppProcesses $app if ($procs.EnumerationFailed -and $app.Installed) { Fail (U '\u65e0\u6cd5\u786e\u8ba4 Claude \u662f\u5426\u5728\u8fd0\u884c\uff0c\u8bf7\u5148\u4ece\u6258\u76d8\u5b8c\u5168\u9000\u51fa\u540e\u91cd\u8bd5\u3002') } if ($procs.Unverified -gt 0) { Fail (U '\u6709 Claude \u8fdb\u7a0b\u65e0\u6cd5\u786e\u8ba4\u8def\u5f84\uff0c\u8bf7\u5148\u4ece\u6258\u76d8\u5b8c\u5168\u9000\u51fa\u540e\u91cd\u8bd5\u3002') } $wasRunning = (@($procs.Target).Count -gt 0) if ($wasRunning) { if ($script:Opt.NoRestart) { Fail (U 'Claude \u6b63\u5728\u8fd0\u884c\uff0c\u8bf7\u5148\u5b8c\u5168\u9000\u51fa\u6216\u53bb\u6389 -NoRestart\u3002') } if (-not (Stop-ClaudeApp $app)) { Fail (U '\u6709 Claude \u8fdb\u7a0b\u672a\u80fd\u9000\u51fa\uff0c\u8bf7\u624b\u52a8\u4ece\u6258\u76d8\u9000\u51fa\u540e\u91cd\u8bd5\u3002') } Say-Ok (U '\u5df2\u5173\u95ed Claude \u684c\u9762\u7248') } try { Invoke-UninstallRegistryWithElevation $state Invoke-ConfigUninstall $state } catch { if ($wasRunning -and -not $script:Opt.NoRestart) { try { $null = Start-ClaudeApp $app } catch { } } throw } Remove-Item -LiteralPath $script:StateFile -Force -ErrorAction SilentlyContinue Say-Ok (U '\u5df2\u5168\u90e8\u8fd8\u539f\uff0cClaude \u5df2\u56de\u5230\u5b98\u65b9\u6a21\u5f0f\u3002') Say ((U ' \u5907\u4efd\u6587\u4ef6 (\u5982\u6709) \u4fdd\u7559\u5728: ') + $script:StateDir) if ($wasRunning -and -not $script:Opt.NoRestart) { if (Start-ClaudeApp $app) { Say-Ok (U '\u5df2\u91cd\u65b0\u6253\u5f00 Claude \u684c\u9762\u7248') } } } function Show-Status { Say-Step (U '\u73af\u5883\u4e0e Claude \u684c\u9762\u7248') Say ((U '\u5f53\u524d\u7528\u6237: ') + $env:USERNAME + ' (' + $script:UserProfileDir + ')') $app = Find-ClaudeDesktop if ($app.Installed) { Say-Ok ((U 'Claude \u684c\u9762\u7248: ') + $app.Kind + (U '\uff0c\u7248\u672c ') + $(if ($app.AppVersion) { $app.AppVersion } else { U '\u672a\u77e5' })) if ($app.DualInstall) { Say-Warn (U '\u68c0\u6d4b\u5230\u53cc\u5b89\u88c5 (MSIX + \u4f20\u7edf EXE)\uff0c\u5efa\u8bae\u5378\u8f7d\u4f20\u7edf\u7248\u3002') } } else { Say-Warn (U '\u672a\u68c0\u6d4b\u5230 Claude \u684c\u9762\u7248') } Say-Step (U '\u672c\u811a\u672c\u7684\u5199\u5165\u8bb0\u5f55') $state = Load-State if ($null -eq $state) { Say (U '\u6ca1\u6709\u5199\u5165\u8bb0\u5f55\u3002') } else { Say-Ok ((U '\u5199\u5165\u65f6\u95f4: ') + $state.AppliedAt + ' | ' + $state.Hive + '\' + $state.PolicyPath + $(if ($state.BaseUrl) { ' | ' + $state.BaseUrl } else { '' })) } $hklmCount = 0 foreach ($h in 'HKLM', 'HKCU') { $vals = @(Get-PolicyValues (Get-PolicyTarget $h)) if ($h -eq 'HKLM') { $hklmCount = $vals.Count } $activeNote = if ($h -eq 'HKLM' -and $vals.Count -gt 0) { U ' (\u5f53\u524d\u751f\u6548\u5c42)' } elseif ($h -eq 'HKCU' -and $vals.Count -gt 0 -and $hklmCount -eq 0) { U ' (\u5f53\u524d\u751f\u6548\u5c42)' } elseif ($h -eq 'HKCU' -and $vals.Count -gt 0 -and $hklmCount -gt 0) { U ' (\u88ab HKLM \u8986\u76d6)' } else { '' } Say-Step ((U '\u6ce8\u518c\u8868\u7b56\u7565 ') + $h + '\' + $script:PolicySubPath + $activeNote) if ($vals.Count -eq 0) { Say (U ' \u4e0d\u5b58\u5728\u6216\u65e0\u914d\u7f6e\u503c'); continue } foreach ($v in $vals) { $txt = [string]$v.Data if ($v.Name -match '(?i)ApiKey|Token|Secret|Password') { $txt = Mask-Secret $txt } if ($txt.Length -gt 110) { $txt = $txt.Substring(0, 110) + '...' } Say (' {0} = [{1}] {2}' -f $v.Name, $v.Kind, $txt) } } Say-Step (U '\u6a21\u5f0f\u914d\u7f6e\u6587\u4ef6') foreach ($p in @(Get-ConfigPaths $app)) { if (-not (Test-Path -LiteralPath $p -PathType Leaf)) { Say (' ' + $p + (U ' (\u4e0d\u5b58\u5728)')); continue } $mode = U '(\u65e0\u6cd5\u89e3\u6790)' try { $raw = Read-Utf8TextStrict $p if (Test-JsonObjectText $raw) { $mr = Get-JsonPathRaw $raw @('deploymentMode') $mode = if ($null -ne $mr -and $mr.StartsWith('"')) { Decode-JsonString $mr } else { U '(\u672a\u8bbe\u7f6e)' } } } catch { } Say (' ' + $p + ' deploymentMode=' + $mode) } Say-Step (U 'App \u65e5\u5fd7\u6700\u8fd1\u4e00\u6b21\u7f51\u5173\u6a21\u5f0f\u8bb0\u5f55') $last = Test-GatewayModeInLog $app ([datetime]::MinValue) if (-not $last.AnyLogFound) { Say (U ' \u672a\u627e\u5230 Claude \u65e5\u5fd7\u6587\u4ef6 (App \u53ef\u80fd\u5c1a\u672a\u542f\u52a8\u8fc7)\u3002') } elseif (-not $last.Active) { Say (U ' \u65e5\u5fd7\u4e2d\u672a\u627e\u5230 [custom-3p] \u8bb0\u5f55\uff0cApp \u4e0a\u6b21\u53ef\u80fd\u8fd0\u884c\u5728\u5b98\u65b9\u6a21\u5f0f\u3002') } else { $deg = if ($last.Degraded) { U ' (degraded / \u51ed\u636e\u5f02\u5e38)' } else { '' } Say-Ok ($last.Line + $deg) Say ((U ' \u65e5\u5fd7\u6587\u4ef6: ') + $last.Log) } } # ---------------------------------------------------------------- Entrypoint function Invoke-Main { if ($script:Opt.Help) { Show-Usage; return } if ($script:Opt.BadArgs.Count -gt 0) { Say-Err ((U '\u672a\u77e5\u53c2\u6570: ') + ($script:Opt.BadArgs -join ', ')) Say (U '\u8fd0\u884c -Help \u67e5\u770b\u652f\u6301\u7684\u53c2\u6570\u3002\u672a\u4fee\u6539\u4efb\u4f55\u8bbe\u7f6e\u3002') Fail (U '\u53c2\u6570\u9519\u8bef\uff0c\u5df2\u4e2d\u6b62\u3002') } $modeCount = 0 foreach ($m in @($script:Opt.Preview, $script:Opt.Status, $script:Opt.Uninstall, $script:Opt.SwitchToOfficial, $script:Opt.SwitchToGateway)) { if ($m) { $modeCount++ } } if ($modeCount -gt 1) { Fail (U '-Preview / -Status / -Uninstall / -SwitchToOfficial / -SwitchToGateway \u4e00\u6b21\u53ea\u80fd\u9009\u4e00\u4e2a\u3002') } if ($script:Opt.Status) { Show-Status; return } if ($script:Opt.Uninstall) { Invoke-Uninstall; return } if ($script:Opt.SwitchToOfficial) { Invoke-ModeSwitch '1p'; return } if ($script:Opt.SwitchToGateway) { Invoke-ModeSwitch '3p'; return } Invoke-Setup } Parse-CliArgs $args # Dot-source or -LoadOnly skips auto-run (for unit tests) if ($MyInvocation.InvocationName -ne '.' -and -not $script:Opt.LoadOnly) { $exitCode = 0 try { Invoke-Main } catch { $msg = [string]$_.Exception.Message if ($msg -like 'NEWAPI_DONE::*') { $exitCode = 0 } elseif ($msg -like 'NEWAPI_FAIL::*') { Say-Err $msg.Substring(13) $exitCode = 1 } else { Say-Err $msg $exitCode = 1 } } finally { # Pause in interactive double-click / iex console when requested or when running via iex $isIex = [string]::IsNullOrEmpty($PSCommandPath) if (($script:Opt.Pause -or ($isIex -and $exitCode -ne 0)) -and (Test-InteractiveConsole)) { Write-Host '' Write-Host (U '\u6309\u56de\u8f66\u952e\u5173\u95ed...') -ForegroundColor DarkGray try { [void][Console]::ReadLine() } catch { } } } # Never call raw "exit" inside "irm | iex", otherwise it closes the customer's PowerShell window! if (-not [string]::IsNullOrEmpty($PSCommandPath)) { exit $exitCode } }