& { $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $baseUrl = 'https://tokify.sale' $registryPath = 'HKCU:\SOFTWARE\Policies\Claude' $machineRegistryPath = 'HKLM:\SOFTWARE\Policies\Claude' $installerVersion = '1.0.0' $apiKey = $null $secureApiKey = $null $settings = $null $snapshot = @{} $changedNames = [System.Collections.Generic.List[string]]::new() $registryKeyExisted = $false $configurationCommitted = $false function Write-Step { param([int]$Number, [string]$Message) Write-Host "[$Number/6] $Message" -ForegroundColor Cyan } function Get-ClaudeLaunchTarget { $target = [ordered]@{ Executable = $null; AppId = $null } $runningProcesses = @(Get-Process -Name 'Claude' -ErrorAction SilentlyContinue) foreach ($process in $runningProcesses) { try { if ($process.Path -and (Test-Path -LiteralPath $process.Path)) { $target.Executable = $process.Path return $target } } catch { } } $candidatePaths = @( (Join-Path $env:LOCALAPPDATA 'AnthropicClaude\Claude.exe'), (Join-Path $env:LOCALAPPDATA 'Claude\Claude.exe'), (Join-Path $env:LOCALAPPDATA 'Programs\Claude\Claude.exe'), (Join-Path $env:ProgramFiles 'Claude\Claude.exe') ) if (${env:ProgramFiles(x86)}) { $candidatePaths += (Join-Path ${env:ProgramFiles(x86)} 'Claude\Claude.exe') } foreach ($candidatePath in $candidatePaths) { if (Test-Path -LiteralPath $candidatePath) { $target.Executable = $candidatePath return $target } } $startApp = Get-StartApps -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq 'Claude' -or $_.Name -like 'Claude *' } | Select-Object -First 1 if ($startApp) { $target.AppId = $startApp.AppID return $target } $package = Get-AppxPackage -Name 'Claude' -ErrorAction SilentlyContinue | Select-Object -First 1 if ($package) { $manifest = Get-AppxPackageManifest -Package $package $applicationId = @($manifest.Package.Applications.Application)[0].Id if ($applicationId) { $target.AppId = "$($package.PackageFamilyName)!$applicationId" } } return $target } function Restore-ClaudeConfiguration { param( [string]$Path, [hashtable]$SavedValues, [System.Collections.Generic.List[string]]$Names, [bool]$KeyExisted ) foreach ($name in $Names) { $saved = $SavedValues[$name] if ($saved.Exists) { New-ItemProperty -Path $Path -Name $name -Value $saved.Value ` -PropertyType $saved.Kind -Force -ErrorAction SilentlyContinue | Out-Null } else { Remove-ItemProperty -Path $Path -Name $name -ErrorAction SilentlyContinue } } if (-not $KeyExisted -and (Test-Path -LiteralPath $Path)) { $remaining = @(Get-Item -LiteralPath $Path).GetValueNames() if ($remaining.Count -eq 0) { Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue } } } try { Clear-Host Write-Host '' Write-Host '========================================' -ForegroundColor DarkYellow Write-Host ' CLAUDINHOFY ' -ForegroundColor DarkYellow Write-Host ' CONFIGURACAO AUTOMATICA ' -ForegroundColor White Write-Host '========================================' -ForegroundColor DarkYellow Write-Host " v$installerVersion" -ForegroundColor DarkGray Write-Host '' Write-Host 'Aviso: este instalador altera politicas por usuario do Claude Desktop.' -ForegroundColor Yellow Write-Host 'A API Key sera armazenada no Registro do Windows sem criptografia propria.' -ForegroundColor Yellow Write-Host 'Ela sera enviada somente para https://tokify.sale para validacao e uso.' -ForegroundColor Yellow Write-Host '' $secureApiKey = Read-Host 'Digite sua API Key' -AsSecureString $apiKey = ([System.Net.NetworkCredential]::new('', $secureApiKey).Password).Trim() if ([string]::IsNullOrWhiteSpace($apiKey)) { throw 'Nenhuma chave informada.' } Write-Step 1 'Validando API Key...' $info = Invoke-RestMethod -Uri "$baseUrl/public/key-info" -Method Post ` -ContentType 'application/json' -Body (@{ key = $apiKey } | ConvertTo-Json -Compress) ` -TimeoutSec 30 -MaximumRedirection 0 if ($info.active -ne $true) { throw 'API Key invalida ou inativa.' } Write-Host 'API Key validada!' -ForegroundColor Green if ($info.quota -and $info.quota.unlimited -eq $true) { Write-Host 'Plano: Ilimitado' -ForegroundColor Green } elseif ($info.quota -and $null -ne $info.quota.remaining) { Write-Host "Saldo: $($info.quota.remaining) tokens" -ForegroundColor Green } Write-Step 2 'Testando o gateway...' $models = Invoke-RestMethod -Uri "$baseUrl/v1/models" -Method Get ` -Headers @{ Authorization = "Bearer $apiKey" } -TimeoutSec 30 -MaximumRedirection 0 $claudeModels = @($models.data | Where-Object { $_.id -match '^claude' }) if ($claudeModels.Count -eq 0) { throw 'O gateway respondeu, mas nenhum modelo Claude foi encontrado.' } Write-Host "Gateway autenticado; $($claudeModels.Count) modelo(s) Claude encontrado(s)." -ForegroundColor Green Write-Step 3 'Localizando Claude Desktop e verificando conflitos...' $launchTarget = Get-ClaudeLaunchTarget if (-not $launchTarget.Executable -and -not $launchTarget.AppId) { throw 'Claude Desktop nao foi encontrado. Instale-o antes de executar este instalador.' } if (Test-Path -LiteralPath $machineRegistryPath) { $machineValues = @((Get-Item -LiteralPath $machineRegistryPath).GetValueNames()) if ($machineValues.Count -gt 0) { throw 'Existe uma politica de maquina para o Claude. Ela tem prioridade sobre a configuracao por usuario; nenhuma alteracao foi realizada.' } } $settings = [ordered]@{ inferenceProvider = 'gateway' inferenceCredentialKind = 'static' inferenceGatewayBaseUrl = $baseUrl inferenceGatewayApiKey = $apiKey inferenceGatewayAuthScheme = 'bearer' deploymentDisplayName = 'Claudinhofy' modelDiscoveryEnabled = 'true' endUserAttribution = 'false' } $registryKeyExisted = Test-Path -LiteralPath $registryPath if ($registryKeyExisted) { $existingKey = Get-Item -LiteralPath $registryPath $existingNames = @($existingKey.GetValueNames()) $ownedByClaudinhofy = ( $existingKey.GetValue('inferenceGatewayBaseUrl') -eq $baseUrl -and $existingKey.GetValue('deploymentDisplayName') -eq 'Claudinhofy' ) $overlap = @($settings.Keys | Where-Object { $existingNames -contains $_ }) if ($overlap.Count -gt 0 -and -not $ownedByClaudinhofy) { throw 'Foi encontrada outra configuracao gerenciada de inferencia. Nenhuma configuracao de terceiros foi sobrescrita.' } } Write-Host 'Claude Desktop localizado e nenhuma configuracao conflitante foi encontrada.' -ForegroundColor Green Write-Host '' Write-Host 'Salve seus trabalhos. O Claude sera fechado e reaberto.' -ForegroundColor Yellow $confirmation = Read-Host 'Confirmar a gravacao da API Key e reiniciar o Claude? (S/N)' if ($confirmation -notmatch '^[Ss]$') { Write-Host 'Instalacao cancelada. Nenhuma alteracao foi realizada.' -ForegroundColor Yellow return } Write-Step 4 'Configurando Claudinhofy...' New-Item -Path $registryPath -Force | Out-Null $registryKey = Get-Item -LiteralPath $registryPath foreach ($name in $settings.Keys) { if ($registryKey.GetValueNames() -contains $name) { $snapshot[$name] = @{ Exists = $true Value = $registryKey.GetValue($name, $null, 'DoNotExpandEnvironmentNames') Kind = $registryKey.GetValueKind($name) } } else { $snapshot[$name] = @{ Exists = $false } } } foreach ($name in $settings.Keys) { New-ItemProperty -Path $registryPath -Name $name -Value $settings[$name] ` -PropertyType String -Force | Out-Null $changedNames.Add($name) } $writtenKey = Get-Item -LiteralPath $registryPath foreach ($name in $settings.Keys) { if ($writtenKey.GetValue($name) -ne $settings[$name]) { throw "Falha ao verificar a configuracao '$name' no Registro." } } Write-Host 'Configuracao gravada e verificada no Registro.' -ForegroundColor Green Write-Step 5 'Reiniciando Claude Desktop...' Get-Process -Name 'Claude' -ErrorAction SilentlyContinue | Stop-Process -Force Start-Sleep -Seconds 3 if ($launchTarget.Executable) { Start-Process -FilePath $launchTarget.Executable } else { Start-Process -FilePath 'explorer.exe' -ArgumentList "shell:AppsFolder\$($launchTarget.AppId)" } Start-Sleep -Seconds 8 Write-Step 6 'Verificando a inicializacao...' if (-not (Get-Process -Name 'Claude' -ErrorAction SilentlyContinue)) { throw 'A configuracao foi gravada, mas nao foi possivel confirmar a abertura do Claude. As alteracoes serao restauradas.' } $configurationCommitted = $true Write-Host '' Write-Host '========================================' -ForegroundColor Green Write-Host ' CONFIGURACAO CONCLUIDA! ' -ForegroundColor Green Write-Host '========================================' -ForegroundColor Green Write-Host '' Write-Host 'O gateway foi autenticado, a politica foi gravada e o Claude foi iniciado.' -ForegroundColor White Write-Host 'Envie uma mensagem no Claude para confirmar o fluxo completo de inferencia.' -ForegroundColor White Write-Host 'A abertura do aplicativo, isoladamente, nao comprova uma resposta do modelo.' -ForegroundColor DarkGray } catch { if (-not $configurationCommitted -and $changedNames.Count -gt 0) { Restore-ClaudeConfiguration -Path $registryPath -SavedValues $snapshot ` -Names $changedNames -KeyExisted $registryKeyExisted } Write-Host '' Write-Host 'Falha na configuracao.' -ForegroundColor Red $message = $_.Exception.Message if ($apiKey) { $message = $message.Replace($apiKey, '[OCULTO]') } $exceptionTypeName = $_.Exception.GetType().FullName if ($_.Exception -is [System.Net.WebException] -or $exceptionTypeName -eq 'System.Net.Http.HttpRequestException') { Write-Host 'Falha de conexao ou autenticacao com o gateway.' -ForegroundColor Red } else { Write-Host $message -ForegroundColor Red } if ($changedNames.Count -gt 0 -and -not $configurationCommitted) { Write-Host 'As configuracoes anteriores foram restauradas.' -ForegroundColor Yellow } $global:LASTEXITCODE = 1 } finally { $snapshot.Clear() Remove-Variable apiKey, secureApiKey, settings -ErrorAction SilentlyContinue [System.GC]::Collect() } }