-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcopilot_here.ps1
More file actions
488 lines (419 loc) · 18.9 KB
/
copilot_here.ps1
File metadata and controls
488 lines (419 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# copilot_here PowerShell functions
# Version: 2026.04.20
# Repository: https://github.com/GordonBeeming/copilot_here
# Set console output encoding to UTF-8 for Unicode character support
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# Configuration
$script:CopilotHereHome = if ($env:USERPROFILE) {
$env:USERPROFILE
} elseif ($env:HOME) {
$env:HOME
} else {
[Environment]::GetFolderPath('UserProfile')
}
$script:CopilotHereScriptPath = Join-Path $script:CopilotHereHome ".copilot_here.ps1"
$script:DefaultCopilotHereBinDir = Join-Path (Join-Path $script:CopilotHereHome ".local") "bin"
# Detect OS: Windows has USERPROFILE, Linux/macOS have HOME but not USERPROFILE
$script:DefaultCopilotHereBinName = if ($env:USERPROFILE) { "copilot_here.exe" } else { "copilot_here" }
$script:DefaultCopilotHereBin = Join-Path $script:DefaultCopilotHereBinDir $script:DefaultCopilotHereBinName
$script:CopilotHereBin = if ($env:COPILOT_HERE_BIN) { $env:COPILOT_HERE_BIN } else { $script:DefaultCopilotHereBin }
$script:CopilotHereReleaseUrl = "https://github.com/GordonBeeming/copilot_here/releases/download/cli-latest"
$script:CopilotHereVersion = "2026.04.20"
# Debug logging function
function Write-CopilotDebug {
param([string]$Message)
if ($env:COPILOT_HERE_DEBUG -eq "1" -or $env:COPILOT_HERE_DEBUG -eq "true") {
Write-Host "[DEBUG] $Message" -ForegroundColor DarkGray
}
}
# Helper function to stop running containers with confirmation
function Stop-CopilotContainers {
$runningContainers = docker ps --filter "name=copilot_here-" -q 2>&1 | Out-Null; if ($LASTEXITCODE -eq 0) { docker ps --filter "name=copilot_here-" -q }
if ($runningContainers) {
Write-Host "[WARNING] copilot_here is currently running in Docker" -ForegroundColor Yellow
$response = Read-Host " Stop running containers to continue? [y/N]"
if ($response -match '^[yY]') {
Write-Host "[STOP] Stopping copilot_here containers..."
docker stop $runningContainers 2>&1 | Out-Null
Write-Host " [OK] Stopped"
return $true
} else {
Write-Host "[ERROR] Cannot update while containers are running (binary is in use)" -ForegroundColor Red
return $false
}
}
return $true
}
# Helper function to download and install binary
function Download-CopilotHereBinary {
# Detect architecture using environment variable (works in all PowerShell versions)
$procArch = $env:PROCESSOR_ARCHITECTURE
$arch = if ($procArch -eq "ARM64" -or $procArch -eq "ARM") {
"arm64"
} elseif ($procArch -eq "AMD64" -or $procArch -eq "x64") {
"x64"
} else {
"x64" # Default fallback
}
# Create bin directory
$binDir = Split-Path $script:CopilotHereBin
if (-not (Test-Path $binDir)) {
New-Item -ItemType Directory -Path $binDir -Force | Out-Null
}
# Detect OS: Windows has USERPROFILE, macOS has specific uname, Linux is the rest
$os = if ($env:USERPROFILE) {
"win"
} else {
# Try to detect macOS with uname command
try {
$unameOutput = & uname 2>&1
if ($LASTEXITCODE -eq 0 -and $unameOutput -eq "Darwin") { "macos" } else { "linux" }
} catch {
"linux"
}
}
$ext = if ($os -eq "win") { "zip" } else { "tar.gz" }
# Download latest release archive
$downloadUrl = "$script:CopilotHereReleaseUrl/copilot_here-${os}-${arch}.${ext}"
$tmpBase = [System.IO.Path]::GetTempFileName()
Remove-Item -Path $tmpBase -ErrorAction SilentlyContinue
$tmpArchive = $tmpBase + ".${ext}"
Write-Host "[DOWNLOAD] Downloading binary from: $downloadUrl"
try {
Invoke-WebRequest -Uri $downloadUrl -OutFile $tmpArchive -UseBasicParsing
} catch {
Remove-Item -Path $tmpArchive -ErrorAction SilentlyContinue
Write-Host "[ERROR] Failed to download binary: $_" -ForegroundColor Red
return $false
}
# Extract binary from archive
try {
if ($env:USERPROFILE) {
# Windows (PowerShell 5.1 or Core)
Expand-Archive -Path $tmpArchive -DestinationPath $binDir -Force
} else {
# Linux/macOS
& tar -xzf $tmpArchive -C $binDir copilot_here
if ($LASTEXITCODE -ne 0) { throw "tar extraction failed" }
& chmod +x $script:CopilotHereBin 2>&1 | Out-Null
}
} catch {
Remove-Item -Path $tmpArchive -ErrorAction SilentlyContinue
Write-Host "[ERROR] Failed to extract binary: $_" -ForegroundColor Red
return $false
}
Remove-Item -Path $tmpArchive -ErrorAction SilentlyContinue
Write-Host "[OK] Binary installed to: $script:CopilotHereBin"
return $true
}
# Helper function to ensure binary is installed
function Ensure-CopilotHereBinary {
if (-not (Test-Path $script:CopilotHereBin)) {
Write-Host "[INSTALL] copilot_here binary not found. Installing..."
return Download-CopilotHereBinary
}
return $true
}
# Helper function to update profile with marker blocks
function Update-ProfileWithMarkers {
param([string]$ProfilePath)
# Create profile directory if needed
$profileDir = Split-Path $ProfilePath
if (-not (Test-Path $profileDir)) {
New-Item -ItemType Directory -Path $profileDir -Force | Out-Null
}
# Create profile if it doesn't exist
if (-not (Test-Path $ProfilePath)) {
New-Item -ItemType File -Path $ProfilePath -Force | Out-Null
}
$markerStart = "# >>> copilot_here >>>"
$markerEnd = "# <<< copilot_here <<<"
$profileContent = Get-Content $ProfilePath -Raw -ErrorAction SilentlyContinue
if ([string]::IsNullOrEmpty($profileContent)) {
$profileContent = ""
}
# Remove old marker block and rebuild fresh
if ($profileContent.Contains($markerStart)) {
$startIndex = $profileContent.IndexOf($markerStart)
$endIndex = $profileContent.IndexOf($markerEnd, $startIndex)
if ($endIndex -gt $startIndex) {
$endIndex += $markerEnd.Length
$beforeBlock = $profileContent.Substring(0, $startIndex)
$afterBlock = if ($endIndex -lt $profileContent.Length) { $profileContent.Substring($endIndex) } else { "" }
# Remove rogue entries
$beforeBlock = $beforeBlock -replace '(?m)^.*copilot_here\.ps1.*$[\r\n]*', ''
$afterBlock = $afterBlock -replace '(?m)^.*copilot_here\.ps1.*$[\r\n]*', ''
$profileContent = $beforeBlock.TrimEnd()
} else {
# Malformed markers
$profileContent = $profileContent -replace '(?m)^.*copilot_here.*$[\r\n]*', ''
$profileContent = $profileContent.TrimEnd()
}
} else {
# No markers - remove rogue entries
$profileContent = $profileContent -replace '(?m)^.*copilot_here\.ps1.*$[\r\n]*', ''
$profileContent = $profileContent.TrimEnd()
}
# Add fresh marker block
$scriptPath = $script:CopilotHereScriptPath
$scriptPathEscaped = $scriptPath.Replace("'", "''")
$markerStart = "# >>> copilot_here >>>"
$markerEnd = "# <<< copilot_here <<<"
$block = "`n`n$markerStart`nif (Test-Path '$scriptPathEscaped') {`n . '$scriptPathEscaped'`n}`n$markerEnd`n"
$profileContent = $profileContent + $block
# Resolve symlink target to preserve symlinks (e.g. GNU Stow)
# Use PS 5.1-compatible null handling (no ?. or ?? operators)
$resolved = Resolve-Path $ProfilePath -ErrorAction SilentlyContinue
if ($resolved) { $resolvedPath = $resolved.Path } else { $resolvedPath = $ProfilePath }
# Explicitly use UTF-8 with BOM to match Set-Content default encoding
[System.IO.File]::WriteAllText($resolvedPath, $profileContent.TrimStart(), [System.Text.Encoding]::UTF8)
Write-Host " [OK] $(Split-Path $ProfilePath -Leaf)" -ForegroundColor Gray
}
# Update function - downloads fresh binary and script
function Update-CopilotHere {
Write-Host "[RELOAD] Updating copilot_here..."
# Check and stop running containers
if (-not (Stop-CopilotContainers)) {
return $false
}
# Remove existing binary
if (Test-Path $script:CopilotHereBin) {
Remove-Item -Path $script:CopilotHereBin -Force
}
# Download fresh binary
Write-Host ""
Write-Host "[INSTALL] Downloading latest binary..."
if (-not (Download-CopilotHereBinary)) {
Write-Host "[ERROR] Failed to download binary" -ForegroundColor Red
return $false
}
# Download and persist fresh PowerShell script
Write-Host ""
Write-Host "[INSTALL] Downloading latest PowerShell script..."
try {
# GitHub release assets may come back as bytes; using -OutFile prevents Set-Content writing byte values line-by-line
Invoke-WebRequest -Uri "$script:CopilotHereReleaseUrl/copilot_here.ps1" -UseBasicParsing -OutFile $script:CopilotHereScriptPath
# Update PowerShell profiles with marker blocks
Write-Host ""
Write-Host "[PROFILE] Updating PowerShell profiles..."
$pwshProfile = "$env:USERPROFILE\Documents\PowerShell\Microsoft.PowerShell_profile.ps1"
Update-ProfileWithMarkers -ProfilePath $pwshProfile
$winPsProfile = "$env:USERPROFILE\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
Update-ProfileWithMarkers -ProfilePath $winPsProfile
Write-Host "[OK] Profiles updated"
Write-Host "[OK] Update complete! Reloading PowerShell functions..."
$null = . $script:CopilotHereScriptPath
Write-Host ""
Write-Host "[VERSION] Script: $script:CopilotHereVersion" -ForegroundColor Cyan
try {
$binVersion = (& $script:CopilotHereBin --version) | Select-Object -First 1
if ($binVersion) {
Write-Host "[VERSION] Binary: $binVersion" -ForegroundColor Cyan
}
} catch { }
Write-Host ""
} catch {
Write-Host ""
Write-Host "[OK] Binary updated!"
Write-Host ""
Write-Host "[WARNING] Could not auto-update PowerShell script/profiles. Please re-import manually:" -ForegroundColor Yellow
Write-Host " iex (iwr -UseBasicParsing $script:CopilotHereReleaseUrl/copilot_here.ps1).Content" -ForegroundColor Yellow
Write-Host ""
Write-Host " Or restart your terminal." -ForegroundColor Yellow
}
return $true
}
# Reset function - same as update (kept for backwards compatibility)
function Reset-CopilotHere {
Update-CopilotHere
}
# Check for updates (called at startup)
function Test-CopilotHereUpdates {
try {
# Fetch remote script with 2 second timeout
$ProgressPreference = 'SilentlyContinue'
$remoteScript = (Invoke-WebRequest -Uri "$script:CopilotHereReleaseUrl/copilot_here.ps1" -UseBasicParsing -TimeoutSec 2).Content
# Extract version from remote script
$remoteVersion = $null
if ($remoteScript -match '\$script:CopilotHereVersion\s*=\s*"(.+?)"') {
$remoteVersion = $matches[1]
}
if (-not $remoteVersion) {
return $false # Couldn't parse version
}
if ($script:CopilotHereVersion -ne $remoteVersion) {
# Compare versions - convert to comparable format
$currentParts = $script:CopilotHereVersion.Split('.')
$remoteParts = $remoteVersion.Split('.')
# Pad arrays to same length
$maxLen = [Math]::Max($currentParts.Length, $remoteParts.Length)
while ($currentParts.Length -lt $maxLen) { $currentParts += "0" }
while ($remoteParts.Length -lt $maxLen) { $remoteParts += "0" }
# Compare each part
$isNewer = $false
for ($i = 0; $i -lt $maxLen; $i++) {
$currentNum = [int]$currentParts[$i]
$remoteNum = [int]$remoteParts[$i]
if ($remoteNum -gt $currentNum) {
$isNewer = $true
break
} elseif ($remoteNum -lt $currentNum) {
break
}
}
if ($isNewer) {
Write-Host "[UPDATE] Update available: $script:CopilotHereVersion -> $remoteVersion"
$confirmation = Read-Host "Would you like to update now? [y/N]"
if ($confirmation -match '^[yY]') {
Update-CopilotHere
return $true # Signal that update was performed
}
}
}
} catch {
# Failed to check or offline - continue normally
}
return $false
}
# Check if argument is an update command
function Test-UpdateArg {
param([string]$Arg)
$updateArgs = @("--update", "-u", "--upgrade", "--update-scripts", "--upgrade-scripts")
return $updateArgs -contains $Arg
}
# Check if argument is a reset command
function Test-ResetArg {
param([string]$Arg)
$resetArgs = @("--reset")
return $resetArgs -contains $Arg
}
# Safe Mode: Asks for confirmation before executing
function copilot_here {
$Arguments = @($args)
Write-CopilotDebug "=== copilot_here called with args: $Arguments"
# Check if script file version differs from in-memory version
$scriptPath = $script:CopilotHereScriptPath
if (Test-Path $scriptPath) {
try {
$fileContent = Get-Content $scriptPath -Raw -ErrorAction SilentlyContinue
if ($fileContent -match '\$script:CopilotHereVersion\s*=\s*"(.+?)"') {
$fileVersion = $matches[1]
if ($fileVersion -and $fileVersion -ne $script:CopilotHereVersion) {
$currentParts = $script:CopilotHereVersion.Split('.')
$fileParts = $fileVersion.Split('.')
$maxLen = [Math]::Max($currentParts.Length, $fileParts.Length)
while ($currentParts.Length -lt $maxLen) { $currentParts += "0" }
while ($fileParts.Length -lt $maxLen) { $fileParts += "0" }
$isNewer = $false
for ($i = 0; $i -lt $maxLen; $i++) {
$currentNum = [int]$currentParts[$i]
$fileNum = [int]$fileParts[$i]
if ($fileNum -gt $currentNum) {
$isNewer = $true
break
} elseif ($fileNum -lt $currentNum) {
break
}
}
if ($isNewer) {
Write-CopilotDebug "Newer on-disk script detected: in-memory=$script:CopilotHereVersion, file=$fileVersion"
Write-Host "[RELOAD] Detected updated shell script (v$fileVersion), reloading..."
. $scriptPath
copilot_here @Arguments
return
}
}
}
} catch {
# Ignore errors reading file
}
}
# Handle --update before binary check
if ($Arguments | Where-Object { Test-UpdateArg $_ } | Select-Object -First 1) {
Write-CopilotDebug "Update argument detected"
Update-CopilotHere
return
}
# Handle --reset before binary check
if ($Arguments | Where-Object { Test-ResetArg $_ } | Select-Object -First 1) {
Write-CopilotDebug "Reset argument detected"
Reset-CopilotHere
return
}
# Check for updates at startup
Write-CopilotDebug "Checking for updates..."
if (Test-CopilotHereUpdates) { return }
Write-CopilotDebug "Ensuring binary is installed..."
if (-not (Ensure-CopilotHereBinary)) { return }
Write-CopilotDebug "Executing binary: $script:CopilotHereBin $Arguments"
& $script:CopilotHereBin @Arguments
$exitCode = $LASTEXITCODE
Write-CopilotDebug "Binary exited with code: $exitCode"
$global:LASTEXITCODE = $exitCode
return $exitCode
}
# YOLO Mode: Auto-approves all tool usage
function copilot_yolo {
$Arguments = @($args)
Write-CopilotDebug "=== copilot_yolo called with args: $Arguments"
# Check if script file version differs from in-memory version
$scriptPath = $script:CopilotHereScriptPath
if (Test-Path $scriptPath) {
try {
$fileContent = Get-Content $scriptPath -Raw -ErrorAction SilentlyContinue
if ($fileContent -match '\$script:CopilotHereVersion\s*=\s*"(.+?)"') {
$fileVersion = $matches[1]
if ($fileVersion -and $fileVersion -ne $script:CopilotHereVersion) {
$currentParts = $script:CopilotHereVersion.Split('.')
$fileParts = $fileVersion.Split('.')
$maxLen = [Math]::Max($currentParts.Length, $fileParts.Length)
while ($currentParts.Length -lt $maxLen) { $currentParts += "0" }
while ($fileParts.Length -lt $maxLen) { $fileParts += "0" }
$isNewer = $false
for ($i = 0; $i -lt $maxLen; $i++) {
$currentNum = [int]$currentParts[$i]
$fileNum = [int]$fileParts[$i]
if ($fileNum -gt $currentNum) {
$isNewer = $true
break
} elseif ($fileNum -lt $currentNum) {
break
}
}
if ($isNewer) {
Write-CopilotDebug "Newer on-disk script detected: in-memory=$script:CopilotHereVersion, file=$fileVersion"
Write-Host "[RELOAD] Detected updated shell script (v$fileVersion), reloading..."
. $scriptPath
copilot_yolo @Arguments
return
}
}
}
} catch {
# Ignore errors reading file
}
}
# Handle --update before binary check
if ($Arguments | Where-Object { Test-UpdateArg $_ } | Select-Object -First 1) {
Write-CopilotDebug "Update argument detected"
Update-CopilotHere
return
}
# Handle --reset before binary check
if ($Arguments | Where-Object { Test-ResetArg $_ } | Select-Object -First 1) {
Write-CopilotDebug "Reset argument detected"
Reset-CopilotHere
return
}
# Check for updates at startup
Write-CopilotDebug "Checking for updates..."
if (Test-CopilotHereUpdates) { return }
Write-CopilotDebug "Ensuring binary is installed..."
if (-not (Ensure-CopilotHereBinary)) { return }
Write-CopilotDebug "Executing binary in YOLO mode: $script:CopilotHereBin --yolo $Arguments"
& $script:CopilotHereBin --yolo @Arguments
$exitCode = $LASTEXITCODE
Write-CopilotDebug "Binary exited with code: $exitCode"
$global:LASTEXITCODE = $exitCode
return $exitCode
}