diff --git a/docs/claude-code-local-proxy.md b/docs/claude-code-local-proxy.md index 757dc162..59f0286a 100644 --- a/docs/claude-code-local-proxy.md +++ b/docs/claude-code-local-proxy.md @@ -2,12 +2,17 @@ This documents how to route Claude Code through CLIProxyAPI, and the related server changes made to improve model aliasing and auth error reporting. -## What we configured (Windows) +## What we configured (Windows/macOS) 1. Run CLIProxyAPI locally (default in this repo uses `127.0.0.1:8318`). 2. Point Claude Code at the local proxy by setting Anthropic environment variables in your Claude Code user settings. -Claude Code reads settings from `C:\Users\\.claude\settings.json` (Windows). Example: +Claude Code reads settings from: + +- Windows: `C:\Users\\.claude\settings.json` +- macOS/Linux: `~/.claude/settings.json` + +Example: ```json { @@ -55,6 +60,15 @@ $hdr=@{ 'User-Agent'='claude-cli'; 'Authorization'='Bearer local-dev-key' } Invoke-RestMethod -Headers $hdr -Uri 'http://127.0.0.1:8318/v1/models' -Method Get ``` +Or with `curl` (macOS/Linux): + +```bash +curl -s \ + -H 'User-Agent: claude-cli' \ + -H 'Authorization: Bearer local-dev-key' \ + 'http://127.0.0.1:8318/v1/models' +``` + Send a minimal Claude Messages request through the proxy: ```powershell @@ -63,3 +77,13 @@ $body=@{ model='opus'; max_tokens=16; stream=$false; messages=@(@{ role='user'; Invoke-RestMethod -Headers $hdr -Uri 'http://127.0.0.1:8318/v1/messages' -Method Post -Body $body ``` +Or with `curl` (macOS/Linux): + +```bash +curl -s \ + -H 'User-Agent: claude-cli' \ + -H 'Authorization: Bearer local-dev-key' \ + -H 'Content-Type: application/json' \ + -d '{"model":"opus","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"hi"}]}' \ + 'http://127.0.0.1:8318/v1/messages' +``` diff --git a/scripts/README.md b/scripts/README.md index 7c28c606..079884fd 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -1,54 +1,13 @@ -# Droid CLI + CLIProxyAPI (Windows) +# Scripts -This repo can run a local OpenAI-compatible proxy (`CLIProxyAPI`) and configure Factory's `droid` CLI to use it via BYOK custom models. +OS-specific helpers live under: -## One-time setup +- Windows: `scripts/windows/README.md` +- macOS: `scripts/macos/README.md` -1. From the repo root, run: - - `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\setup-droid-cliproxy.ps1 -ProxyApiKey ""` +Convenience wrappers (macOS/Linux): -This will: -- Build `bin\cliproxyapi.exe` -- Write `C:\Users\\.factory\config.json` with a `custom_models` entry pointing at `http://127.0.0.1:8317/v1` - -## Start / stop the proxy - -- Build (recommended after pulling updates): `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\build-cliproxyapi.ps1` -- Start: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\start-cliproxy.ps1` -- Stop: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\stop-cliproxy.ps1` -- Restart: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\restart-cliproxy.ps1` - -Logs: -- `logs\cliproxyapi.out.log` -- `logs\cliproxyapi.err.log` - -## Auto-start at logon (Windows) - -Recommended: install a per-user startup entry (no admin required): - -- Install: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\install-cliproxyapi-startup-run.ps1` -- Uninstall: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\uninstall-cliproxyapi-startup-run.ps1` - -Optional: install a scheduled task (may require admin depending on your system policy): - -- Install: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\install-cliproxyapi-startup-task.ps1` -- Uninstall: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\uninstall-cliproxyapi-startup-task.ps1` - -This uses `scripts\run-cliproxyapi-hidden.vbs` to start the server hidden and write logs to `logs\`. - -### One-time cleanup (if stop says "Access is denied") - -That means CLIProxyAPI was started **elevated** (commonly via a scheduled task with `RunLevel=HighestAvailable`), and a normal restart can't kill it. - -Run once in an **elevated PowerShell**: - -- `taskkill /IM cliproxyapi.exe /F` -- `schtasks /Delete /TN "CLIProxyAPI-Logon" /F` (if it exists) - -## Use it in Droid - -- In `droid`, run `/model` and pick `CLIProxy (local)` -- In non-interactive mode, use: `droid exec --model custom:gpt-5.1 "..."` (replace model as needed) -- `scripts\setup-droid-cliproxy.ps1` adds several `custom:` entries (e.g. `custom:gpt-5.2`, `custom:gpt-5.1-codex`, `custom:gemini-3-pro-preview`) -- For reasoning variants, pick a model like `CLIProxy (local): gpt-5.2 (reasoning: high)` (this uses `gpt-5.2(high)` under the hood). -- `gpt-5.1-codex-max` also has reasoning variants (including `xhigh`) like `custom:gpt-5.1-codex-max(xhigh)`. +- Build: `./scripts/build.sh` +- Start: `./scripts/start.sh` +- Stop: `./scripts/stop.sh` +- Restart: `./scripts/restart.sh` diff --git a/scripts/build-cliproxyapi.ps1 b/scripts/build-cliproxyapi.ps1 index 0bd75249..88c7d2b8 100644 --- a/scripts/build-cliproxyapi.ps1 +++ b/scripts/build-cliproxyapi.ps1 @@ -1,27 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -function Get-RepoRoot { - return (Resolve-Path (Join-Path $PSScriptRoot "..")).Path -} - -$repoRoot = Get-RepoRoot -$outDir = Join-Path $repoRoot "bin" -$outPath = Join-Path $outDir "cliproxyapi-latest.exe" - -if (-not (Test-Path -LiteralPath $outDir)) { - New-Item -ItemType Directory -Path $outDir | Out-Null -} - -Write-Host "Building CLIProxyAPI..." -Write-Host " out: $outPath" - -Push-Location $repoRoot -try { - go build -o $outPath .\cmd\server -} finally { - Pop-Location -} - -Write-Host "Done." +& (Join-Path $PSScriptRoot "windows\\build-cliproxyapi.ps1") @args diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 00000000..10f01097 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$script_dir/macos/build-cliproxyapi.sh" "$@" + diff --git a/scripts/fix-droid-spec-model.ps1 b/scripts/fix-droid-spec-model.ps1 index acd73a33..e828b5bc 100644 --- a/scripts/fix-droid-spec-model.ps1 +++ b/scripts/fix-droid-spec-model.ps1 @@ -1,79 +1,5 @@ -param( - [Parameter(Mandatory = $false)] - [string]$Model = "custom:gpt-5.2(high)" -) - Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -function Ensure-CustomModelExists([string]$ModelId) { - if (-not $ModelId.StartsWith("custom:")) { - throw "Model must start with 'custom:'. Got: $ModelId" - } - $inner = $ModelId.Substring("custom:".Length) +& (Join-Path $PSScriptRoot "windows\\fix-droid-spec-model.ps1") @args - $configPath = Join-Path $env:USERPROFILE ".factory\\config.json" - if (-not (Test-Path -LiteralPath $configPath)) { - throw "Droid BYOK config not found: $configPath" - } - $cfg = Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json - $models = @($cfg.custom_models | ForEach-Object { [string]$_.model }) - if (-not ($models -contains $inner)) { - throw "Custom model '$ModelId' not found in $configPath. Available: $($models -join ', ')" - } -} - -function Update-JsonFile([string]$Path, [scriptblock]$Mutator) { - $obj = Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json - & $Mutator $obj | Out-Null - $json = $obj | ConvertTo-Json -Depth 50 - $utf8NoBom = New-Object System.Text.UTF8Encoding($false) - [System.IO.File]::WriteAllText($Path, $json, $utf8NoBom) -} - -function Update-JsoncModelLine([string]$Path, [string]$ModelId) { - $text = Get-Content -Raw -LiteralPath $Path - if ($text -notmatch '"model"\s*:\s*"[^"]*"') { - throw "Couldn't find a JSON 'model' field in: $Path" - } - $updated = [regex]::Replace($text, '"model"\s*:\s*"[^"]*"', ('"model": "' + $ModelId + '"'), 1) - $utf8NoBom = New-Object System.Text.UTF8Encoding($false) - [System.IO.File]::WriteAllText($Path, $updated, $utf8NoBom) -} - -Ensure-CustomModelExists -ModelId $Model - -# Update global settings.json (JSONC with comments) -$globalSettingsPath = Join-Path $env:USERPROFILE ".factory\\settings.json" -if (Test-Path -LiteralPath $globalSettingsPath) { - Update-JsoncModelLine -Path $globalSettingsPath -ModelId $Model - Write-Host "Updated global model -> $globalSettingsPath" -} else { - Write-Host "Skipped (not found): $globalSettingsPath" -} - -# Update the latest session settings for this folder (pure JSON) -$sessionDir = Join-Path $env:USERPROFILE ".factory\\sessions\\-D-code-CLIProxyAPI" -if (Test-Path -LiteralPath $sessionDir) { - $latest = Get-ChildItem -LiteralPath $sessionDir -Filter "*.settings.json" -File | - Sort-Object LastWriteTime -Descending | - Select-Object -First 1 - if ($latest) { - Update-JsonFile -Path $latest.FullName -Mutator { - param($o) - $o.model = $Model - if ($o.PSObject.Properties.Name -contains "providerLock") { $o.PSObject.Properties.Remove("providerLock") } - if ($o.PSObject.Properties.Name -contains "providerLockTimestamp") { $o.PSObject.Properties.Remove("providerLockTimestamp") } - if ($o.PSObject.Properties.Name -contains "apiProviderLock") { $o.PSObject.Properties.Remove("apiProviderLock") } - if ($o.PSObject.Properties.Name -contains "apiProviderLockTimestamp") { $o.PSObject.Properties.Remove("apiProviderLockTimestamp") } - } - Write-Host "Updated session model -> $($latest.FullName)" - } else { - Write-Host "No session settings found in: $sessionDir" - } -} else { - Write-Host "Skipped (not found): $sessionDir" -} - -Write-Host "" -Write-Host "Restart droid, then try Spec mode again." diff --git a/scripts/install-autostart.sh b/scripts/install-autostart.sh new file mode 100644 index 00000000..4a03cc6d --- /dev/null +++ b/scripts/install-autostart.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$script_dir/macos/install-cliproxyapi-launchagent.sh" "$@" + diff --git a/scripts/install-cliproxyapi-startup-run.ps1 b/scripts/install-cliproxyapi-startup-run.ps1 index b7ed9d0a..40a1c2f6 100644 --- a/scripts/install-cliproxyapi-startup-run.ps1 +++ b/scripts/install-cliproxyapi-startup-run.ps1 @@ -1,22 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -$valueName = "CLIProxyAPI" -$scriptDir = $PSScriptRoot -$ps1Path = Join-Path $scriptDir "start-cliproxy.ps1" - -if (-not (Test-Path -LiteralPath $ps1Path)) { - throw "Missing starter script: $ps1Path" -} - -# Use a hidden PowerShell process at logon. -$command = "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ps1Path`"" - -Write-Host "Installing HKCU Run entry '$valueName'..." -Write-Host " Command: $command" - -New-Item -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Force | Out-Null -Set-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Name $valueName -Value $command - -Write-Host "Done." +& (Join-Path $PSScriptRoot "windows\\install-cliproxyapi-startup-run.ps1") @args diff --git a/scripts/install-cliproxyapi-startup-task.ps1 b/scripts/install-cliproxyapi-startup-task.ps1 index ab49f14d..7241ad3c 100644 --- a/scripts/install-cliproxyapi-startup-task.ps1 +++ b/scripts/install-cliproxyapi-startup-task.ps1 @@ -1,40 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -$taskName = "CLIProxyAPI" -$scriptDir = $PSScriptRoot -$vbsPath = Join-Path $scriptDir "run-cliproxyapi-hidden.vbs" +& (Join-Path $PSScriptRoot "windows\\install-cliproxyapi-startup-task.ps1") @args -if (-not (Test-Path -LiteralPath $vbsPath)) { - throw "Missing launcher: $vbsPath" -} - -Write-Host "Creating scheduled task '$taskName' (At log on)..." -Write-Host " Launcher: $vbsPath" - -try { - $action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$vbsPath`"" - $trigger = New-ScheduledTaskTrigger -AtLogOn - $userId = if ($env:USERDOMAIN) { "$($env:USERDOMAIN)\\$($env:USERNAME)" } else { $env:USERNAME } - $principal = New-ScheduledTaskPrincipal -UserId $userId -LogonType Interactive -RunLevel Limited - $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable - - Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null - Write-Host "Done." - Write-Host "Verify:" - Write-Host " Get-ScheduledTask -TaskName $taskName | Format-List *" - exit 0 -} catch { - Write-Warning "Register-ScheduledTask failed: $($_.Exception.Message)" - Write-Host "Falling back to schtasks.exe..." -} - -$taskAction = "wscript.exe `"$vbsPath`"" -& schtasks.exe /Create /TN $taskName /SC ONLOGON /F /RL LIMITED /TR $taskAction | Out-Null -if ($LASTEXITCODE -ne 0) { - throw "schtasks.exe failed with exit code $LASTEXITCODE. Try running this script in an elevated PowerShell." -} - -Write-Host "Done." -Write-Host "Verify:" -Write-Host " schtasks /Query /TN $taskName /V /FO LIST" diff --git a/scripts/macos/README.md b/scripts/macos/README.md new file mode 100644 index 00000000..a6d3bb7d --- /dev/null +++ b/scripts/macos/README.md @@ -0,0 +1,30 @@ +# CLIProxyAPI (macOS) + +This folder contains macOS helpers for building, running, and auto-starting CLIProxyAPI. + +## One-time setup + +From the repo root: + +- Build: `./scripts/build.sh` + +This builds `bin/cliproxyapi-latest`. + +## Start / stop the proxy + +- Start: `./scripts/start.sh` +- Stop: `./scripts/stop.sh` +- Restart: `./scripts/restart.sh` + +Logs: +- `logs/cliproxyapi.out.log` +- `logs/cliproxyapi.err.log` + +## Auto-start at login (launchd) + +Install a per-user LaunchAgent (no admin required): + +- Install: `./scripts/install-autostart.sh` +- Uninstall: `./scripts/uninstall-autostart.sh` + +The LaunchAgent plist is written to `~/Library/LaunchAgents/com.cliproxyapi.plist`. diff --git a/scripts/macos/build-cliproxyapi.sh b/scripts/macos/build-cliproxyapi.sh new file mode 100644 index 00000000..e137aaa8 --- /dev/null +++ b/scripts/macos/build-cliproxyapi.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +out_dir="$repo_root/bin" +out_path="$out_dir/cliproxyapi-latest" + +mkdir -p "$out_dir" + +echo "Building CLIProxyAPI..." +echo " out: $out_path" + +(cd "$repo_root" && go build -o "$out_path" ./cmd/server) + +echo "Done." + diff --git a/scripts/macos/install-cliproxyapi-launchagent.sh b/scripts/macos/install-cliproxyapi-launchagent.sh new file mode 100644 index 00000000..f2e141ee --- /dev/null +++ b/scripts/macos/install-cliproxyapi-launchagent.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "$(uname -s)" != "Darwin" ]]; then + echo "launchd autostart is macOS-only." >&2 + exit 1 +fi + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +default_exe="$repo_root/bin/cliproxyapi" +latest_exe="$repo_root/bin/cliproxyapi-latest" +exe="$default_exe" +if [[ -f "$latest_exe" ]]; then exe="$latest_exe"; fi + +config_path="$repo_root/config.yaml" +logs_dir="$repo_root/logs" +mkdir -p "$logs_dir" + +if [[ ! -f "$exe" ]]; then + echo "Binary not found: $exe" >&2 + echo "Build it with: ./scripts/build.sh" >&2 + exit 1 +fi +chmod +x "$exe" 2>/dev/null || true + +if [[ ! -f "$config_path" ]]; then + echo "Config not found: $config_path" >&2 + exit 1 +fi + +label="com.cliproxyapi" +plist_dir="$HOME/Library/LaunchAgents" +plist_path="$plist_dir/${label}.plist" +mkdir -p "$plist_dir" + +cat >"$plist_path" < + + + + Label + ${label} + + ProgramArguments + + ${exe} + -config + ${config_path} + + + WorkingDirectory + ${repo_root} + + RunAtLoad + + + StandardOutPath + ${logs_dir}/cliproxyapi.out.log + StandardErrorPath + ${logs_dir}/cliproxyapi.err.log + + +EOF + +uid="$(id -u)" +launchctl bootout "gui/${uid}" "$plist_path" >/dev/null 2>&1 || true +launchctl bootstrap "gui/${uid}" "$plist_path" +launchctl kickstart -k "gui/${uid}/${label}" >/dev/null 2>&1 || true + +echo "Installed LaunchAgent: $plist_path" + diff --git a/scripts/macos/restart-cliproxy.sh b/scripts/macos/restart-cliproxy.sh new file mode 100644 index 00000000..8b329924 --- /dev/null +++ b/scripts/macos/restart-cliproxy.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +echo "Restarting CLIProxyAPI..." +"$script_dir/stop-cliproxy.sh" || true +"$script_dir/start-cliproxy.sh" + diff --git a/scripts/macos/start-cliproxy.sh b/scripts/macos/start-cliproxy.sh new file mode 100644 index 00000000..77b1d753 --- /dev/null +++ b/scripts/macos/start-cliproxy.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +default_exe="$repo_root/bin/cliproxyapi" +latest_exe="$repo_root/bin/cliproxyapi-latest" +exe="$default_exe" +if [[ -f "$latest_exe" ]]; then exe="$latest_exe"; fi + +config_path="$repo_root/config.yaml" +logs_dir="$repo_root/logs" +stdout_log="$logs_dir/cliproxyapi.out.log" +stderr_log="$logs_dir/cliproxyapi.err.log" +pid_file="$logs_dir/cliproxyapi.pid" + +mkdir -p "$logs_dir" + +if [[ ! -f "$exe" ]]; then + echo "Binary not found: $exe" >&2 + echo "Build it with: ./scripts/build.sh" >&2 + exit 1 +fi +chmod +x "$exe" 2>/dev/null || true + +if [[ ! -f "$config_path" ]]; then + echo "Config not found: $config_path" >&2 + exit 1 +fi + +port="$( + grep -E '^[[:space:]]*port:[[:space:]]*[0-9]+[[:space:]]*$' "$config_path" 2>/dev/null \ + | head -n 1 \ + | sed -E 's/[^0-9]*([0-9]+).*/\1/' +)" +if [[ -z "${port:-}" ]]; then port="8318"; fi + +if [[ -f "$pid_file" ]]; then + existing_pid="$(cat "$pid_file" 2>/dev/null || true)" + if [[ -n "${existing_pid:-}" ]] && kill -0 "$existing_pid" 2>/dev/null; then + echo "CLIProxyAPI already running (PID $existing_pid)." + exit 0 + fi +fi + +if command -v lsof >/dev/null 2>&1; then + if lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1; then + echo "Port $port is already in use." >&2 + echo "If this is CLIProxyAPI, run: ./scripts/restart.sh" >&2 + exit 0 + fi +fi + +echo "Starting CLIProxyAPI..." +echo " exe: $exe" +echo " config: $config_path" +echo " logs: $logs_dir" + +nohup "$exe" -config "$config_path" >"$stdout_log" 2>"$stderr_log" & +pid="$!" +echo "$pid" >"$pid_file" + +echo "Started (PID $pid). Tail logs:" +echo " tail -f \"$stdout_log\"" + diff --git a/scripts/macos/stop-cliproxy.sh b/scripts/macos/stop-cliproxy.sh new file mode 100644 index 00000000..90dc6925 --- /dev/null +++ b/scripts/macos/stop-cliproxy.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +pid_file="$repo_root/logs/cliproxyapi.pid" + +stop_pid() { + local pid="$1" + if ! kill -0 "$pid" 2>/dev/null; then + return 1 + fi + echo "Stopping CLIProxyAPI (PID $pid)" + kill "$pid" 2>/dev/null || true + for _ in {1..20}; do + if ! kill -0 "$pid" 2>/dev/null; then + return 0 + fi + sleep 0.25 + done + echo "Force killing CLIProxyAPI (PID $pid)" + kill -9 "$pid" 2>/dev/null || true + return 0 +} + +stopped_any=false + +if [[ -f "$pid_file" ]]; then + pid="$(cat "$pid_file" 2>/dev/null || true)" + if [[ -n "${pid:-}" ]] && stop_pid "$pid"; then + stopped_any=true + fi + rm -f "$pid_file" +fi + +for name in cliproxyapi-latest cliproxyapi; do + if command -v pkill >/dev/null 2>&1; then + if pkill -x "$name" 2>/dev/null; then + echo "Stopping $name" + stopped_any=true + fi + fi +done + +if [[ "$stopped_any" == "false" ]]; then + echo "No running CLIProxyAPI process found." +fi + diff --git a/scripts/macos/uninstall-cliproxyapi-launchagent.sh b/scripts/macos/uninstall-cliproxyapi-launchagent.sh new file mode 100644 index 00000000..89a6990f --- /dev/null +++ b/scripts/macos/uninstall-cliproxyapi-launchagent.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "$(uname -s)" != "Darwin" ]]; then + echo "launchd autostart is macOS-only." >&2 + exit 1 +fi + +label="com.cliproxyapi" +plist_path="$HOME/Library/LaunchAgents/${label}.plist" +uid="$(id -u)" + +if [[ -f "$plist_path" ]]; then + launchctl bootout "gui/${uid}" "$plist_path" >/dev/null 2>&1 || true + rm -f "$plist_path" + echo "Removed LaunchAgent: $plist_path" +else + echo "LaunchAgent not found: $plist_path" +fi + diff --git a/scripts/restart-cliproxy.ps1 b/scripts/restart-cliproxy.ps1 index 156c5eb0..68949799 100644 --- a/scripts/restart-cliproxy.ps1 +++ b/scripts/restart-cliproxy.ps1 @@ -1,18 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -Write-Host "Restarting CLIProxyAPI..." +& (Join-Path $PSScriptRoot "windows\\restart-cliproxy.ps1") @args -try { - & (Join-Path $PSScriptRoot "stop-cliproxy.ps1") -} catch { - Write-Warning "Stop failed: $($_.Exception.Message)" - Write-Host "" - Write-Host "If you see 'Access is denied', the server is running elevated." - Write-Host "One-time fix (run in an elevated PowerShell):" - Write-Host " taskkill /IM cliproxyapi.exe /F" - Write-Host " schtasks /Delete /TN \"CLIProxyAPI-Logon\" /F" - throw -} - -& (Join-Path $PSScriptRoot "start-cliproxy.ps1") diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..68650876 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$script_dir/macos/restart-cliproxy.sh" "$@" + diff --git a/scripts/run-cliproxyapi-hidden.vbs b/scripts/run-cliproxyapi-hidden.vbs index 19cfa940..fb25baa3 100644 --- a/scripts/run-cliproxyapi-hidden.vbs +++ b/scripts/run-cliproxyapi-hidden.vbs @@ -1,44 +1,11 @@ Option Explicit -' Runs CLIProxyAPI at logon without showing a console window. -' This script delegates to scripts\start-cliproxy.ps1. - -Function ParentProcessName() - On Error Resume Next - Dim query, wmi, procs, proc - ParentProcessName = "" - Set wmi = GetObject("winmgmts:\\\\.\\root\\cimv2") - query = "Select ProcessId, ParentProcessId, CommandLine From Win32_Process Where Name='wscript.exe'" - Set procs = wmi.ExecQuery(query) - For Each proc In procs - If InStr(LCase(proc.CommandLine), LCase(WScript.ScriptFullName)) > 0 Then - Dim parentPid, parentQuery, parentProcs, parentProc - parentPid = proc.ParentProcessId - parentQuery = "Select Name From Win32_Process Where ProcessId=" & parentPid - Set parentProcs = wmi.ExecQuery(parentQuery) - For Each parentProc In parentProcs - ParentProcessName = LCase(parentProc.Name) - Exit Function - Next - End If - Next -End Function - -Dim shell, fso, scriptDir, ps1Path, cmd -Set shell = CreateObject("WScript.Shell") +Dim fso, shell, targetVbs, cmd Set fso = CreateObject("Scripting.FileSystemObject") +Set shell = CreateObject("WScript.Shell") -scriptDir = fso.GetParentFolderName(WScript.ScriptFullName) -ps1Path = scriptDir & "\start-cliproxy.ps1" +targetVbs = fso.BuildPath(fso.GetParentFolderName(WScript.ScriptFullName), "windows\\run-cliproxyapi-hidden.vbs") +cmd = "wscript.exe """ & targetVbs & """" -Dim parentName -parentName = ParentProcessName() - -' If this is invoked by Task Scheduler, exit early so we don't spawn an elevated -' server process (which is hard to stop/update). Prefer a HKCU Run entry instead. -If parentName = "taskeng.exe" Or parentName = "taskhostw.exe" Then - WScript.Quit 0 -End If - -cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File """ & ps1Path & """" shell.Run cmd, 0, False + diff --git a/scripts/setup-droid-cliproxy.ps1 b/scripts/setup-droid-cliproxy.ps1 index c0cc80f2..46acc414 100644 --- a/scripts/setup-droid-cliproxy.ps1 +++ b/scripts/setup-droid-cliproxy.ps1 @@ -1,159 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -param( - [Parameter(Mandatory = $false)] - [string]$ProxyApiKey = $env:CLIPROXY_API_KEY, +& (Join-Path $PSScriptRoot "windows\\setup-droid-cliproxy.ps1") @args - [Parameter(Mandatory = $false)] - [string]$ProxyBaseUrl = "http://127.0.0.1:8317/v1", - - [Parameter(Mandatory = $false)] - [string]$ProxyModel = "gpt-5.1" -) - -function Get-RepoRoot { - return (Resolve-Path (Join-Path $PSScriptRoot "..")).Path -} - -function Ensure-Dir([string]$Path) { - if (-not (Test-Path -LiteralPath $Path)) { - New-Item -ItemType Directory -Path $Path | Out-Null - } -} - -function Build-CLIProxy([string]$RepoRoot) { - $binDir = Join-Path $RepoRoot "bin" - Ensure-Dir $binDir - - $exePath = Join-Path $binDir "cliproxyapi.exe" - - Write-Host "Building CLIProxyAPI -> $exePath" - Push-Location $RepoRoot - try { - & go build -o $exePath .\cmd\server - } finally { - Pop-Location - } - - return $exePath -} - -function Ensure-DroidConfig([string]$BaseUrl, [string]$ApiKey, [string]$Model) { - $factoryDir = Join-Path $env:USERPROFILE ".factory" - Ensure-Dir $factoryDir - - $configPath = Join-Path $factoryDir "config.json" - $backupPath = Join-Path $factoryDir ("config.json.bak." + (Get-Date -Format "yyyyMMdd-HHmmss")) - - $existingConfig = $null - if (Test-Path -LiteralPath $configPath) { - Copy-Item -LiteralPath $configPath -Destination $backupPath -Force - Write-Host "Backed up existing Droid config -> $backupPath" - try { - $existingConfig = Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json - } catch { - $existingConfig = $null - } - } - if (-not $existingConfig) { - $existingConfig = [PSCustomObject]@{} - } - - $modelsToAdd = @( - "gpt-5.2", - "gpt-5.2(low)", - "gpt-5.2(medium)", - "gpt-5.2(high)", - "gpt-5.2(xhigh)", - "gpt-5.1-codex-max", - "gpt-5.1-codex-max(low)", - "gpt-5.1-codex-max(medium)", - "gpt-5.1-codex-max(high)", - "gpt-5.1-codex-max(xhigh)", - "gemini-3-pro-preview", - "gemini-claude-sonnet-4-5-thinking", - "gemini-claude-opus-4-5-thinking" - ) - - $modelsToRemove = @( - "gpt-5-codex", - "gpt-5-codex-mini", - "gpt-5", - "gemini-3-pro-image-preview", - "gemini-2.5-flash-lite", - "gpt-oss-120b-medium", - "gemini-claude-sonnet-4-5", - "gpt-5.1", - "gemini-2.5-flash", - "gemini-2.5-computer-use-preview-10-2025", - "gpt-5.1-codex-mini", - "gpt-5.1-codex" - ) - - $newEntries = $modelsToAdd | ForEach-Object { - $modelId = $_ - $displayModelId = $modelId - if ($modelId -match '\((low|medium|high|xhigh|none|auto)\)$') { - $displayModelId = ($modelId -replace '\((low|medium|high|xhigh|none|auto)\)$', ' (reasoning: $1)') - } - [PSCustomObject]@{ - model_display_name = "CLIProxy (local): $displayModelId" - model = $modelId - base_url = $BaseUrl - api_key = $ApiKey - provider = "openai" - } - } - - $existingModels = @() - if ($existingConfig.PSObject.Properties.Name -contains "custom_models" -and $existingConfig.custom_models) { - $existingModels = @($existingConfig.custom_models) - } - - $filteredExisting = $existingModels | Where-Object { - $m = $_ - -not ( - $m -and - ($m.PSObject.Properties.Name -contains "base_url") -and - ($m.PSObject.Properties.Name -contains "model") -and - ($m.base_url -eq $BaseUrl) -and - ( - ($modelsToAdd -contains [string]$m.model) -or - ($modelsToRemove -contains [string]$m.model) - ) - ) - } - - $existingConfig | Add-Member -NotePropertyName "custom_models" -NotePropertyValue (@($filteredExisting) + @($newEntries)) -Force - - $json = $existingConfig | ConvertTo-Json -Depth 20 - $utf8NoBom = New-Object System.Text.UTF8Encoding($false) - [System.IO.File]::WriteAllText($configPath, $json, $utf8NoBom) - Write-Host "Wrote Droid BYOK config -> $configPath" -} - -function Write-UsageHint([string]$ApiKey, [string]$BaseUrl) { - Write-Host "" - Write-Host "Next:" - Write-Host " 1) Start the proxy: scripts\\start-cliproxy.ps1" - Write-Host " 2) In Droid: /model -> select 'CLIProxy (local)'" - Write-Host "" - Write-Host "Proxy auth (Droid api_key): $ApiKey" - Write-Host "Proxy base_url: $BaseUrl" -} - -$repoRoot = Get-RepoRoot -$configPath = Join-Path $repoRoot "config.yaml" - -if (-not (Test-Path -LiteralPath $configPath)) { - throw "Expected config file not found: $configPath" -} - -if (-not $ProxyApiKey -or $ProxyApiKey.Trim() -eq "") { - throw "Missing proxy API key. Provide -ProxyApiKey or set env var CLIPROXY_API_KEY." -} - -Build-CLIProxy -RepoRoot $repoRoot | Out-Null -Ensure-DroidConfig -BaseUrl $ProxyBaseUrl -ApiKey $ProxyApiKey -Model $ProxyModel -Write-UsageHint -ApiKey $ProxyApiKey -BaseUrl $ProxyBaseUrl diff --git a/scripts/start-cliproxy.ps1 b/scripts/start-cliproxy.ps1 index 255e5288..536fde7c 100644 --- a/scripts/start-cliproxy.ps1 +++ b/scripts/start-cliproxy.ps1 @@ -1,61 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -function Get-RepoRoot { - return (Resolve-Path (Join-Path $PSScriptRoot "..")).Path -} +& (Join-Path $PSScriptRoot "windows\\start-cliproxy.ps1") @args -function Ensure-Dir([string]$Path) { - if (-not (Test-Path -LiteralPath $Path)) { - New-Item -ItemType Directory -Path $Path | Out-Null - } -} - -$repoRoot = Get-RepoRoot -$defaultExePath = Join-Path $repoRoot "bin\\cliproxyapi.exe" -$latestExePath = Join-Path $repoRoot "bin\\cliproxyapi-latest.exe" -$exePath = if (Test-Path -LiteralPath $latestExePath) { $latestExePath } else { $defaultExePath } -$configPath = Join-Path $repoRoot "config.yaml" -$logsDir = Join-Path $repoRoot "logs" -Ensure-Dir $logsDir - -$stdoutLog = Join-Path $logsDir "cliproxyapi.out.log" -$stderrLog = Join-Path $logsDir "cliproxyapi.err.log" - -if (-not (Test-Path -LiteralPath $exePath)) { - throw "Binary not found: $exePath. Build it with: go build -o bin\\cliproxyapi.exe .\\cmd\\server (or: scripts\\build-cliproxyapi.ps1)." -} -if (-not (Test-Path -LiteralPath $configPath)) { - throw "Config not found: $configPath" -} - -function Get-ConfigPort([string]$Path) { - try { - $line = Get-Content -LiteralPath $Path | Where-Object { $_ -match '^\s*port:\s*\d+\s*$' } | Select-Object -First 1 - if ($line -match '(\d+)') { return [int]$Matches[1] } - } catch {} - return 8318 -} - -$port = Get-ConfigPort $configPath -$existing = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1 -if ($existing) { - Write-Warning "Port $port is already in use (PID $($existing.OwningProcess))." - Write-Host "If this is CLIProxyAPI, run: powershell -NoProfile -ExecutionPolicy Bypass -File .\\scripts\\restart-cliproxy.ps1" - return -} - -Write-Host "Starting CLIProxyAPI..." -Write-Host " exe: $exePath" -Write-Host " config: $configPath" -Write-Host " logs: $logsDir" - -Start-Process -FilePath $exePath ` - -ArgumentList @("-config", $configPath) ` - -WorkingDirectory $repoRoot ` - -WindowStyle Hidden ` - -RedirectStandardOutput $stdoutLog ` - -RedirectStandardError $stderrLog | Out-Null - -Write-Host "Started. Tail logs:" -Write-Host " Get-Content -Wait $stdoutLog" diff --git a/scripts/start.sh b/scripts/start.sh new file mode 100644 index 00000000..af7447d7 --- /dev/null +++ b/scripts/start.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$script_dir/macos/start-cliproxy.sh" "$@" + diff --git a/scripts/stop-cliproxy.ps1 b/scripts/stop-cliproxy.ps1 index 5b5f19d5..e50ad519 100644 --- a/scripts/stop-cliproxy.ps1 +++ b/scripts/stop-cliproxy.ps1 @@ -1,30 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -$procNames = @("cliproxyapi", "cliproxyapi-latest") -$procs = @() -foreach ($name in $procNames) { - $procs += @(Get-Process -Name $name -ErrorAction SilentlyContinue) -} +& (Join-Path $PSScriptRoot "windows\\stop-cliproxy.ps1") @args -if (-not $procs) { - Write-Host "No running CLIProxyAPI process found." - exit 0 -} - -$hadError = $false -foreach ($proc in $procs) { - $procId = $proc.Id - Write-Host "Stopping $($proc.ProcessName) (PID $procId)" - try { - Stop-Process -Id $procId -Force -ErrorAction Stop - } catch { - $hadError = $true - Write-Warning "Failed to stop PID ${procId}: $($_.Exception.Message)" - Write-Warning "If CLIProxyAPI was started elevated (e.g. via a 'HighestAvailable' scheduled task), run this script from an elevated PowerShell or stop it via Task Manager (Run as administrator)." - } -} - -if ($hadError) { - throw "Failed to stop one or more CLIProxyAPI processes." -} diff --git a/scripts/stop.sh b/scripts/stop.sh new file mode 100644 index 00000000..118f5664 --- /dev/null +++ b/scripts/stop.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$script_dir/macos/stop-cliproxy.sh" "$@" + diff --git a/scripts/uninstall-autostart.sh b/scripts/uninstall-autostart.sh new file mode 100644 index 00000000..3399f3c4 --- /dev/null +++ b/scripts/uninstall-autostart.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "$script_dir/macos/uninstall-cliproxyapi-launchagent.sh" "$@" + diff --git a/scripts/uninstall-cliproxyapi-startup-run.ps1 b/scripts/uninstall-cliproxyapi-startup-run.ps1 index 676c344d..b3bd11ad 100644 --- a/scripts/uninstall-cliproxyapi-startup-run.ps1 +++ b/scripts/uninstall-cliproxyapi-startup-run.ps1 @@ -1,9 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -$valueName = "CLIProxyAPI" - -Write-Host "Removing HKCU Run entry '$valueName'..." -Remove-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Name $valueName -ErrorAction SilentlyContinue -Write-Host "Done." +& (Join-Path $PSScriptRoot "windows\\uninstall-cliproxyapi-startup-run.ps1") @args diff --git a/scripts/uninstall-cliproxyapi-startup-task.ps1 b/scripts/uninstall-cliproxyapi-startup-task.ps1 index 861becbd..0360b770 100644 --- a/scripts/uninstall-cliproxyapi-startup-task.ps1 +++ b/scripts/uninstall-cliproxyapi-startup-task.ps1 @@ -1,23 +1,5 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -$taskName = "CLIProxyAPI" +& (Join-Path $PSScriptRoot "windows\\uninstall-cliproxyapi-startup-task.ps1") @args -Write-Host "Deleting scheduled task '$taskName'..." - -try { - if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop - Write-Host "Done." - exit 0 - } -} catch { - Write-Warning "Unregister-ScheduledTask failed: $($_.Exception.Message)" - Write-Host "Falling back to schtasks.exe..." -} - -& schtasks.exe /Delete /TN $taskName /F | Out-Null -if ($LASTEXITCODE -ne 0) { - throw "schtasks.exe failed with exit code $LASTEXITCODE" -} -Write-Host "Done." diff --git a/scripts/windows/README.md b/scripts/windows/README.md new file mode 100644 index 00000000..94a0648f --- /dev/null +++ b/scripts/windows/README.md @@ -0,0 +1,54 @@ +# Droid CLI + CLIProxyAPI (Windows) + +This repo can run a local OpenAI-compatible proxy (`CLIProxyAPI`) and configure Factory's `droid` CLI to use it via BYOK custom models. + +## One-time setup + +1. From the repo root, run: + - `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\setup-droid-cliproxy.ps1 -ProxyApiKey ""` + +This will: +- Build `bin\cliproxyapi.exe` +- Write `C:\Users\\.factory\config.json` with a `custom_models` entry pointing at `http://127.0.0.1:8317/v1` + +## Start / stop the proxy + +- Build (recommended after pulling updates): `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\build-cliproxyapi.ps1` +- Start: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\start-cliproxy.ps1` +- Stop: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\stop-cliproxy.ps1` +- Restart: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\restart-cliproxy.ps1` + +Logs: +- `logs\cliproxyapi.out.log` +- `logs\cliproxyapi.err.log` + +## Auto-start at logon (Windows) + +Recommended: install a per-user startup entry (no admin required): + +- Install: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\install-cliproxyapi-startup-run.ps1` +- Uninstall: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\uninstall-cliproxyapi-startup-run.ps1` + +Optional: install a scheduled task (may require admin depending on your system policy): + +- Install: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\install-cliproxyapi-startup-task.ps1` +- Uninstall: `powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\uninstall-cliproxyapi-startup-task.ps1` + +This uses `scripts\run-cliproxyapi-hidden.vbs` to start the server hidden and write logs to `logs\`. + +### One-time cleanup (if stop says "Access is denied") + +That means CLIProxyAPI was started **elevated** (commonly via a scheduled task with `RunLevel=HighestAvailable`), and a normal restart can't kill it. + +Run once in an **elevated PowerShell**: + +- `taskkill /IM cliproxyapi.exe /F` +- `schtasks /Delete /TN "CLIProxyAPI-Logon" /F` (if it exists) + +## Use it in Droid + +- In `droid`, run `/model` and pick `CLIProxy (local)` +- In non-interactive mode, use: `droid exec --model custom:gpt-5.1 "..."` (replace model as needed) +- `scripts\setup-droid-cliproxy.ps1` adds several `custom:` entries (e.g. `custom:gpt-5.2`, `custom:gpt-5.1-codex-max`, `custom:gemini-3-pro-preview`) +- For reasoning variants, pick a model like `CLIProxy (local): gpt-5.2 (reasoning: high)` (this uses `gpt-5.2(high)` under the hood). +- `gpt-5.1-codex-max` also has reasoning variants (including `xhigh`) like `custom:gpt-5.1-codex-max(xhigh)`. diff --git a/scripts/windows/build-cliproxyapi.ps1 b/scripts/windows/build-cliproxyapi.ps1 new file mode 100644 index 00000000..420158a8 --- /dev/null +++ b/scripts/windows/build-cliproxyapi.ps1 @@ -0,0 +1,26 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +function Get-RepoRoot { + return (Resolve-Path (Join-Path $PSScriptRoot "..\\..")).Path +} + +$repoRoot = Get-RepoRoot +$outDir = Join-Path $repoRoot "bin" +$outPath = Join-Path $outDir "cliproxyapi-latest.exe" + +if (-not (Test-Path -LiteralPath $outDir)) { + New-Item -ItemType Directory -Path $outDir | Out-Null +} + +Write-Host "Building CLIProxyAPI..." +Write-Host " out: $outPath" + +Push-Location $repoRoot +try { + go build -o $outPath .\cmd\server +} finally { + Pop-Location +} + +Write-Host "Done." diff --git a/scripts/windows/fix-droid-spec-model.ps1 b/scripts/windows/fix-droid-spec-model.ps1 new file mode 100644 index 00000000..acd73a33 --- /dev/null +++ b/scripts/windows/fix-droid-spec-model.ps1 @@ -0,0 +1,79 @@ +param( + [Parameter(Mandatory = $false)] + [string]$Model = "custom:gpt-5.2(high)" +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +function Ensure-CustomModelExists([string]$ModelId) { + if (-not $ModelId.StartsWith("custom:")) { + throw "Model must start with 'custom:'. Got: $ModelId" + } + $inner = $ModelId.Substring("custom:".Length) + + $configPath = Join-Path $env:USERPROFILE ".factory\\config.json" + if (-not (Test-Path -LiteralPath $configPath)) { + throw "Droid BYOK config not found: $configPath" + } + $cfg = Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json + $models = @($cfg.custom_models | ForEach-Object { [string]$_.model }) + if (-not ($models -contains $inner)) { + throw "Custom model '$ModelId' not found in $configPath. Available: $($models -join ', ')" + } +} + +function Update-JsonFile([string]$Path, [scriptblock]$Mutator) { + $obj = Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json + & $Mutator $obj | Out-Null + $json = $obj | ConvertTo-Json -Depth 50 + $utf8NoBom = New-Object System.Text.UTF8Encoding($false) + [System.IO.File]::WriteAllText($Path, $json, $utf8NoBom) +} + +function Update-JsoncModelLine([string]$Path, [string]$ModelId) { + $text = Get-Content -Raw -LiteralPath $Path + if ($text -notmatch '"model"\s*:\s*"[^"]*"') { + throw "Couldn't find a JSON 'model' field in: $Path" + } + $updated = [regex]::Replace($text, '"model"\s*:\s*"[^"]*"', ('"model": "' + $ModelId + '"'), 1) + $utf8NoBom = New-Object System.Text.UTF8Encoding($false) + [System.IO.File]::WriteAllText($Path, $updated, $utf8NoBom) +} + +Ensure-CustomModelExists -ModelId $Model + +# Update global settings.json (JSONC with comments) +$globalSettingsPath = Join-Path $env:USERPROFILE ".factory\\settings.json" +if (Test-Path -LiteralPath $globalSettingsPath) { + Update-JsoncModelLine -Path $globalSettingsPath -ModelId $Model + Write-Host "Updated global model -> $globalSettingsPath" +} else { + Write-Host "Skipped (not found): $globalSettingsPath" +} + +# Update the latest session settings for this folder (pure JSON) +$sessionDir = Join-Path $env:USERPROFILE ".factory\\sessions\\-D-code-CLIProxyAPI" +if (Test-Path -LiteralPath $sessionDir) { + $latest = Get-ChildItem -LiteralPath $sessionDir -Filter "*.settings.json" -File | + Sort-Object LastWriteTime -Descending | + Select-Object -First 1 + if ($latest) { + Update-JsonFile -Path $latest.FullName -Mutator { + param($o) + $o.model = $Model + if ($o.PSObject.Properties.Name -contains "providerLock") { $o.PSObject.Properties.Remove("providerLock") } + if ($o.PSObject.Properties.Name -contains "providerLockTimestamp") { $o.PSObject.Properties.Remove("providerLockTimestamp") } + if ($o.PSObject.Properties.Name -contains "apiProviderLock") { $o.PSObject.Properties.Remove("apiProviderLock") } + if ($o.PSObject.Properties.Name -contains "apiProviderLockTimestamp") { $o.PSObject.Properties.Remove("apiProviderLockTimestamp") } + } + Write-Host "Updated session model -> $($latest.FullName)" + } else { + Write-Host "No session settings found in: $sessionDir" + } +} else { + Write-Host "Skipped (not found): $sessionDir" +} + +Write-Host "" +Write-Host "Restart droid, then try Spec mode again." diff --git a/scripts/windows/install-cliproxyapi-startup-run.ps1 b/scripts/windows/install-cliproxyapi-startup-run.ps1 new file mode 100644 index 00000000..c6f52815 --- /dev/null +++ b/scripts/windows/install-cliproxyapi-startup-run.ps1 @@ -0,0 +1,21 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$valueName = "CLIProxyAPI" +$scriptDir = $PSScriptRoot +$ps1Path = Join-Path $scriptDir "start-cliproxy.ps1" + +if (-not (Test-Path -LiteralPath $ps1Path)) { + throw "Missing starter script: $ps1Path" +} + +# Use a hidden PowerShell process at logon. +$command = "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$ps1Path`"" + +Write-Host "Installing HKCU Run entry '$valueName'..." +Write-Host " Command: $command" + +New-Item -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Force | Out-Null +Set-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Name $valueName -Value $command + +Write-Host "Done." diff --git a/scripts/windows/install-cliproxyapi-startup-task.ps1 b/scripts/windows/install-cliproxyapi-startup-task.ps1 new file mode 100644 index 00000000..ab49f14d --- /dev/null +++ b/scripts/windows/install-cliproxyapi-startup-task.ps1 @@ -0,0 +1,40 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$taskName = "CLIProxyAPI" +$scriptDir = $PSScriptRoot +$vbsPath = Join-Path $scriptDir "run-cliproxyapi-hidden.vbs" + +if (-not (Test-Path -LiteralPath $vbsPath)) { + throw "Missing launcher: $vbsPath" +} + +Write-Host "Creating scheduled task '$taskName' (At log on)..." +Write-Host " Launcher: $vbsPath" + +try { + $action = New-ScheduledTaskAction -Execute "wscript.exe" -Argument "`"$vbsPath`"" + $trigger = New-ScheduledTaskTrigger -AtLogOn + $userId = if ($env:USERDOMAIN) { "$($env:USERDOMAIN)\\$($env:USERNAME)" } else { $env:USERNAME } + $principal = New-ScheduledTaskPrincipal -UserId $userId -LogonType Interactive -RunLevel Limited + $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable + + Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null + Write-Host "Done." + Write-Host "Verify:" + Write-Host " Get-ScheduledTask -TaskName $taskName | Format-List *" + exit 0 +} catch { + Write-Warning "Register-ScheduledTask failed: $($_.Exception.Message)" + Write-Host "Falling back to schtasks.exe..." +} + +$taskAction = "wscript.exe `"$vbsPath`"" +& schtasks.exe /Create /TN $taskName /SC ONLOGON /F /RL LIMITED /TR $taskAction | Out-Null +if ($LASTEXITCODE -ne 0) { + throw "schtasks.exe failed with exit code $LASTEXITCODE. Try running this script in an elevated PowerShell." +} + +Write-Host "Done." +Write-Host "Verify:" +Write-Host " schtasks /Query /TN $taskName /V /FO LIST" diff --git a/scripts/windows/restart-cliproxy.ps1 b/scripts/windows/restart-cliproxy.ps1 new file mode 100644 index 00000000..156c5eb0 --- /dev/null +++ b/scripts/windows/restart-cliproxy.ps1 @@ -0,0 +1,18 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +Write-Host "Restarting CLIProxyAPI..." + +try { + & (Join-Path $PSScriptRoot "stop-cliproxy.ps1") +} catch { + Write-Warning "Stop failed: $($_.Exception.Message)" + Write-Host "" + Write-Host "If you see 'Access is denied', the server is running elevated." + Write-Host "One-time fix (run in an elevated PowerShell):" + Write-Host " taskkill /IM cliproxyapi.exe /F" + Write-Host " schtasks /Delete /TN \"CLIProxyAPI-Logon\" /F" + throw +} + +& (Join-Path $PSScriptRoot "start-cliproxy.ps1") diff --git a/scripts/windows/run-cliproxyapi-hidden.vbs b/scripts/windows/run-cliproxyapi-hidden.vbs new file mode 100644 index 00000000..19cfa940 --- /dev/null +++ b/scripts/windows/run-cliproxyapi-hidden.vbs @@ -0,0 +1,44 @@ +Option Explicit + +' Runs CLIProxyAPI at logon without showing a console window. +' This script delegates to scripts\start-cliproxy.ps1. + +Function ParentProcessName() + On Error Resume Next + Dim query, wmi, procs, proc + ParentProcessName = "" + Set wmi = GetObject("winmgmts:\\\\.\\root\\cimv2") + query = "Select ProcessId, ParentProcessId, CommandLine From Win32_Process Where Name='wscript.exe'" + Set procs = wmi.ExecQuery(query) + For Each proc In procs + If InStr(LCase(proc.CommandLine), LCase(WScript.ScriptFullName)) > 0 Then + Dim parentPid, parentQuery, parentProcs, parentProc + parentPid = proc.ParentProcessId + parentQuery = "Select Name From Win32_Process Where ProcessId=" & parentPid + Set parentProcs = wmi.ExecQuery(parentQuery) + For Each parentProc In parentProcs + ParentProcessName = LCase(parentProc.Name) + Exit Function + Next + End If + Next +End Function + +Dim shell, fso, scriptDir, ps1Path, cmd +Set shell = CreateObject("WScript.Shell") +Set fso = CreateObject("Scripting.FileSystemObject") + +scriptDir = fso.GetParentFolderName(WScript.ScriptFullName) +ps1Path = scriptDir & "\start-cliproxy.ps1" + +Dim parentName +parentName = ParentProcessName() + +' If this is invoked by Task Scheduler, exit early so we don't spawn an elevated +' server process (which is hard to stop/update). Prefer a HKCU Run entry instead. +If parentName = "taskeng.exe" Or parentName = "taskhostw.exe" Then + WScript.Quit 0 +End If + +cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File """ & ps1Path & """" +shell.Run cmd, 0, False diff --git a/scripts/windows/setup-droid-cliproxy.ps1 b/scripts/windows/setup-droid-cliproxy.ps1 new file mode 100644 index 00000000..0e4a1839 --- /dev/null +++ b/scripts/windows/setup-droid-cliproxy.ps1 @@ -0,0 +1,159 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +param( + [Parameter(Mandatory = $false)] + [string]$ProxyApiKey = $env:CLIPROXY_API_KEY, + + [Parameter(Mandatory = $false)] + [string]$ProxyBaseUrl = "http://127.0.0.1:8317/v1", + + [Parameter(Mandatory = $false)] + [string]$ProxyModel = "gpt-5.1" +) + +function Get-RepoRoot { + return (Resolve-Path (Join-Path $PSScriptRoot "..\\..")).Path +} + +function Ensure-Dir([string]$Path) { + if (-not (Test-Path -LiteralPath $Path)) { + New-Item -ItemType Directory -Path $Path | Out-Null + } +} + +function Build-CLIProxy([string]$RepoRoot) { + $binDir = Join-Path $RepoRoot "bin" + Ensure-Dir $binDir + + $exePath = Join-Path $binDir "cliproxyapi.exe" + + Write-Host "Building CLIProxyAPI -> $exePath" + Push-Location $RepoRoot + try { + & go build -o $exePath .\cmd\server + } finally { + Pop-Location + } + + return $exePath +} + +function Ensure-DroidConfig([string]$BaseUrl, [string]$ApiKey, [string]$Model) { + $factoryDir = Join-Path $env:USERPROFILE ".factory" + Ensure-Dir $factoryDir + + $configPath = Join-Path $factoryDir "config.json" + $backupPath = Join-Path $factoryDir ("config.json.bak." + (Get-Date -Format "yyyyMMdd-HHmmss")) + + $existingConfig = $null + if (Test-Path -LiteralPath $configPath) { + Copy-Item -LiteralPath $configPath -Destination $backupPath -Force + Write-Host "Backed up existing Droid config -> $backupPath" + try { + $existingConfig = Get-Content -Raw -LiteralPath $configPath | ConvertFrom-Json + } catch { + $existingConfig = $null + } + } + if (-not $existingConfig) { + $existingConfig = [PSCustomObject]@{} + } + + $modelsToAdd = @( + "gpt-5.2", + "gpt-5.2(low)", + "gpt-5.2(medium)", + "gpt-5.2(high)", + "gpt-5.2(xhigh)", + "gpt-5.1-codex-max", + "gpt-5.1-codex-max(low)", + "gpt-5.1-codex-max(medium)", + "gpt-5.1-codex-max(high)", + "gpt-5.1-codex-max(xhigh)", + "gemini-3-pro-preview", + "gemini-claude-sonnet-4-5-thinking", + "gemini-claude-opus-4-5-thinking" + ) + + $modelsToRemove = @( + "gpt-5-codex", + "gpt-5-codex-mini", + "gpt-5", + "gemini-3-pro-image-preview", + "gemini-2.5-flash-lite", + "gpt-oss-120b-medium", + "gemini-claude-sonnet-4-5", + "gpt-5.1", + "gemini-2.5-flash", + "gemini-2.5-computer-use-preview-10-2025", + "gpt-5.1-codex-mini", + "gpt-5.1-codex" + ) + + $newEntries = $modelsToAdd | ForEach-Object { + $modelId = $_ + $displayModelId = $modelId + if ($modelId -match '\((low|medium|high|xhigh|none|auto)\)$') { + $displayModelId = ($modelId -replace '\((low|medium|high|xhigh|none|auto)\)$', ' (reasoning: $1)') + } + [PSCustomObject]@{ + model_display_name = "CLIProxy (local): $displayModelId" + model = $modelId + base_url = $BaseUrl + api_key = $ApiKey + provider = "openai" + } + } + + $existingModels = @() + if ($existingConfig.PSObject.Properties.Name -contains "custom_models" -and $existingConfig.custom_models) { + $existingModels = @($existingConfig.custom_models) + } + + $filteredExisting = $existingModels | Where-Object { + $m = $_ + -not ( + $m -and + ($m.PSObject.Properties.Name -contains "base_url") -and + ($m.PSObject.Properties.Name -contains "model") -and + ($m.base_url -eq $BaseUrl) -and + ( + ($modelsToAdd -contains [string]$m.model) -or + ($modelsToRemove -contains [string]$m.model) + ) + ) + } + + $existingConfig | Add-Member -NotePropertyName "custom_models" -NotePropertyValue (@($filteredExisting) + @($newEntries)) -Force + + $json = $existingConfig | ConvertTo-Json -Depth 20 + $utf8NoBom = New-Object System.Text.UTF8Encoding($false) + [System.IO.File]::WriteAllText($configPath, $json, $utf8NoBom) + Write-Host "Wrote Droid BYOK config -> $configPath" +} + +function Write-UsageHint([string]$ApiKey, [string]$BaseUrl) { + Write-Host "" + Write-Host "Next:" + Write-Host " 1) Start the proxy: scripts\\start-cliproxy.ps1" + Write-Host " 2) In Droid: /model -> select 'CLIProxy (local)'" + Write-Host "" + Write-Host "Proxy auth (Droid api_key): $ApiKey" + Write-Host "Proxy base_url: $BaseUrl" +} + +$repoRoot = Get-RepoRoot +$configPath = Join-Path $repoRoot "config.yaml" + +if (-not (Test-Path -LiteralPath $configPath)) { + throw "Expected config file not found: $configPath" +} + +if (-not $ProxyApiKey -or $ProxyApiKey.Trim() -eq "") { + throw "Missing proxy API key. Provide -ProxyApiKey or set env var CLIPROXY_API_KEY." +} + +Build-CLIProxy -RepoRoot $repoRoot | Out-Null +Ensure-DroidConfig -BaseUrl $ProxyBaseUrl -ApiKey $ProxyApiKey -Model $ProxyModel +Write-UsageHint -ApiKey $ProxyApiKey -BaseUrl $ProxyBaseUrl diff --git a/scripts/windows/start-cliproxy.ps1 b/scripts/windows/start-cliproxy.ps1 new file mode 100644 index 00000000..f832b70a --- /dev/null +++ b/scripts/windows/start-cliproxy.ps1 @@ -0,0 +1,61 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +function Get-RepoRoot { + return (Resolve-Path (Join-Path $PSScriptRoot "..\\..")).Path +} + +function Ensure-Dir([string]$Path) { + if (-not (Test-Path -LiteralPath $Path)) { + New-Item -ItemType Directory -Path $Path | Out-Null + } +} + +$repoRoot = Get-RepoRoot +$defaultExePath = Join-Path $repoRoot "bin\\cliproxyapi.exe" +$latestExePath = Join-Path $repoRoot "bin\\cliproxyapi-latest.exe" +$exePath = if (Test-Path -LiteralPath $latestExePath) { $latestExePath } else { $defaultExePath } +$configPath = Join-Path $repoRoot "config.yaml" +$logsDir = Join-Path $repoRoot "logs" +Ensure-Dir $logsDir + +$stdoutLog = Join-Path $logsDir "cliproxyapi.out.log" +$stderrLog = Join-Path $logsDir "cliproxyapi.err.log" + +if (-not (Test-Path -LiteralPath $exePath)) { + throw "Binary not found: $exePath. Build it with: go build -o bin\\cliproxyapi.exe .\\cmd\\server (or: scripts\\build-cliproxyapi.ps1)." +} +if (-not (Test-Path -LiteralPath $configPath)) { + throw "Config not found: $configPath" +} + +function Get-ConfigPort([string]$Path) { + try { + $line = Get-Content -LiteralPath $Path | Where-Object { $_ -match '^\s*port:\s*\d+\s*$' } | Select-Object -First 1 + if ($line -match '(\d+)') { return [int]$Matches[1] } + } catch {} + return 8318 +} + +$port = Get-ConfigPort $configPath +$existing = Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1 +if ($existing) { + Write-Warning "Port $port is already in use (PID $($existing.OwningProcess))." + Write-Host "If this is CLIProxyAPI, run: powershell -NoProfile -ExecutionPolicy Bypass -File .\\scripts\\restart-cliproxy.ps1" + return +} + +Write-Host "Starting CLIProxyAPI..." +Write-Host " exe: $exePath" +Write-Host " config: $configPath" +Write-Host " logs: $logsDir" + +Start-Process -FilePath $exePath ` + -ArgumentList @("-config", $configPath) ` + -WorkingDirectory $repoRoot ` + -WindowStyle Hidden ` + -RedirectStandardOutput $stdoutLog ` + -RedirectStandardError $stderrLog | Out-Null + +Write-Host "Started. Tail logs:" +Write-Host " Get-Content -Wait $stdoutLog" diff --git a/scripts/windows/stop-cliproxy.ps1 b/scripts/windows/stop-cliproxy.ps1 new file mode 100644 index 00000000..5b5f19d5 --- /dev/null +++ b/scripts/windows/stop-cliproxy.ps1 @@ -0,0 +1,30 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$procNames = @("cliproxyapi", "cliproxyapi-latest") +$procs = @() +foreach ($name in $procNames) { + $procs += @(Get-Process -Name $name -ErrorAction SilentlyContinue) +} + +if (-not $procs) { + Write-Host "No running CLIProxyAPI process found." + exit 0 +} + +$hadError = $false +foreach ($proc in $procs) { + $procId = $proc.Id + Write-Host "Stopping $($proc.ProcessName) (PID $procId)" + try { + Stop-Process -Id $procId -Force -ErrorAction Stop + } catch { + $hadError = $true + Write-Warning "Failed to stop PID ${procId}: $($_.Exception.Message)" + Write-Warning "If CLIProxyAPI was started elevated (e.g. via a 'HighestAvailable' scheduled task), run this script from an elevated PowerShell or stop it via Task Manager (Run as administrator)." + } +} + +if ($hadError) { + throw "Failed to stop one or more CLIProxyAPI processes." +} diff --git a/scripts/windows/uninstall-cliproxyapi-startup-run.ps1 b/scripts/windows/uninstall-cliproxyapi-startup-run.ps1 new file mode 100644 index 00000000..4901fa93 --- /dev/null +++ b/scripts/windows/uninstall-cliproxyapi-startup-run.ps1 @@ -0,0 +1,8 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$valueName = "CLIProxyAPI" + +Write-Host "Removing HKCU Run entry '$valueName'..." +Remove-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Name $valueName -ErrorAction SilentlyContinue +Write-Host "Done." diff --git a/scripts/windows/uninstall-cliproxyapi-startup-task.ps1 b/scripts/windows/uninstall-cliproxyapi-startup-task.ps1 new file mode 100644 index 00000000..861becbd --- /dev/null +++ b/scripts/windows/uninstall-cliproxyapi-startup-task.ps1 @@ -0,0 +1,23 @@ +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +$taskName = "CLIProxyAPI" + +Write-Host "Deleting scheduled task '$taskName'..." + +try { + if (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue) { + Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop + Write-Host "Done." + exit 0 + } +} catch { + Write-Warning "Unregister-ScheduledTask failed: $($_.Exception.Message)" + Write-Host "Falling back to schtasks.exe..." +} + +& schtasks.exe /Delete /TN $taskName /F | Out-Null +if ($LASTEXITCODE -ne 0) { + throw "schtasks.exe failed with exit code $LASTEXITCODE" +} +Write-Host "Done."