# 兼容 Windows PowerShell 5.1;所有状态只写入当前用户配置目录。 param( [ValidateSet('configure', 'restore')][string]$Action = 'configure', [string]$Model = '', [ValidateSet('zh', 'en')][string]$Lang = 'en' ) $ErrorActionPreference = 'Stop' $WarningPreference = 'Stop' class GetRunSetupException : System.Exception { GetRunSetupException([string]$Message) : base($Message) {} } function Stop-Setup([string]$Message) { throw [GetRunSetupException]::new($Message) } function Get-Message([string]$Zh, [string]$En) { if ($Lang -eq 'zh') { $Zh } else { $En } } function ConvertTo-Map($Value) { if ($null -eq $Value) { return $null } if ($Value -is [System.Management.Automation.PSCustomObject]) { $Map = [ordered]@{} foreach ($Property in $Value.PSObject.Properties) { $Map[$Property.Name] = ConvertTo-Map $Property.Value } return ,$Map } if ($Value -is [System.Collections.IList]) { return ,@($Value | ForEach-Object { ConvertTo-Map $_ }) } return $Value } function Read-ConfigBytes([string]$Path) { if (Test-Path -LiteralPath $Path) { $Item = Get-Item -Force -LiteralPath $Path if ($Item.PSIsContainer -or ($Item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { Stop-Setup (Get-Message '配置路径不是普通文件,请手动配置。' 'A configuration path is not a regular file. Configure manually.') } return ,([IO.File]::ReadAllBytes($Path)) } return $null } function Read-Object($Bytes) { if ($null -eq $Bytes) { return ,([ordered]@{}) } try { $Text = [Text.UTF8Encoding]::new($false, $true).GetString($Bytes).TrimStart([char]0xFEFF) if ($PSVersionTable.PSVersion.Major -ge 7) { $Options = [System.Text.Json.JsonDocumentOptions]::new() $Options.MaxDepth = 100 $Document = [System.Text.Json.JsonDocument]::Parse($Text, $Options) $Document.Dispose() } $Value = ConvertTo-Map (ConvertFrom-Json -InputObject $Text -ErrorAction Stop) if ($Value -isnot [System.Collections.IDictionary]) { throw 'object required' } return ,$Value } catch { Stop-Setup (Get-Message 'JSON 格式错误或不是对象,原配置未修改。' 'Invalid JSON or non-object configuration. The original file was not changed.') } } function Write-Atomic([string]$Path, [byte[]]$Bytes) { $Temporary = $Path + '.' + [guid]::NewGuid().ToString('N') + '.tmp' try { $Stream = [IO.File]::Open($Temporary, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) try { $Stream.Write($Bytes, 0, $Bytes.Length); $Stream.Flush() } finally { $Stream.Dispose() } if ([IO.File]::Exists($Path)) { [IO.File]::Replace($Temporary, $Path, [NullString]::Value) } else { [IO.File]::Move($Temporary, $Path) } } finally { if ([IO.File]::Exists($Temporary)) { [IO.File]::Delete($Temporary) } } } function Encode-Object($Value) { return ,([Text.UTF8Encoding]::new($false).GetBytes((ConvertTo-Json -InputObject $Value -Depth 100) + "`n")) } function Equal-Bytes($A, $B) { return (($null -eq $A -and $null -eq $B) -or ($null -ne $A -and $null -ne $B -and [Convert]::ToBase64String($A) -ceq [Convert]::ToBase64String($B))) } function Get-Snapshot([string]$Name) { if ($ConfigEnv.Contains($Name)) { return ,([ordered]@{ present = $true; value = $ConfigEnv[$Name] }) } return ,([ordered]@{ present = $false }) } function Equal-Snapshot($A, $B) { return ((ConvertTo-Json -InputObject $A -Depth 100 -Compress) -ceq (ConvertTo-Json -InputObject $B -Depth 100 -Compress)) } $LockStream = $null $Key = '' try { if ($Action -eq 'configure') { if (-not (Get-Command claude -ErrorAction SilentlyContinue)) { Stop-Setup (Get-Message '未找到 Claude Code。请先完成安装步骤。' 'Claude Code was not found. Complete the installation steps first.') } $SecureKey = Read-Host (Get-Message '粘贴 GetRun API Key 后按回车(输入隐藏)' 'Paste your GetRun API key and press Enter (input hidden)') -AsSecureString $Pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureKey) try { $Key = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($Pointer) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Pointer); $SecureKey.Dispose() } if (-not $Key -or $Key -match '[\x00-\x1f\x7f]') { Stop-Setup (Get-Message '未输入有效 Key,配置未修改。' 'No valid key entered. Configuration was not changed.') } } $Directory = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path ([Environment]::GetFolderPath('UserProfile')) '.claude' } $Directory = [IO.Path]::GetFullPath($Directory) [void][IO.Directory]::CreateDirectory($Directory) $SettingsPath = Join-Path $Directory 'settings.json' $StatePath = Join-Path $Directory 'getrun-setup-state.json' $LockPath = Join-Path $Directory '.getrun-setup.lock' try { $LockStream = [IO.File]::Open($LockPath, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) } catch { Stop-Setup (Get-Message '另一个配置任务正在运行;若之前被中断,请检查 .getrun-setup.lock 后再试。' 'Another setup is running. If interrupted, inspect .getrun-setup.lock before retrying.') } $Raw = Read-ConfigBytes $SettingsPath $StateRaw = Read-ConfigBytes $StatePath $Settings = Read-Object $Raw $State = Read-Object $StateRaw $ConfigEnv = if ($Settings.Contains('env')) { $Settings['env'] } else { [ordered]@{} } if ($ConfigEnv -isnot [System.Collections.IDictionary]) { Stop-Setup (Get-Message 'env 必须是 JSON 对象。' 'env must be a JSON object.') } if ($null -ne $StateRaw -and ($State['version'] -ne 1 -or $State['fields'] -isnot [System.Collections.IDictionary])) { Stop-Setup (Get-Message '恢复记录无法识别。' 'The restore record is not recognized.') } $Fields = if ($State.Contains('fields')) { $State['fields'] } else { [ordered]@{} } $BaseNames = @('ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY') $ModelNames = @('ANTHROPIC_MODEL', 'CLAUDE_CODE_SUBAGENT_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'ANTHROPIC_DEFAULT_FABLE_MODEL') foreach ($Name in @($Fields.Keys)) { $Entry = $Fields[$Name] if (($BaseNames + $ModelNames) -cnotcontains $Name -or $Entry -isnot [System.Collections.IDictionary] -or $Entry.Count -ne 2 -or -not $Entry.Contains('before') -or -not $Entry.Contains('after')) { Stop-Setup (Get-Message '恢复记录损坏。' 'The restore record is invalid.') } foreach ($Snapshot in @($Entry['before'], $Entry['after'])) { if ($Snapshot -isnot [System.Collections.IDictionary] -or $Snapshot['present'] -isnot [bool] -or ($Snapshot['present'] -and -not $Snapshot.Contains('value'))) { Stop-Setup (Get-Message '恢复记录损坏。' 'The restore record is invalid.') } } } $Skipped = @() if ($Action -eq 'configure') { foreach ($Flag in @('CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY')) { $Value = if ($ConfigEnv.Contains($Flag)) { $ConfigEnv[$Flag] } else { [Environment]::GetEnvironmentVariable($Flag) } if ([string]$Value -in @('1', 'true')) { Stop-Setup (Get-Message '已启用其他云服务商,请先检查手动配置。' 'Another cloud provider is enabled. Review the manual configuration first.') } } $Changes = [ordered]@{ ANTHROPIC_BASE_URL = 'https://api.get-apikey.com'; ANTHROPIC_AUTH_TOKEN = $Key; ANTHROPIC_API_KEY = '' } if ($Model) { foreach ($Name in $ModelNames) { $Changes[$Name] = $Model } } foreach ($Name in $Changes.Keys) { $Current = Get-Snapshot $Name $Before = if ($Fields.Contains($Name) -and (Equal-Snapshot $Current $Fields[$Name]['after'])) { $Fields[$Name]['before'] } else { $Current } $Fields[$Name] = [ordered]@{ before = $Before; after = [ordered]@{ present = $true; value = $Changes[$Name] } } $ConfigEnv[$Name] = $Changes[$Name] } } else { if (-not $Fields.Count) { Write-Output (Get-Message '没有需要恢复的配置。' 'There is no configuration to restore.'); return } foreach ($Name in @($Fields.Keys)) { $Entry = $Fields[$Name] if (-not (Equal-Snapshot (Get-Snapshot $Name) $Entry['after'])) { $Skipped += $Name; continue } if ($Entry['before']['present']) { $ConfigEnv[$Name] = $Entry['before']['value'] } else { $ConfigEnv.Remove($Name) } $Fields.Remove($Name) } } if ($ConfigEnv.Count -or $Settings.Contains('env')) { $Settings['env'] = $ConfigEnv } if (-not (Equal-Bytes (Read-ConfigBytes $SettingsPath) $Raw) -or -not (Equal-Bytes (Read-ConfigBytes $StatePath) $StateRaw)) { Stop-Setup (Get-Message '配置已被其他程序修改,请重新运行。' 'Another program changed the configuration. Run setup again.') } if ($null -ne $Raw) { $Backup = Join-Path $Directory ('settings.json.getrun-' + [guid]::NewGuid().ToString('N') + '.bak') Write-Atomic $Backup $Raw Write-Output ((Get-Message '原配置备份:' 'Configuration backup: ') + $Backup) } Write-Atomic $StatePath (Encode-Object ([ordered]@{ version = 1; fields = $Fields })) try { Write-Atomic $SettingsPath (Encode-Object $Settings) } catch { if ($null -eq $StateRaw) { [IO.File]::Delete($StatePath) } else { Write-Atomic $StatePath $StateRaw } throw } if ($Skipped.Count) { Write-Output ((Get-Message '以下字段后来被修改,已保留:' 'Kept fields changed after setup: ') + ($Skipped -join ', ')) } Write-Output (Get-Message '配置已保存。重启 Claude Code,运行 /status 检查地址和认证来源。' 'Configuration saved. Restart Claude Code and run /status to check the endpoint and authentication.') } catch { # 不输出整个异常记录,避免带出配置或用户输入。 if ($_.Exception -is [GetRunSetupException]) { throw $_.Exception } $Diagnostic = ' [' + $_.Exception.GetType().FullName + ':' + $_.InvocationInfo.ScriptLineNumber + ']' throw [Exception]::new((Get-Message '配置未完成。检查安装、JSON、文件权限、恢复记录或云服务商设置。' 'Setup failed. Check installation, JSON, permissions, restore records or cloud-provider settings.') + $Diagnostic) } finally { $Key = $null if ($null -ne $LockStream) { $LockStream.Dispose(); [IO.File]::Delete($LockPath) } }