& { $ErrorActionPreference = "Stop" $CodexDir = Join-Path $env:USERPROFILE ".codex" $ConfigFile = Join-Path $CodexDir "config.toml" $EnvFile = Join-Path $CodexDir ".env" $ProviderName = "mrmaster" $DisplayName = "Mr Master" $BaseUrl = "https://api.mrmasterlk.shop/v1" $EnvName = "MRMASTER_API_KEY" $DefaultModel = "gpt-5.6-sol" Clear-Host Write-Host "" Write-Host "==================================================" -ForegroundColor Cyan Write-Host " Mr Master Codex Setup " -ForegroundColor Cyan Write-Host "==================================================" -ForegroundColor Cyan Write-Host "" Write-Host "Service : $DisplayName" -ForegroundColor White Write-Host "Endpoint : $BaseUrl" -ForegroundColor White Write-Host "Model : $DefaultModel" -ForegroundColor White Write-Host "" Write-Host "Safety Check:" -ForegroundColor Green Write-Host " * Chat histories & past sessions will NOT be deleted." -ForegroundColor Green Write-Host " * Existing settings will be backed up automatically." -ForegroundColor Green Write-Host "" # 1. Ensure .codex directory exists if (-not (Test-Path $CodexDir)) { New-Item -ItemType Directory -Path $CodexDir -Force | Out-Null } # 2. Check for existing API key $ExistingKey = $null if (Test-Path $EnvFile) { $EnvLines = Get-Content -Path $EnvFile -ErrorAction SilentlyContinue foreach ($Line in $EnvLines) { if ($Line -match ("^" + [regex]::Escape($EnvName) + "=(.*)$")) { $ExistingKey = $Matches[1].Trim() break } } } if ([string]::IsNullOrWhiteSpace($ExistingKey)) { $ExistingKey = [Environment]::GetEnvironmentVariable($EnvName, [EnvironmentVariableTarget]::User) } $ApiKey = $null if (-not [string]::IsNullOrWhiteSpace($ExistingKey)) { Write-Host "Existing API key found: $($ExistingKey.Substring(0, [Math]::Min(10, $ExistingKey.Length)))..." -ForegroundColor Yellow $replace = Read-Host "Use existing API key? (Y/n)" if ($replace -match "^[Nn]$") { $NeedNewKey = $true } else { $NeedNewKey = $false $ApiKey = $ExistingKey } } else { $NeedNewKey = $true } # 3. Prompt for API key if needed if ($NeedNewKey) { Write-Host "" Write-Host "Enter your Mr Master API Key (e.g. sk_live_...):" -ForegroundColor Cyan $InputKey = Read-Host "API Key" $ApiKey = $InputKey.Trim() if ([string]::IsNullOrWhiteSpace($ApiKey)) { Write-Host "" Write-Host "ERROR: API key cannot be empty. Setup aborted." -ForegroundColor Red exit 1 } } # 4. Optional API test Write-Host "" Write-Host "Testing connection to Mr Master API..." -ForegroundColor Cyan try { $TestHeaders = @{ Authorization = "Bearer $ApiKey" } $Response = Invoke-RestMethod -Uri "$BaseUrl/models" -Headers $TestHeaders -Method GET -TimeoutSec 15 Write-Host " -> Connection successful!" -ForegroundColor Green } catch { Write-Host " -> Notice: Could not verify endpoint immediately ($($_.Exception.Message))." -ForegroundColor Yellow $continue = Read-Host "Save settings and continue setup anyway? (Y/n)" if ($continue -match "^[Nn]$") { Write-Host "Setup cancelled." -ForegroundColor Yellow exit 0 } } # 5. Backups $Timestamp = Get-Date -Format "yyyyMMdd-HHmmss" if (Test-Path $ConfigFile) { $ConfigBackup = "$ConfigFile.backup-$Timestamp" Copy-Item -Path $ConfigFile -Destination $ConfigBackup -Force Write-Host " -> Backed up existing config.toml" -ForegroundColor DarkGray } if (Test-Path $EnvFile) { $EnvBackup = "$EnvFile.backup-$Timestamp" Copy-Item -Path $EnvFile -Destination $EnvBackup -Force Write-Host " -> Backed up existing .env" -ForegroundColor DarkGray } # 6. Write config.toml cleanly Write-Host "" Write-Host "Writing clean config.toml..." -ForegroundColor Cyan $Utf8NoBom = New-Object System.Text.UTF8Encoding($false) $ConfigLines = @( "model = ""$DefaultModel""" "model_provider = ""$ProviderName""" "model_reasoning_effort = ""low""" "" "[desktop]" "conversationDetailMode = ""STEPS_COMMANDS""" "" "[model_providers.$ProviderName]" "name = ""$DisplayName""" "base_url = ""$BaseUrl""" "wire_api = ""responses""" "requires_openai_auth = false" "env_key = ""$EnvName""" "supports_websockets = false" ) $ConfigContent = ($ConfigLines -join [Environment]::NewLine) + [Environment]::NewLine [System.IO.File]::WriteAllText($ConfigFile, $ConfigContent, $Utf8NoBom) Write-Host " -> config.toml written successfully." -ForegroundColor Green # 7. Update .env file Write-Host "Writing .codex.env file..." -ForegroundColor Cyan $NewEnvLines = @() $KeyWritten = $false if (Test-Path $EnvFile) { $ExistingLines = Get-Content -Path $EnvFile -ErrorAction SilentlyContinue foreach ($Line in $ExistingLines) { if ($Line -match ("^" + [regex]::Escape($EnvName) + "=")) { $NewEnvLines += "$EnvName=$ApiKey" $KeyWritten = $true } else { $NewEnvLines += $Line } } } if (-not $KeyWritten) { $NewEnvLines += "$EnvName=$ApiKey" } $EnvContent = ($NewEnvLines -join [Environment]::NewLine) + [Environment]::NewLine [System.IO.File]::WriteAllText($EnvFile, $EnvContent, $Utf8NoBom) Write-Host " -> .env file updated successfully." -ForegroundColor Green # 8. Set Windows User Environment Variable Write-Host "Updating Windows User Environment Variables..." -ForegroundColor Cyan [Environment]::SetEnvironmentVariable($EnvName, $ApiKey, [EnvironmentVariableTarget]::User) Set-Item -Path "Env:$EnvName" -Value $ApiKey Write-Host " -> Environment variable $EnvName set." -ForegroundColor Green # 9. Completion & Relaunch Write-Host "" Write-Host "==================================================" -ForegroundColor Green Write-Host " SETUP COMPLETED SUCCESSFULLY " -ForegroundColor Green Write-Host "==================================================" -ForegroundColor Green Write-Host "" Write-Host "Provider : $DisplayName ($ProviderName)" Write-Host "Base URL : $BaseUrl" Write-Host "Model : $DefaultModel" Write-Host "" $restart = Read-Host "Close running instances and restart VS Code / Codex now? (Y/n)" if ($restart -notmatch "^[Nn]$") { Write-Host "Closing active instances..." -ForegroundColor Yellow Get-Process Code, codex -ErrorAction SilentlyContinue | Stop-Process -Force Start-Sleep -Seconds 1 $CodeCmd = Get-Command code -ErrorAction SilentlyContinue if ($null -ne $CodeCmd) { Start-Process "code" Write-Host "Relaunched VS Code!" -ForegroundColor Green } } Write-Host "" Write-Host "All set! Mr Master Codex is ready." -ForegroundColor Cyan Write-Host "" }