param([switch]$ConfigureOnly) function Start-RubyCliSetup { $ErrorActionPreference = 'Stop' $RubyOrigin = 'https://app.rubycli.cloud' $RubyUtf8 = New-Object System.Text.UTF8Encoding $false $RubyTemporaryInstaller = $null $RubyKey = $null $RubyHomeDirectory = if ($env:USERPROFILE) { [IO.Path]::GetFullPath($env:USERPROFILE) } else { [Environment]::GetFolderPath('UserProfile') } function Stop-RubySetup([string]$Message) { $Failure = New-Object System.InvalidOperationException $Message $Failure.Data['RubyCLI'] = $true throw $Failure } function Write-RubyStep([int]$Number, [string]$Title) { Write-Host '' Write-Host (" {0}/4 {1}" -f $Number, $Title) -ForegroundColor Magenta } function Read-RubyObject([string]$Path) { if (-not (Test-Path -LiteralPath $Path)) { return [pscustomobject]@{} } try { $Object = [IO.File]::ReadAllText($Path) | ConvertFrom-Json } catch { Stop-RubySetup "Arquivo JSON invalido: $Path. Corrija-o antes de executar novamente." } if ($null -eq $Object -or $Object -isnot [pscustomobject]) { Stop-RubySetup "A configuracao precisa ser um objeto JSON: $Path." } return $Object } function Set-RubyProperty($Object, [string]$Name, $Value) { $Object | Add-Member -NotePropertyName $Name -NotePropertyValue $Value -Force } function Save-RubyObject([string]$Path, $Object, [string]$BackupSuffix) { $Directory = Split-Path -Parent $Path [IO.Directory]::CreateDirectory($Directory) | Out-Null if (Test-Path -LiteralPath $Path) { Copy-Item -LiteralPath $Path -Destination "$Path.$BackupSuffix" -ErrorAction Stop } $TemporaryPath = Join-Path $Directory ('.rubycli-' + [Guid]::NewGuid().ToString('N') + '.tmp') try { [IO.File]::WriteAllText($TemporaryPath, (($Object | ConvertTo-Json -Depth 100) + "`n"), $RubyUtf8) if (Test-Path -LiteralPath $Path) { [IO.File]::Replace($TemporaryPath, $Path, [NullString]::Value) } else { [IO.File]::Move($TemporaryPath, $Path) } } finally { if (Test-Path -LiteralPath $TemporaryPath) { Remove-Item -LiteralPath $TemporaryPath -Force } } } function Get-RubyCatalog([string]$Key) { try { $Result = Invoke-WebRequest -UseBasicParsing -Uri "$RubyOrigin/v1/models" -Headers @{ Authorization = "Bearer $Key"; Accept = 'application/json' } -MaximumRedirection 0 -TimeoutSec 30 } catch { $Status = 0 if ($null -ne $_.Exception.Response) { $Status = [int]$_.Exception.Response.StatusCode } switch ($Status) { 401 { Stop-RubySetup 'A chave nao foi aceita. Gere ou confira sua chave em https://app.rubycli.cloud/settings.' } 403 { Stop-RubySetup 'O acesso desta conta ou chave esta bloqueado. Consulte seu painel RubyCLI.' } 429 { Stop-RubySetup 'Muitas tentativas neste momento. Aguarde um pouco e execute novamente.' } default { Stop-RubySetup 'Nao foi possivel consultar a RubyCLI. Verifique sua conexao e tente novamente.' } } } try { $Content = if ($Result.Content -is [byte[]]) { $RubyUtf8.GetString($Result.Content) } else { [string]$Result.Content } $Catalog = $Content | ConvertFrom-Json if ($Catalog.data -isnot [System.Array]) { throw 'Invalid catalog' } $Items = @($Catalog.data | Where-Object { $_.id -is [string] -and $_.id -match '^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$' }) if ($Items.Count -ne $Catalog.data.Count) { throw 'Invalid model' } } catch { Stop-RubySetup 'A API retornou um catalogo inesperado. Tente novamente ou consulte o painel.' } if ($Items.Count -eq 0) { Stop-RubySetup 'A chave esta ativa, mas nao ha modelos liberados. Confira seu plano, saldo ou ofertas gratuitas no painel.' } return ,$Items } function Get-RubyClaudeCommand { $Command = Get-Command claude -ErrorAction SilentlyContinue | Select-Object -First 1 if ($Command) { return $Command } $NativePath = Join-Path $RubyHomeDirectory '.local\bin\claude.exe' if (Test-Path -LiteralPath $NativePath) { return Get-Command -Name $NativePath } return $null } function Add-RubyClaudePath { $NativeDirectory = Join-Path $RubyHomeDirectory '.local\bin' if (-not (Test-Path -LiteralPath (Join-Path $NativeDirectory 'claude.exe'))) { return } $CurrentUserPath = [Environment]::GetEnvironmentVariable('Path', 'User') $Entries = @($CurrentUserPath -split ';' | Where-Object { $_ }) if ($Entries -notcontains $NativeDirectory) { [Environment]::SetEnvironmentVariable('Path', (($Entries + $NativeDirectory) -join ';'), 'User') } if (($env:Path -split ';') -notcontains $NativeDirectory) { $env:Path = $NativeDirectory + ';' + $env:Path } } try { if ($PSVersionTable.PSVersion.Major -lt 5) { Stop-RubySetup 'Abra o PowerShell 5.1 ou uma versao mais recente.' } [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 Write-Host '' Write-Host ' RUBYCLI' -ForegroundColor Magenta Write-Host ' Seu ambiente de trabalho, conectado aos modelos Ruby.' -ForegroundColor White Write-Host ' Claude Code e integracao com o Claude Desktop.' -ForegroundColor DarkGray $RubyInteractive = -not [Console]::IsInputRedirected $RubyDesktopMode = if ($env:RUBY_DESKTOP) { $env:RUBY_DESKTOP } else { 'auto' } if ($RubyDesktopMode -notin @('auto', '0', '1')) { Stop-RubySetup 'Use RUBY_DESKTOP=auto, 0 ou 1.' } $RubyConfigurationOnly = $ConfigureOnly -or $env:RUBY_CONFIGURE_ONLY -eq '1' Write-RubyStep 1 'Verificar sua conexao' $RubyKey = $env:RUBY_API_KEY if ([string]::IsNullOrWhiteSpace($RubyKey)) { if (-not $RubyInteractive) { Stop-RubySetup 'Execute em um terminal interativo para informar sua chave, ou defina RUBY_API_KEY no ambiente.' } Write-Host ' Copie sua chave completa no painel. Ela ficara oculta ao colar.' -ForegroundColor DarkGray $SecureKey = Read-Host ' Chave RubyCLI' -AsSecureString $SecurePointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureKey) try { $RubyKey = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($SecurePointer) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($SecurePointer); $SecureKey.Dispose() } } $RubyKey = $RubyKey.Trim() if ($RubyKey -notmatch '^sk-ruby-[A-Za-z0-9_-]{20,200}$') { Stop-RubySetup 'Informe a chave RubyCLI completa, que comeca com sk-ruby-.' } $Models = Get-RubyCatalog $RubyKey Write-Host ' Conexao validada. Nenhuma chamada de IA foi feita.' -ForegroundColor Green Write-RubyStep 2 'Escolher seu modelo' $SelectedModel = $env:RUBY_MODEL if ($SelectedModel) { if ($SelectedModel -notin @($Models | ForEach-Object { $_.id })) { Stop-RubySetup 'RUBY_MODEL precisa ser um ID disponivel no catalogo desta chave.' } } else { $SelectedModel = $Models[0].id if ($RubyInteractive) { for ($Index = 0; $Index -lt $Models.Count; $Index++) { $Label = if ($Models[$Index].display_name) { $Models[$Index].display_name } elseif ($Models[$Index].name) { $Models[$Index].name } else { $Models[$Index].id } $Label = [regex]::Replace([string]$Label, '[\x00-\x1f\x7f]', ' ') Write-Host (" {0,3} {1} ({2})" -f ($Index + 1), $Label, $Models[$Index].id) } $Choice = Read-Host ' Numero do modelo [1]' if ($Choice) { $ChosenIndex = 0 if (-not [int]::TryParse($Choice, [ref]$ChosenIndex) -or $ChosenIndex -lt 1 -or $ChosenIndex -gt $Models.Count) { Stop-RubySetup 'Escolha um numero da lista de modelos.' } $SelectedModel = $Models[$ChosenIndex - 1].id } } } Write-Host (" Modelo: {0}" -f $SelectedModel) -ForegroundColor Green $ConfigurationDirectory = if ($env:CLAUDE_CONFIG_DIR) { [IO.Path]::GetFullPath($env:CLAUDE_CONFIG_DIR) } else { Join-Path $RubyHomeDirectory '.claude' } $SettingsPath = Join-Path $ConfigurationDirectory 'settings.json' $Settings = Read-RubyObject $SettingsPath if ($Settings.PSObject.Properties['env']) { if ($Settings.env -isnot [pscustomobject]) { Stop-RubySetup 'O campo env de settings.json precisa ser um objeto JSON.' } $SettingsEnvironment = $Settings.env } else { $SettingsEnvironment = [pscustomobject]@{} } $EnvironmentSettings = @{ ANTHROPIC_BASE_URL = "$RubyOrigin/anthropic" ANTHROPIC_AUTH_TOKEN = $RubyKey ANTHROPIC_API_KEY = '' ANTHROPIC_MODEL = $SelectedModel ANTHROPIC_DEFAULT_OPUS_MODEL = $SelectedModel ANTHROPIC_DEFAULT_SONNET_MODEL = $SelectedModel ANTHROPIC_DEFAULT_HAIKU_MODEL = $SelectedModel ANTHROPIC_DEFAULT_FABLE_MODEL = $SelectedModel CLAUDE_CODE_SUBAGENT_MODEL = $SelectedModel MAX_THINKING_TOKENS = '0' DISABLE_PROMPT_CACHING = '1' ENABLE_TOOL_SEARCH = 'false' CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1' CLAUDE_CODE_USE_BEDROCK = '0' CLAUDE_CODE_USE_VERTEX = '0' CLAUDE_CODE_USE_FOUNDRY = '0' } foreach ($Name in $EnvironmentSettings.Keys) { Set-RubyProperty $SettingsEnvironment $Name $EnvironmentSettings[$Name] } Set-RubyProperty $Settings 'env' $SettingsEnvironment Set-RubyProperty $Settings 'model' $SelectedModel if ($Settings.PSObject.Properties['permissions']) { if ($Settings.permissions -isnot [pscustomobject]) { Stop-RubySetup 'O campo permissions de settings.json precisa ser um objeto JSON.' } $SettingsPermissions = $Settings.permissions } else { $SettingsPermissions = [pscustomobject]@{} } Set-RubyProperty $SettingsPermissions 'defaultMode' 'default' Set-RubyProperty $Settings 'permissions' $SettingsPermissions $DesktopWrites = @() $DesktopResult = 'Claude Desktop nao encontrado. Se instalar depois, execute a configuracao novamente.' $DesktopProfile = if ($env:APPDATA) { Join-Path $env:APPDATA 'Claude' } else { $null } $DesktopGatewayProfile = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA 'Claude-3p' } else { $null } $DesktopFound = $DesktopGatewayProfile -and ((Test-Path -LiteralPath $DesktopGatewayProfile) -or ($DesktopProfile -and (Test-Path -LiteralPath $DesktopProfile))) if ($RubyDesktopMode -eq '0') { $DesktopResult = 'Claude Desktop: configuracao desativada por RUBY_DESKTOP=0.' } elseif ($DesktopFound) { $PersonalLogin = $false if ($DesktopProfile -and $RubyDesktopMode -ne '1') { $PersonalConfig = Read-RubyObject (Join-Path $DesktopProfile 'config.json') foreach ($LoginField in @('oauth:tokenCacheV2', 'oauth:tokenCache', 'lastKnownAccountUuid')) { if ($PersonalConfig.PSObject.Properties[$LoginField] -and $PersonalConfig.$LoginField) { $PersonalLogin = $true } } } if ($PersonalLogin -and $RubyDesktopMode -ne '1') { $DesktopResult = 'Sua conexao pessoal do Claude Desktop foi mantida. Para trocar para RubyCLI, execute novamente com RUBY_DESKTOP=1.' } else { $DesktopEntryId = '41f1b57b-4e79-4b2a-9216-ced6ee9ea1c0' $DesktopLibrary = Join-Path $DesktopGatewayProfile 'configLibrary' $DesktopEntryPath = Join-Path $DesktopLibrary "$DesktopEntryId.json" $DesktopMetaPath = Join-Path $DesktopLibrary '_meta.json' $DesktopConfigPath = Join-Path $DesktopGatewayProfile 'claude_desktop_config.json' $DesktopEntry = Read-RubyObject $DesktopEntryPath $DesktopMeta = Read-RubyObject $DesktopMetaPath $DesktopConfig = Read-RubyObject $DesktopConfigPath foreach ($Pair in @{ inferenceProvider = 'gateway'; inferenceCredentialKind = 'static'; inferenceGatewayBaseUrl = "$RubyOrigin/anthropic" inferenceGatewayApiKey = $RubyKey; inferenceGatewayAuthScheme = 'bearer' }.GetEnumerator()) { Set-RubyProperty $DesktopEntry $Pair.Key $Pair.Value } if ($DesktopEntry.PSObject.Properties['coworkEgressAllowedHosts'] -and $DesktopEntry.coworkEgressAllowedHosts -isnot [System.Array]) { Stop-RubySetup 'coworkEgressAllowedHosts precisa ser uma lista no Claude Desktop.' } $Entries = @() if ($DesktopMeta.PSObject.Properties['entries']) { if ($DesktopMeta.entries -isnot [System.Array]) { Stop-RubySetup 'entries precisa ser uma lista na biblioteca do Claude Desktop.' } $Entries = @($DesktopMeta.entries) } $RubyEntryExists = $false foreach ($Entry in $Entries) { if ($Entry -isnot [pscustomobject]) { Stop-RubySetup 'A biblioteca do Claude Desktop contem uma entrada invalida.' } if ($Entry.id -eq $DesktopEntryId) { Set-RubyProperty $Entry 'name' 'RubyCLI'; $RubyEntryExists = $true } } if (-not $RubyEntryExists) { $Entries += [pscustomobject]@{ id = $DesktopEntryId; name = 'RubyCLI' } } Set-RubyProperty $DesktopMeta 'entries' ([object[]]$Entries) Set-RubyProperty $DesktopMeta 'appliedId' $DesktopEntryId Set-RubyProperty $DesktopConfig 'deploymentMode' '3p' $DesktopWrites = @( @{ Path = $DesktopEntryPath; Value = $DesktopEntry }, @{ Path = $DesktopMetaPath; Value = $DesktopMeta }, @{ Path = $DesktopConfigPath; Value = $DesktopConfig } ) $DesktopResult = 'Claude Desktop conectado a RubyCLI. Feche e abra o aplicativo para aplicar.' } } Write-RubyStep 3 'Preparar o Claude Code' if ($RubyConfigurationOnly) { Write-Host ' Modo de configuracao: a instalacao foi mantida.' -ForegroundColor DarkGray } else { $ClaudeCommand = Get-RubyClaudeCommand $WorkingVersion = $null if ($ClaudeCommand) { try { $WorkingVersion = (& $ClaudeCommand --version 2>$null | Select-Object -First 1) } catch { $WorkingVersion = $null } if ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0) { $WorkingVersion = $null } } if (-not $WorkingVersion) { Write-Host ' Instalando a versao stable pelo instalador oficial da Anthropic.' -ForegroundColor DarkGray $RubyTemporaryInstaller = Join-Path ([IO.Path]::GetTempPath()) ('rubycli-claude-' + [Guid]::NewGuid().ToString('N') + '.ps1') try { Invoke-WebRequest -UseBasicParsing -Uri 'https://claude.ai/install.ps1' -OutFile $RubyTemporaryInstaller -TimeoutSec 120 -MaximumRedirection 5 $OfficialSource = [IO.File]::ReadAllText($RubyTemporaryInstaller) & ([scriptblock]::Create($OfficialSource)) stable Add-RubyClaudePath $ClaudeCommand = Get-RubyClaudeCommand if (-not $ClaudeCommand) { throw 'Claude command unavailable' } $WorkingVersion = & $ClaudeCommand --version 2>$null | Select-Object -First 1 if (-not $WorkingVersion -or ($null -ne $LASTEXITCODE -and $LASTEXITCODE -ne 0)) { throw 'Claude verification failed' } } catch { Stop-RubySetup 'A instalacao do Claude Code nao foi concluida. Consulte https://app.rubycli.cloud/docs#claude-code e execute novamente.' } } Add-RubyClaudePath Write-Host ' Claude Code disponivel.' -ForegroundColor Green } Write-RubyStep 4 'Salvar sua configuracao' $BackupSuffix = 'rubycli.backup-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssfffZ') + '-' + [Guid]::NewGuid().ToString('N').Substring(0, 6) Save-RubyObject $SettingsPath $Settings $BackupSuffix foreach ($Write in $DesktopWrites) { Save-RubyObject $Write.Path $Write.Value $BackupSuffix } Write-Host ' Configuracao salva. Arquivos anteriores recebem uma copia de seguranca.' -ForegroundColor Green Write-Host (" {0}" -f $DesktopResult) -ForegroundColor DarkGray Write-Host '' Write-Host ' PRONTO PARA SUA PROXIMA IDEIA' -ForegroundColor Magenta Write-Host ' Abra a pasta do seu projeto e execute: claude' -ForegroundColor White Write-Host ' Saldo e consumo: https://app.rubycli.cloud/dashboard' -ForegroundColor DarkGray Write-Host '' } catch { $Message = if ($_.Exception.Data['RubyCLI']) { $_.Exception.Message } else { 'Nao foi possivel concluir a configuracao. Seus backups existentes foram mantidos. Consulte https://app.rubycli.cloud/docs#claude-code.' } Write-Host '' Write-Host (" RubyCLI: {0}" -f $Message) -ForegroundColor Red throw (New-Object System.InvalidOperationException $Message) } finally { $RubyKey = $null if ($RubyTemporaryInstaller -and (Test-Path -LiteralPath $RubyTemporaryInstaller)) { Remove-Item -LiteralPath $RubyTemporaryInstaller -Force } } } Start-RubyCliSetup