#Requires -Version 5.1 function Invoke-SimpleClawInstaller { $ErrorActionPreference = 'Stop' $catalogUrl = 'https://simple-claw.ru/v1/models' $apiBase = 'https://simple-claw.ru' function Fail([string]$message) { throw "Ошибка: $message" } function JsonString([string]$value) { return ConvertTo-Json -InputObject $value -Compress } function Save-Text([string]$path, [string]$content, [switch]$PowerShellScript) { $directory = Split-Path -Parent $path [System.IO.Directory]::CreateDirectory($directory) | Out-Null if (Test-Path -LiteralPath $path) { $suffix = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssfffffffZ') $backup = "$path.backup-$suffix" Copy-Item -LiteralPath $path -Destination $backup Write-Host "Резервная копия: $backup" } $temporary = Join-Path $directory ('.simpleclaw-' + [guid]::NewGuid().ToString('N')) try { # Windows PowerShell 5.1 needs a BOM for script paths containing Cyrillic. # Configs and key files must remain UTF-8 without a BOM. $encoding = New-Object System.Text.UTF8Encoding($PowerShellScript.IsPresent) [System.IO.File]::WriteAllText($temporary, $content, $encoding) Move-Item -LiteralPath $temporary -Destination $path -Force } finally { if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force } } } function Set-Property($object, [string]$name, $value) { $object | Add-Member -MemberType NoteProperty -Name $name -Value $value -Force } function Read-OpenCodeConfig([string]$path) { if (-not (Test-Path -LiteralPath $path)) { return [pscustomobject]@{} } try { $text = [System.IO.File]::ReadAllText($path) $tokens = '"(?:\\.|[^"\\])*"|//[^\r\n]*|/\*[\s\S]*?\*/' $text = [regex]::Replace($text, $tokens, [System.Text.RegularExpressions.MatchEvaluator]{ param($match) if ($match.Value.StartsWith('"')) { return $match.Value }; return ' ' }) $text = [regex]::Replace($text, '"(?:\\.|[^"\\])*"|,\s*(?=[}\]])', [System.Text.RegularExpressions.MatchEvaluator]{ param($match) if ($match.Value.StartsWith('"')) { return $match.Value }; return '' }) $config = ConvertFrom-Json -InputObject $text if ($null -eq $config -or $config -isnot [pscustomobject]) { throw 'Not an object' } return $config } catch { Fail 'Не удалось прочитать JSON/JSONC-конфиг OpenCode; исходный файл сохранён.' } } function Object-Property($object, [string]$name) { if (-not $object.PSObject.Properties[$name]) { return [pscustomobject]@{} } $value = $object.$name if ($null -eq $value -or $value -isnot [pscustomobject]) { Fail "$name должен быть JSON-объектом." } return $value } function Protect-OpenCodeDirectory([string]$path) { if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User $acl = New-Object System.Security.AccessControl.DirectorySecurity $acl.SetAccessRuleProtection($true, $false) $acl.SetOwner($sid) $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') $acl.AddAccessRule($rule) Set-Acl -LiteralPath $path -AclObject $acl } else { & chmod 700 $path if ($LASTEXITCODE -ne 0) { Fail 'Не удалось ограничить доступ к личной папке ключа.' } } } function Protect-OpenCodeKeyFiles([string]$path) { foreach ($file in Get-ChildItem -LiteralPath $path -Filter 'opencode.key*' -File) { if ([Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT) { $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User $acl = New-Object System.Security.AccessControl.FileSecurity $acl.SetAccessRuleProtection($true, $false) $acl.SetOwner($sid) $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', 'Allow'))) Set-Acl -LiteralPath $file.FullName -AclObject $acl } else { & chmod 600 $file.FullName if ($LASTEXITCODE -ne 0) { Fail 'Не удалось ограничить доступ к файлу ключа.' } } } } Write-Host 'Подключение Simple Claw' Write-Host '1) Codex CLI / Codex App / IDE' Write-Host '2) Claude Code CLI' Write-Host '3) OpenCode' $choice = Read-Host 'Выберите клиент [1-3]' switch ($choice) { '1' { $client = 'codex'; $provider = 'openai'; $protocol = 'responses' } '2' { $client = 'claude-code'; $provider = 'anthropic'; $protocol = 'messages' } '3' { $client = 'opencode'; $provider = $null; $protocol = 'chat_completions' } default { Fail 'Выберите 1, 2 или 3.' } } try { $catalog = Invoke-RestMethod -Uri $catalogUrl -Method Get -TimeoutSec 30 } catch { Fail 'Не удалось загрузить каталог моделей Simple Claw.' } if ($null -eq $catalog -or $null -eq $catalog.data) { Fail 'Каталог не содержит data[].' } $models = @($catalog.data | Where-Object { ($null -eq $provider -or $_.owned_by -eq $provider) -and @($_.protocols) -contains $protocol -and $_.id -is [string] -and $_.id.Length -gt 0 -and $_.id -notmatch '[\r\n]' -and ($client -ne 'opencode' -or $_.id -notmatch '[{}\x00-\x1f\x7f]') } | ForEach-Object { $_.id } | Select-Object -Unique) if ($models.Count -eq 0) { Fail "В каталоге нет моделей с протоколом $protocol." } Write-Host "`nДоступные модели Simple Claw для $client`:`n" for ($index = 0; $index -lt $models.Count; $index++) { Write-Host ('{0,2}. {1}' -f ($index + 1), $models[$index]) } $numberText = Read-Host 'Номер модели' $number = 0 if (-not [int]::TryParse($numberText, [ref]$number) -or $number -lt 1 -or $number -gt $models.Count) { Fail 'Введите номер модели из списка.' } $model = [string]$models[$number - 1] $secureKey = Read-Host 'API-ключ Simple Claw (ввод скрыт)' -AsSecureString $plainKey = (New-Object System.Net.NetworkCredential('', $secureKey)).Password if (-not $plainKey.StartsWith('sc_') -or $plainKey.Length -lt 16 -or $plainKey -match '\s') { Fail 'Нужен API-ключ Simple Claw, начинающийся с sc_.' } $userProfilePath = if ($env:USERPROFILE) { $env:USERPROFILE } else { [Environment]::GetFolderPath('UserProfile') } $secretDirectory = Join-Path $env:LOCALAPPDATA 'SimpleClaw' [System.IO.Directory]::CreateDirectory($secretDirectory) | Out-Null $secretPath = Join-Path $secretDirectory "$client.key" $helperPath = Join-Path $secretDirectory "read-$client-key.ps1" $encryptedKey = ConvertFrom-SecureString -SecureString $secureKey $plainKey = $null $helper = @' $ErrorActionPreference = 'Stop' $encrypted = [System.IO.File]::ReadAllText('__SECRET_PATH__').Trim() $secure = ConvertTo-SecureString -String $encrypted $key = (New-Object System.Net.NetworkCredential('', $secure)).Password [Console]::Out.Write($key) '@ $helper = $helper.Replace('__SECRET_PATH__', $secretPath.Replace("'", "''")) if ($client -eq 'codex') { $configPath = Join-Path $userProfilePath '.codex\config.toml' $old = if (Test-Path -LiteralPath $configPath) { [System.IO.File]::ReadAllText($configPath) } else { '' } $retained = New-Object 'System.Collections.Generic.List[string]' $inTable = $false $skipProvider = $false foreach ($line in ($old -split "`r?`n")) { if ($line -match '^\s*\[\s*([^\]]+)\s*\]\s*(?:#.*)?$') { $inTable = $true $tableName = $Matches[1].Trim() $skipProvider = ($tableName -eq 'model_providers.simpleclaw' -or $tableName.StartsWith('model_providers.simpleclaw.')) } if ($skipProvider) { continue } if (-not $inTable -and $line -match '^\s*(model|model_provider|web_search)\s*=') { continue } $retained.Add($line) } $top = 'model = ' + (JsonString $model) + "`nmodel_provider = `"simpleclaw`"`nweb_search = `"disabled`"`n`n" $providerConfig = "`n[model_providers.simpleclaw]`nname = `"Simple Claw`"`nbase_url = `"$apiBase/v1`"`nwire_api = `"responses`"`nsupports_websockets = false`n`n" $providerConfig += '[model_providers.simpleclaw.auth]' + "`ncommand = " + (JsonString (Get-Process -Id $PID).Path) + "`n" $providerConfig += 'args = [' + ((@('-NoProfile', '-NonInteractive', '-File', $helperPath) | ForEach-Object { JsonString $_ }) -join ', ') + "]`n" $updated = $top + (($retained -join "`n").TrimEnd()) + "`n" + $providerConfig Save-Text $secretPath ($encryptedKey + "`n") Save-Text $helperPath $helper -PowerShellScript Save-Text $configPath $updated } elseif ($client -eq 'opencode') { $configRoot = if ($env:XDG_CONFIG_HOME) { $env:XDG_CONFIG_HOME } else { Join-Path $userProfilePath '.config' } $configDirectory = Join-Path $configRoot 'opencode' $configPath = Join-Path $configDirectory 'opencode.json' $jsoncPath = Join-Path $configDirectory 'opencode.jsonc' if ((Test-Path -LiteralPath $configPath) -and (Test-Path -LiteralPath $jsoncPath)) { Fail 'Найдены два global-конфига OpenCode; оставьте один JSON или JSONC перед установкой.' } if (Test-Path -LiteralPath $jsoncPath) { $configPath = $jsoncPath } $config = Read-OpenCodeConfig $configPath $providerKey = if ($config.PSObject.Properties['providers']) { 'providers' } else { 'provider' } $providers = Object-Property $config $providerKey $previous = Object-Property $providers 'simpleclaw' $modelSettings = Object-Property $previous 'models' foreach ($id in $models) { if (-not $modelSettings.PSObject.Properties[$id]) { Set-Property $modelSettings $id ([pscustomobject]@{ name = $id }) } } if ($secretPath.Contains('}')) { Fail 'Путь ключа не должен содержать закрывающую фигурную скобку.' } $options = [pscustomobject]@{ baseURL = "$apiBase/v1"; apiKey = ('{file:' + $secretPath.Replace('\', '/') + '}') } $simpleclaw = [pscustomobject]@{ name = 'Simple Claw'; models = $modelSettings } if ($providerKey -eq 'providers') { Set-Property $simpleclaw 'package' 'aisdk:@ai-sdk/openai-compatible' Set-Property $simpleclaw 'settings' $options $legacyProviders = Object-Property $config 'provider' $legacyProviders.PSObject.Properties.Remove('simpleclaw') } else { Set-Property $simpleclaw 'npm' '@ai-sdk/openai-compatible' Set-Property $simpleclaw 'options' $options } Set-Property $providers 'simpleclaw' $simpleclaw Set-Property $config $providerKey $providers if ($config.PSObject.Properties['permissions']) { $rules = $config.permissions if ($rules -isnot [array] -or @($rules | Where-Object { $_ -isnot [pscustomobject] }).Count -gt 0) { Fail 'permissions OpenCode 2 должен содержать массив правил.' } $rules = @($rules | Where-Object { -not ($_.action -eq 'skill' -and $_.resource -eq '*' -and $_.effect -eq 'deny') }) $rules += [pscustomobject]@{ action = 'skill'; resource = '*'; effect = 'deny' } Set-Property $config 'permissions' $rules } else { $permission = if ($config.PSObject.Properties['permission']) { $config.permission } else { [pscustomobject]@{} } if ($permission -is [string] -and $permission -in @('ask', 'allow', 'deny')) { $permission = [pscustomobject]@{ '*' = $permission } } if ($null -eq $permission -or $permission -isnot [pscustomobject]) { Fail 'permission OpenCode должен быть объектом или ask/allow/deny.' } Set-Property $permission 'skill' 'deny' Set-Property $config 'permission' $permission } Set-Property $config 'model' "simpleclaw/$model" $updated = ConvertTo-Json -InputObject $config -Depth 100 Protect-OpenCodeDirectory $secretDirectory Protect-OpenCodeKeyFiles $secretDirectory $keyText = (New-Object System.Net.NetworkCredential('', $secureKey)).Password Save-Text $secretPath $keyText $keyText = $null Protect-OpenCodeKeyFiles $secretDirectory Save-Text $configPath ($updated + "`n") } else { $configPath = Join-Path $userProfilePath '.claude\settings.json' $config = if (Test-Path -LiteralPath $configPath) { [System.IO.File]::ReadAllText($configPath) | ConvertFrom-Json } else { [pscustomobject]@{} } if ($null -eq $config -or $config -isnot [pscustomobject]) { Fail 'settings.json должен содержать JSON-объект.' } $envSettings = if ($config.PSObject.Properties['env']) { $config.env } else { [pscustomobject]@{} } if ($null -eq $envSettings -or $envSettings -isnot [pscustomobject]) { Fail 'settings.json.env должен быть JSON-объектом.' } $envSettings.PSObject.Properties.Remove('ANTHROPIC_API_KEY') $envSettings.PSObject.Properties.Remove('ANTHROPIC_AUTH_TOKEN') foreach ($entry in @{ ANTHROPIC_BASE_URL = $apiBase ANTHROPIC_MODEL = $model ANTHROPIC_CUSTOM_MODEL_OPTION = $model ANTHROPIC_CUSTOM_MODEL_OPTION_NAME = "Simple Claw · $model" ANTHROPIC_DEFAULT_OPUS_MODEL = $model ANTHROPIC_DEFAULT_SONNET_MODEL = $model ANTHROPIC_DEFAULT_HAIKU_MODEL = $model ANTHROPIC_DEFAULT_FABLE_MODEL = $model CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = '0' }.GetEnumerator()) { Set-Property $envSettings $entry.Key $entry.Value } Set-Property $config 'env' $envSettings Set-Property $config 'model' $model $powerShellPath = (Get-Process -Id $PID).Path Set-Property $config 'apiKeyHelper' ('"' + $powerShellPath + '" -NoProfile -NonInteractive -File "' + $helperPath + '"') $updated = ConvertTo-Json -InputObject $config -Depth 30 Save-Text $secretPath ($encryptedKey + "`n") Save-Text $helperPath $helper -PowerShellScript Save-Text $configPath ($updated + "`n") } Write-Host "Настроен: $configPath" Write-Host "Модель: $model" if ($client -eq 'opencode') { Write-Host 'Запустите opencode models, затем opencode.' Write-Host 'Конфигурация проекта может переопределять глобальные настройки. Сам OpenCode скрипт не устанавливает.' } elseif ($client -eq 'codex') { Write-Host 'Перезапустите Codex App/IDE или запустите codex и проверьте провайдера через /status.' } else { Write-Host 'Запустите claude и проверьте адрес gateway и модель через /status.' Write-Host 'Claude Desktop Chat настраивается отдельно в интерфейсе приложения.' } } try { Invoke-SimpleClawInstaller } finally { Remove-Item Function:\Invoke-SimpleClawInstaller -ErrorAction SilentlyContinue }