diff --git a/scripts/README.md b/scripts/README.md index 44ba294d..7c28c606 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -13,13 +13,38 @@ This will: ## 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)` diff --git a/scripts/build-cliproxyapi.ps1 b/scripts/build-cliproxyapi.ps1 new file mode 100644 index 00000000..0bd75249 --- /dev/null +++ b/scripts/build-cliproxyapi.ps1 @@ -0,0 +1,27 @@ +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/install-cliproxyapi-startup-run.ps1 b/scripts/install-cliproxyapi-startup-run.ps1 new file mode 100644 index 00000000..b7ed9d0a --- /dev/null +++ b/scripts/install-cliproxyapi-startup-run.ps1 @@ -0,0 +1,22 @@ +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/install-cliproxyapi-startup-task.ps1 b/scripts/install-cliproxyapi-startup-task.ps1 new file mode 100644 index 00000000..ab49f14d --- /dev/null +++ b/scripts/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/restart-cliproxy.ps1 b/scripts/restart-cliproxy.ps1 new file mode 100644 index 00000000..156c5eb0 --- /dev/null +++ b/scripts/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/run-cliproxyapi-hidden.vbs b/scripts/run-cliproxyapi-hidden.vbs new file mode 100644 index 00000000..19cfa940 --- /dev/null +++ b/scripts/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/start-cliproxy.ps1 b/scripts/start-cliproxy.ps1 index c88d2f34..255e5288 100644 --- a/scripts/start-cliproxy.ps1 +++ b/scripts/start-cliproxy.ps1 @@ -12,7 +12,9 @@ function Ensure-Dir([string]$Path) { } $repoRoot = Get-RepoRoot -$exePath = Join-Path $repoRoot "bin\\cliproxyapi.exe" +$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 @@ -21,12 +23,28 @@ $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. Run scripts\\setup-droid-cliproxy.ps1 first (or build it with: go build -o bin\\cliproxyapi.exe .\\cmd\\server)." + 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" @@ -41,4 +59,3 @@ Start-Process -FilePath $exePath ` Write-Host "Started. Tail logs:" Write-Host " Get-Content -Wait $stdoutLog" - diff --git a/scripts/stop-cliproxy.ps1 b/scripts/stop-cliproxy.ps1 index 540bc5c8..5b5f19d5 100644 --- a/scripts/stop-cliproxy.ps1 +++ b/scripts/stop-cliproxy.ps1 @@ -1,16 +1,30 @@ Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" -$exeName = "cliproxyapi" -$procs = Get-Process -Name $exeName -ErrorAction SilentlyContinue +$procNames = @("cliproxyapi", "cliproxyapi-latest") +$procs = @() +foreach ($name in $procNames) { + $procs += @(Get-Process -Name $name -ErrorAction SilentlyContinue) +} if (-not $procs) { - Write-Host "No running $exeName process found." + Write-Host "No running CLIProxyAPI process found." exit 0 } -$procs | ForEach-Object { - Write-Host "Stopping $exeName (PID $($_.Id))" - Stop-Process -Id $_.Id -Force +$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/uninstall-cliproxyapi-startup-run.ps1 b/scripts/uninstall-cliproxyapi-startup-run.ps1 new file mode 100644 index 00000000..676c344d --- /dev/null +++ b/scripts/uninstall-cliproxyapi-startup-run.ps1 @@ -0,0 +1,9 @@ +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/uninstall-cliproxyapi-startup-task.ps1 b/scripts/uninstall-cliproxyapi-startup-task.ps1 new file mode 100644 index 00000000..861becbd --- /dev/null +++ b/scripts/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."