-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
1042 lines (951 loc) · 47.1 KB
/
Copy pathinstall.ps1
File metadata and controls
1042 lines (951 loc) · 47.1 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# RAPP Brainstem Installer for Windows
# Usage: irm https://raw.githubusercontent.com/kody-w/rapp-installer/main/install.ps1 | iex
#
# Works on a factory Windows 11 install — auto-installs Python, Git, and GitHub CLI via winget.
$ErrorActionPreference = "Stop"
# Force TLS 1.2 for every web request in this session. Stock Windows PowerShell 5.1
# on older builds negotiates TLS 1.0 by default, which GitHub and raw.githubusercontent
# now refuse — the download would fail with an opaque "could not create SSL/TLS secure
# channel". Additive and harmless where 1.2 is already the default.
try {
[Net.ServicePointManager]::SecurityProtocol = `
[Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
} catch {}
$BRAINSTEM_HOME = "$env:USERPROFILE\.brainstem"
$BRAINSTEM_BIN = "$env:USERPROFILE\.local\bin"
$REPO_URL = "https://github.com/kody-w/rapp-installer.git"
$REMOTE_VERSION_URL = "https://raw.githubusercontent.com/kody-w/rapp-installer/main/rapp_brainstem/VERSION"
$VENV_DIR = "$env:USERPROFILE\.brainstem\venv"
# Optional version pin: `--version vX.Y.Z` (also accepts a bare 0.6.14 or the release
# tag form brainstem-v0.6.14). Parsed from the script arguments so a user can pin or
# RC-test a specific release on Windows, e.g.
# & ([scriptblock]::Create((irm https://.../install.ps1))) --version v0.6.14
$PIN_VERSION = ""
$argList = @($args)
for ($i = 0; $i -lt $argList.Count; $i++) {
if ($argList[$i] -eq "--version" -and ($i + 1) -lt $argList.Count) {
$PIN_VERSION = [string]$argList[$i + 1]
$i++
}
}
function Print-Banner {
Write-Host ""
Write-Host " 🧠 RAPP Brainstem" -ForegroundColor Cyan
Write-Host " Local-first AI agent server" -ForegroundColor Gray
Write-Host " Powered by GitHub Copilot — no API keys needed" -ForegroundColor Gray
Write-Host ""
}
function Compare-SemVer {
param([string]$Local, [string]$Remote)
$lParts = $Local.Split('.')
$rParts = $Remote.Split('.')
for ($i = 0; $i -lt [Math]::Max($lParts.Length, $rParts.Length); $i++) {
$lv = if ($i -lt $lParts.Length) { [int]$lParts[$i] } else { 0 }
$rv = if ($i -lt $rParts.Length) { [int]$rParts[$i] } else { 0 }
if ($rv -gt $lv) { return 1 } # remote is newer
if ($rv -lt $lv) { return -1 } # local is newer
}
return 0 # equal
}
function Check-ForUpgrade {
$versionFile = "$BRAINSTEM_HOME\src\rapp_brainstem\VERSION"
if (-not (Test-Path $versionFile)) { return $true }
$localVersion = (Get-Content $versionFile -Raw).Trim()
try {
$remoteVersion = (Invoke-WebRequest -Uri $REMOTE_VERSION_URL -UseBasicParsing -TimeoutSec 10).Content.Trim()
} catch {
Write-Host " [!] Could not check remote version — upgrading anyway" -ForegroundColor Yellow
return $true
}
Write-Host " Local version: $localVersion" -ForegroundColor Cyan
Write-Host " Remote version: $remoteVersion" -ForegroundColor Cyan
if ($localVersion -eq $remoteVersion) {
Write-Host ""
Write-Host " [OK] Already up to date (v$localVersion)" -ForegroundColor Green
Write-Host ""
return $false
}
$cmp = Compare-SemVer -Local $localVersion -Remote $remoteVersion
if ($cmp -eq 1) {
Write-Host " [..] Upgrade available: $localVersion -> $remoteVersion" -ForegroundColor Yellow
return $true
}
Write-Host ""
Write-Host " [OK] Already up to date (v$localVersion)" -ForegroundColor Green
Write-Host ""
return $false
}
function Install-WithWinget {
param([string]$PackageId, [string]$Name)
Write-Host " [..] Installing $Name via winget..." -ForegroundColor Yellow
winget install --id $PackageId --accept-source-agreements --accept-package-agreements --silent 2>&1 | Out-Null
# Refresh PATH for this session
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
}
function Resolve-PythonExe {
# Return a real Python 3 executable. Prefer the one Check-Prerequisites already
# validated ($script:PythonExe); otherwise probe — this matters on the
# "already up to date" fast path, which skips Check-Prerequisites and would
# otherwise fall back to a bare "python" that may be the Windows Store alias
# stub (it prints "Python was not found" and opens the Store instead of running).
if ($script:PythonExe) { return $script:PythonExe }
foreach ($cmd in @("python3", "python")) {
try {
$out = & $cmd --version 2>&1
if ($LASTEXITCODE -eq 0 -and $out -match "Python 3\.(\d+)") {
$script:PythonExe = $cmd
return $cmd
}
} catch {}
}
$direct = "$env:LOCALAPPDATA\Programs\Python\Python311\python.exe"
if (Test-Path $direct) { $script:PythonExe = $direct; return $direct }
return "python"
}
function Get-VenvPython {
# Path to the venv interpreter (Windows layout: venv\Scripts\python.exe).
return "$VENV_DIR\Scripts\python.exe"
}
function Resolve-RunPython {
# The interpreter used to install deps, check deps, and launch the server: the
# venv python when it exists (issue #29 — install and launch must resolve the
# SAME interpreter), otherwise the system python as a safe fallback.
$venvPy = Get-VenvPython
if (Test-Path $venvPy) { return $venvPy }
return (Resolve-PythonExe)
}
function Test-PipWorks {
param([string]$Py)
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& $Py -m pip --version 2>&1 | Out-Null
return ($LASTEXITCODE -eq 0)
} catch {
return $false
} finally {
$ErrorActionPreference = $prev
}
}
function Ensure-Pip {
# A found Python is NOT guaranteed to have pip. Corp-managed images and
# stripped/partial installs ship a working python.exe with no pip module —
# seen in the wild on a fresh Windows 11 machine: every pip call printed
# "No module named pip", then the server died at `import requests` behind a
# dead localhost:7071 browser tab. Bootstrap order: ensurepip (stdlib,
# works offline, restores the pip bundled with Python) -> get-pip.py (network).
# Returns $true only when `python -m pip` actually works.
$py = Resolve-PythonExe
if (Test-PipWorks $py) { return $true }
Write-Host " [..] Python has no pip — bootstrapping via ensurepip..." -ForegroundColor Yellow
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
# Write-Host, not bare pipeline output: Ensure-Pip's return value is its
# pipeline — stray tool output here would corrupt the caller's boolean.
& $py -m ensurepip --upgrade --default-pip 2>&1 | ForEach-Object { Write-Host "$_" }
} catch {
} finally {
$ErrorActionPreference = $prev
}
if (Test-PipWorks $py) {
Write-Host " [OK] pip bootstrapped via ensurepip" -ForegroundColor Green
return $true
}
Write-Host " [..] ensurepip unavailable — fetching get-pip.py..." -ForegroundColor Yellow
$getPip = Join-Path $env:TEMP "rapp-get-pip.py"
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
Invoke-WebRequest -Uri "https://bootstrap.pypa.io/get-pip.py" -OutFile $getPip -UseBasicParsing -TimeoutSec 120
& $py $getPip 2>&1 | ForEach-Object { Write-Host "$_" }
} catch {
} finally {
$ErrorActionPreference = $prev
Remove-Item $getPip -Force -ErrorAction SilentlyContinue
}
if (Test-PipWorks $py) {
Write-Host " [OK] pip bootstrapped via get-pip.py" -ForegroundColor Green
return $true
}
Write-Host " [X] Python at '$py' has no pip and it could not be bootstrapped." -ForegroundColor Red
Write-Host " Fix it manually, then re-run this installer:" -ForegroundColor Yellow
Write-Host " `"$py`" -m ensurepip --upgrade --default-pip" -ForegroundColor Cyan
Write-Host " Or reinstall Python from https://python.org with 'pip' checked." -ForegroundColor Yellow
return $false
}
function Setup-Venv {
# Create ~/.brainstem/venv so dependencies are isolated from system/user Python
# and the launcher always resolves the SAME interpreter that install used
# (issue #29). Idempotent: a healthy existing venv is reused; a broken one is
# recreated. Mirrors install.sh's setup_venv.
$venvPy = Get-VenvPython
if (Test-Path $venvPy) {
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
& $venvPy -c "import sys" 2>&1 | Out-Null
$ok = ($LASTEXITCODE -eq 0)
$ErrorActionPreference = $prev
if ($ok) {
Write-Host " [OK] Virtual environment OK" -ForegroundColor Green
return
}
Write-Host " [..] Virtual environment broken — recreating..." -ForegroundColor Yellow
Remove-Item -Recurse -Force $VENV_DIR -ErrorAction SilentlyContinue
}
$sysPy = Resolve-PythonExe
Write-Host " Creating virtual environment..."
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
& $sysPy -m venv $VENV_DIR 2>&1 | Out-Null
if (-not (Test-Path (Get-VenvPython))) {
# Some minimal Python installs need ensurepip primed before venv works.
& $sysPy -m ensurepip --upgrade 2>&1 | Out-Null
& $sysPy -m venv $VENV_DIR 2>&1 | Out-Null
}
$ErrorActionPreference = $prev
if (-not (Test-Path (Get-VenvPython))) {
Write-Host " [X] Failed to create virtual environment at $VENV_DIR" -ForegroundColor Red
throw "venv creation failed"
}
# Upgrade pip inside the venv (best-effort; venv already ships pip).
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
& (Get-VenvPython) -m pip install --upgrade pip 2>&1 | Out-Null
$ErrorActionPreference = $prev
Write-Host " [OK] Virtual environment ready" -ForegroundColor Green
}
function Check-Prerequisites {
Write-Host "Checking prerequisites..."
# winget (ships with Windows 11)
try {
winget --version 2>&1 | Out-Null
} catch {
Write-Host " [X] winget not found — this installer requires Windows 10 1709+ or Windows 11" -ForegroundColor Red
throw "winget not found"
}
# Git
$gitOk = $false
try {
$gitVersion = git --version 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [OK] $gitVersion" -ForegroundColor Green
$gitOk = $true
}
} catch {}
if (-not $gitOk) {
Install-WithWinget "Git.Git" "Git"
try {
git --version 2>&1 | Out-Null
Write-Host " [OK] Git installed" -ForegroundColor Green
} catch {
Write-Host " [X] Git install failed — install manually from https://git-scm.com" -ForegroundColor Red
throw "Git install failed"
}
}
# Python 3.11+
$pythonOk = $false
$pythonCmd = $null
# Try multiple python command names (python3 first on some systems, then python)
foreach ($cmd in @("python3", "python")) {
try {
$out = & $cmd --version 2>&1
if ($LASTEXITCODE -eq 0 -and $out -match "Python 3\.(\d+)") {
$minor = [int]$Matches[1]
if ($minor -ge 11) {
Write-Host " [OK] $out" -ForegroundColor Green
$pythonOk = $true
$pythonCmd = $cmd
break
}
}
} catch {}
}
if (-not $pythonOk) {
# Disable Windows App Execution Aliases that shadow real python
# These stubs print "Python was not found" and prevent detection
$aliasDir = "$env:LOCALAPPDATA\Microsoft\WindowsApps"
foreach ($stub in @("python.exe", "python3.exe")) {
$stubPath = Join-Path $aliasDir $stub
if (Test-Path $stubPath) {
try {
$target = (Get-Item $stubPath).Target
if (-not $target) {
# It's an App Execution Alias stub — rename it out of the way
Rename-Item $stubPath "$stub.disabled" -ErrorAction SilentlyContinue
Write-Host " [..] Disabled Windows Store python stub" -ForegroundColor Yellow
}
} catch {}
}
}
Install-WithWinget "Python.Python.3.11" "Python 3.11"
# winget installs to a known path — add it explicitly
$pyBase = "$env:LOCALAPPDATA\Programs\Python\Python311"
if (Test-Path $pyBase) {
$env:Path = "$pyBase;$pyBase\Scripts;$env:Path"
}
# Also refresh from registry
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
# Verify the REAL python is now reachable
$pythonOk = $false
foreach ($cmd in @("python3", "python")) {
try {
$out = & $cmd --version 2>&1
if ($LASTEXITCODE -eq 0 -and $out -match "Python 3\.(\d+)") {
Write-Host " [OK] $out installed" -ForegroundColor Green
$pythonOk = $true
$pythonCmd = $cmd
break
}
} catch {}
}
# Last resort: try the known install path directly
if (-not $pythonOk) {
$directPy = "$env:LOCALAPPDATA\Programs\Python\Python311\python.exe"
if (Test-Path $directPy) {
$out = & $directPy --version 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " [OK] $out installed (direct path)" -ForegroundColor Green
$pythonOk = $true
$pythonCmd = $directPy
}
}
}
if (-not $pythonOk) {
Write-Host " [X] Python install failed — install from https://python.org" -ForegroundColor Red
Write-Host " Make sure to check 'Add Python to PATH' during install" -ForegroundColor Yellow
throw "Python 3.11+ install failed"
}
}
# Store the working python command for later use
$script:PythonExe = $pythonCmd
# GitHub CLI (optional but recommended)
try {
gh --version 2>&1 | Out-Null
Write-Host " [OK] GitHub CLI installed" -ForegroundColor Green
} catch {
Write-Host " [..] Installing GitHub CLI..." -ForegroundColor Yellow
Install-WithWinget "GitHub.cli" "GitHub CLI"
try {
gh --version 2>&1 | Out-Null
Write-Host " [OK] GitHub CLI installed" -ForegroundColor Green
} catch {
Write-Host " [!] GitHub CLI not installed (optional — you can authenticate later)" -ForegroundColor Yellow
}
}
}
# ── soul refresh on upgrade (issue #40) ──────────────────────────────────────────
# Normalized SHA-256 of a soul.md, computed IDENTICALLY to rapp_brainstem/tests/soul_hash.py
# so the shipped soul_defaults.sha256 manifest works for both installers. Normalize:
# strip a UTF-8 BOM, CRLF->LF, strip trailing space/tab per line, exactly one trailing
# newline; then Get-FileHash a UTF-8 (no BOM) temp copy. Returns lowercase hex, or $null
# if the file cannot be read/decoded (the caller then preserves the soul untouched).
function Get-NormalizedSoulHash {
param([string]$Path)
try {
# ReadAllText(UTF8) auto-detects and strips a UTF-8 BOM, matching soul_hash.py.
$text = [System.IO.File]::ReadAllText($Path, [System.Text.Encoding]::UTF8)
} catch { return $null }
$text = $text.Replace("`r`n", "`n").Replace("`r", "`n")
$lines = $text.Split([char]10)
for ($i = 0; $i -lt $lines.Length; $i++) {
$lines[$i] = $lines[$i].TrimEnd([char]32, [char]9)
}
$text = [string]::Join([string][char]10, $lines).TrimEnd([char]10) + [string][char]10
$tmp = [System.IO.Path]::GetTempFileName()
try {
[System.IO.File]::WriteAllText($tmp, $text, (New-Object System.Text.UTF8Encoding($false)))
return (Get-FileHash -Path $tmp -Algorithm SHA256).Hash.ToLower()
} catch {
return $null
} finally {
Remove-Item $tmp -Force -ErrorAction SilentlyContinue
}
}
# True if $Hash is the first token of some non-comment line in the manifest.
function Test-SoulHashInManifest {
param([string]$Hash, [string]$ManifestPath)
if (-not $Hash) { return $false }
if (-not (Test-Path $ManifestPath)) { return $false }
foreach ($line in [System.IO.File]::ReadAllLines($ManifestPath)) {
$trimmed = $line.Trim()
if ($trimmed -eq "" -or $trimmed.StartsWith("#")) { continue }
if (($trimmed -split '\s+')[0].ToLower() -eq $Hash.ToLower()) { return $true }
}
return $false
}
function Resolve-PinnedTag {
# Resolve a --version pin against every tag form we ship: the documented v0.6.14
# UX, a bare 0.6.14, and the actual release tag brainstem-v0.6.14. Returns the
# matching git ref, or $null. Assumes the current directory is the repo.
param([string]$Pin)
$bare = $Pin -replace '^v', ''
foreach ($cand in @($Pin, "v$bare", "brainstem-$bare", "brainstem-v$bare")) {
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
git rev-parse $cand 2>&1 | Out-Null
$ok = ($LASTEXITCODE -eq 0)
$ErrorActionPreference = $prev
if ($ok) { return $cand }
}
return $null
}
function Install-Brainstem {
Write-Host ""
Write-Host "Installing RAPP Brainstem..."
if (-not (Test-Path $BRAINSTEM_HOME)) {
New-Item -ItemType Directory -Force -Path $BRAINSTEM_HOME | Out-Null
}
if (Test-Path "$BRAINSTEM_HOME\src\.git") {
# Smart update — preserve soul, agents, config
$LocalVer = "0.0.0"
$VerFile = "$BRAINSTEM_HOME\src\rapp_brainstem\VERSION"
if (Test-Path $VerFile) { $LocalVer = (Get-Content $VerFile -Raw).Trim() }
if ($PIN_VERSION) {
$RemoteVer = ($PIN_VERSION -replace '^v', '')
} else {
try { $RemoteVer = (Invoke-WebRequest -Uri $REMOTE_VERSION_URL -UseBasicParsing -TimeoutSec 5).Content.Trim() } catch { $RemoteVer = "0.0.0" }
}
Write-Host " Local: v$LocalVer"
if ($PIN_VERSION) {
Write-Host " Target: v$RemoteVer (pinned)"
} else {
Write-Host " Remote: v$RemoteVer"
}
if ($LocalVer -eq $RemoteVer) {
Write-Host " [OK] Already up to date (v$LocalVer)" -ForegroundColor Green
} else {
Write-Host " Upgrading v$LocalVer -> v$RemoteVer..."
$Backup = "$env:TEMP\brainstem-upgrade-$(Get-Random)"
New-Item -ItemType Directory -Force -Path $Backup | Out-Null
# Backup user files
$AgentsDir = "$BRAINSTEM_HOME\src\rapp_brainstem\agents"
$SoulFile = "$BRAINSTEM_HOME\src\rapp_brainstem\soul.md"
$EnvFile = "$BRAINSTEM_HOME\src\rapp_brainstem\.env"
if (Test-Path $SoulFile) { Copy-Item $SoulFile "$Backup\soul.md" }
if (Test-Path $EnvFile) { Copy-Item $EnvFile "$Backup\.env" }
if (Test-Path $AgentsDir) { Copy-Item "$AgentsDir\*.py" "$Backup\" -ErrorAction SilentlyContinue }
Write-Host " [OK] Backed up soul, agents, config" -ForegroundColor Green
# Pull latest from THIS installer's repo. A prior install may have cloned from a
# different origin (fork/mirror); repoint origin and hard-reset to it so the upgrade
# is reliable even across unrelated histories. User files (soul, agents, .env) were
# backed up above and are restored below; tokens and .brainstem_data are gitignored.
Push-Location "$BRAINSTEM_HOME\src"
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
git remote set-url origin $REPO_URL 2>&1 | Out-Null
$TagRef = $null
if ($PIN_VERSION) {
# Pin/RC-test: fetch tags and check out the requested release tag
# (accepts v0.6.14 / 0.6.14 / brainstem-v0.6.14 forms like install.sh).
git stash 2>&1 | Out-Null
git fetch --tags --quiet origin 2>&1 | Out-Null
$TagRef = Resolve-PinnedTag $PIN_VERSION
$pullOk = $false
if ($TagRef) {
git checkout --quiet $TagRef 2>&1 | Out-Null
$pullOk = ($LASTEXITCODE -eq 0)
} else {
Write-Host " [X] Version $PIN_VERSION not found. Available versions:" -ForegroundColor Red
git tag -l 'brainstem-v*' 'v*' 2>&1 | Sort-Object | ForEach-Object { Write-Host " $_" }
}
} else {
git fetch --quiet origin main 2>&1 | Out-Null
$pullOk = ($LASTEXITCODE -eq 0)
if ($pullOk) {
git reset --hard --quiet FETCH_HEAD 2>&1 | Out-Null
$pullOk = ($LASTEXITCODE -eq 0)
}
}
$ErrorActionPreference = $prevEAP
Pop-Location
if ($PIN_VERSION -and -not $TagRef) {
throw "pinned version $PIN_VERSION not found"
}
if ($pullOk) {
if ($PIN_VERSION) {
Write-Host " [OK] Checked out $TagRef" -ForegroundColor Green
} else {
Write-Host " [OK] Framework updated" -ForegroundColor Green
}
} else {
Write-Host " [!] Update download failed — keeping existing files (v$LocalVer)" -ForegroundColor Yellow
}
# Restore user files.
# soul.md: refresh it only when the pre-upgrade file was an unmodified
# historical default (issue #40) — its normalized hash is in the manifest
# AND the new default differs; then back the old one up to soul.md.bak-<date>.
# Otherwise (any customization, or anything we cannot hash) preserve it
# byte-for-byte. Fail-safe: preserve, never clobber.
if (Test-Path "$Backup\soul.md") {
$soulRefreshed = $false
if ($pullOk) {
$Manifest = "$BRAINSTEM_HOME\src\rapp_brainstem\tests\soul_defaults.sha256"
$OldHash = Get-NormalizedSoulHash "$Backup\soul.md"
$NewHash = Get-NormalizedSoulHash $SoulFile
if ($OldHash -and $NewHash -and ($OldHash -ne $NewHash) -and (Test-SoulHashInManifest $OldHash $Manifest)) {
$Bak = "$BRAINSTEM_HOME\src\rapp_brainstem\soul.md.bak-$(Get-Date -Format 'yyyyMMdd')"
# Don't clobber an earlier same-day backup (a second refresh on the same date).
if (Test-Path $Bak) {
$bn = 1
while (Test-Path "$Bak-$bn") { $bn++ }
$Bak = "$Bak-$bn"
}
Copy-Item "$Backup\soul.md" $Bak
Write-Host " [OK] Refreshed default soul (yours was an unmodified default); backup at $Bak" -ForegroundColor Green
$soulRefreshed = $true
}
}
if (-not $soulRefreshed) { Copy-Item "$Backup\soul.md" $SoulFile -Force }
}
if (Test-Path "$Backup\.env") { Copy-Item "$Backup\.env" $EnvFile -Force }
# Only restore genuinely user-added agents. Compute the set the repo now
# ships from the fresh checkout and skip-restore anything in it — otherwise
# bundled agents (context_memory, manage_memory, hacker_news) get reverted
# to the backed-up copies on every upgrade (issue #2).
$Shipped = @()
if (Test-Path $AgentsDir) {
$Shipped = @(Get-ChildItem "$AgentsDir\*.py" -ErrorAction SilentlyContinue | ForEach-Object { $_.Name })
}
Get-ChildItem "$Backup\*.py" -ErrorAction SilentlyContinue | ForEach-Object {
if (($_.Name -notin @("basic_agent.py", "__init__.py")) -and ($_.Name -notin $Shipped)) {
Copy-Item $_.FullName "$AgentsDir\$($_.Name)" -Force
}
}
Remove-Item -Recurse -Force $Backup -ErrorAction SilentlyContinue
# Report the version actually on disk after the pull, not the remote string —
# if the pull failed the banner must not claim a successful upgrade.
$NewVer = $LocalVer
if (Test-Path $VerFile) { $NewVer = (Get-Content $VerFile -Raw).Trim() }
if ($pullOk -and $NewVer -ne $LocalVer) {
Write-Host " [OK] Upgrade complete: v$LocalVer -> v$NewVer" -ForegroundColor Green
} elseif ($pullOk) {
Write-Host " [OK] Already at the latest framework (v$NewVer)" -ForegroundColor Green
}
}
} else {
# A broken prior install (src present but .git gone) may still hold the user's
# soul, .env, custom agents, and memories — none of which are in git. Preserve
# them before wiping so a re-run can't silently destroy the user's work
# (issue #21). The common case (no existing src) skips all of this.
$FreshBackup = $null
$srcRapp = "$BRAINSTEM_HOME\src\rapp_brainstem"
if (Test-Path $srcRapp) {
$FreshBackup = "$env:TEMP\brainstem-fresh-$(Get-Random)"
New-Item -ItemType Directory -Force -Path "$FreshBackup\agents" | Out-Null
if (Test-Path "$srcRapp\soul.md") { Copy-Item "$srcRapp\soul.md" "$FreshBackup\soul.md" -Force -ErrorAction SilentlyContinue }
if (Test-Path "$srcRapp\.env") { Copy-Item "$srcRapp\.env" "$FreshBackup\.env" -Force -ErrorAction SilentlyContinue }
if (Test-Path "$srcRapp\agents") { Copy-Item "$srcRapp\agents\*.py" "$FreshBackup\agents\" -Force -ErrorAction SilentlyContinue }
if (Test-Path "$srcRapp\.brainstem_data") { Copy-Item "$srcRapp\.brainstem_data" "$FreshBackup\.brainstem_data" -Recurse -Force -ErrorAction SilentlyContinue }
}
if (Test-Path "$BRAINSTEM_HOME\src") {
Remove-Item -Recurse -Force "$BRAINSTEM_HOME\src" -ErrorAction SilentlyContinue
}
Write-Host " Cloning repository..."
git clone --quiet $REPO_URL "$BRAINSTEM_HOME\src" 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Host " [X] Failed to clone repository" -ForegroundColor Red
throw "git clone failed"
}
if ($PIN_VERSION) {
# Pin/RC-test: check out the requested release tag after cloning
# (accepts v0.6.14 / 0.6.14 / brainstem-v0.6.14 forms like install.sh).
Push-Location "$BRAINSTEM_HOME\src"
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
git fetch --tags --quiet origin 2>&1 | Out-Null
$TagRef = Resolve-PinnedTag $PIN_VERSION
if ($TagRef) {
git checkout --quiet $TagRef 2>&1 | Out-Null
} else {
Write-Host " [X] Version $PIN_VERSION not found. Available versions:" -ForegroundColor Red
git tag -l 'brainstem-v*' 'v*' 2>&1 | Sort-Object | ForEach-Object { Write-Host " $_" }
}
$ErrorActionPreference = $prevEAP
Pop-Location
if (-not $TagRef) { throw "pinned version $PIN_VERSION not found" }
Write-Host " [OK] Checked out $TagRef" -ForegroundColor Green
}
# Restore any preserved user files over the fresh checkout.
if ($FreshBackup) {
$AgentsDir = "$BRAINSTEM_HOME\src\rapp_brainstem\agents"
if (Test-Path "$FreshBackup\soul.md") { Copy-Item "$FreshBackup\soul.md" "$BRAINSTEM_HOME\src\rapp_brainstem\soul.md" -Force -ErrorAction SilentlyContinue }
if (Test-Path "$FreshBackup\.env") { Copy-Item "$FreshBackup\.env" "$BRAINSTEM_HOME\src\rapp_brainstem\.env" -Force -ErrorAction SilentlyContinue }
Get-ChildItem "$FreshBackup\agents\*.py" -ErrorAction SilentlyContinue | ForEach-Object {
if ($_.Name -notin @("basic_agent.py", "__init__.py")) {
Copy-Item $_.FullName "$AgentsDir\$($_.Name)" -Force -ErrorAction SilentlyContinue
}
}
if (Test-Path "$FreshBackup\.brainstem_data") { Copy-Item "$FreshBackup\.brainstem_data" "$BRAINSTEM_HOME\src\rapp_brainstem\.brainstem_data" -Recurse -Force -ErrorAction SilentlyContinue }
Remove-Item -Recurse -Force $FreshBackup -ErrorAction SilentlyContinue
Write-Host " [OK] Preserved your soul, agents, memories, and config" -ForegroundColor Green
}
}
Write-Host " [OK] Source code ready" -ForegroundColor Green
}
function Run-PipInstall {
$reqFile = "$BRAINSTEM_HOME\src\rapp_brainstem\requirements.txt"
# Install into the venv (issue #29). The venv created by Setup-Venv already ships
# pip; only the rare system-python fallback (no venv) needs pip bootstrapping.
$py = Resolve-RunPython
if (-not (Test-PipWorks $py)) {
if (-not (Ensure-Pip)) { return }
$py = Resolve-RunPython
}
# Use the call operator, NOT Start-Process (same reasoning as Check-PythonDeps):
# the call operator quotes a $reqFile path containing spaces correctly, and it
# needs no console attachment — Start-Process -NoNewWindow -Wait can block
# forever in consoleless sessions (CI, some terminal hosts). Drop
# ErrorActionPreference to Continue locally so pip's stderr progress lines are
# not promoted to a terminating NativeCommandError under the script's global
# $ErrorActionPreference = 'Stop'.
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& $py -m pip install -r $reqFile 2>&1 | ForEach-Object { "$_" }
# `--user` is only valid (and only needed) on the system-python fallback; it
# errors inside a venv, so skip it when installing into the venv.
if ($LASTEXITCODE -ne 0 -and $py -ne (Get-VenvPython)) {
& $py -m pip install -r $reqFile --user 2>&1 | ForEach-Object { "$_" }
}
} finally {
$ErrorActionPreference = $prev
}
}
function Check-PythonDeps {
$py = Resolve-RunPython
# Use the call operator, NOT Start-Process -ArgumentList. Start-Process joins array
# arguments with spaces but does not re-quote an element that itself contains spaces,
# so "-c", "import flask, flask_cors, ..." reached python as the tokens
# "-c import flask, flask_cors, ..." — python's -c got only "import" -> SyntaxError.
# The call operator quotes arguments correctly. Drop ErrorActionPreference to Continue
# locally so python's stderr (e.g. when a module is missing) is not promoted to a
# terminating NativeCommandError under the script's global $ErrorActionPreference='Stop'.
$prev = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& $py -c "import flask, flask_cors, requests, dotenv" 2>&1 | Out-Null
return ($LASTEXITCODE -eq 0)
} catch {
return $false
} finally {
$ErrorActionPreference = $prev
}
}
function Setup-Dependencies {
Write-Host ""
Write-Host "Installing dependencies..."
Push-Location "$BRAINSTEM_HOME\src\rapp_brainstem"
Run-PipInstall
$depsOk = Check-PythonDeps
if (-not $depsOk) {
# v0.6.2 accidentally self-healed transient pip failures via the second
# Run-PipInstall in Launch-Brainstem. Keep one deliberate retry here so
# a PyPI/DNS blip doesn't hard-abort a fresh install.
Write-Host " [..] Dependency check failed — retrying pip install once..." -ForegroundColor Yellow
Run-PipInstall
$depsOk = Check-PythonDeps
}
Pop-Location
if (-not $depsOk) {
# Never print [OK] and continue toward a server that will die at
# `import requests` behind a dead browser tab — stop here, honestly,
# with the guidance Ensure-Pip/pip printed above.
throw "Python dependencies failed to install (see messages above)"
}
Write-Host " [OK] Dependencies installed" -ForegroundColor Green
}
function Ensure-Dependencies {
# Quick import check — only run pip when something is actually missing (mirrors
# install.sh's ensure_deps; keeps the fast path from hitting PyPI every launch).
Push-Location "$BRAINSTEM_HOME\src\rapp_brainstem"
if (Check-PythonDeps) {
Pop-Location
Write-Host " [OK] Dependencies verified" -ForegroundColor Green
return
}
Write-Host " [..] Missing dependencies — installing..." -ForegroundColor Yellow
Run-PipInstall
$ok = Check-PythonDeps
Pop-Location
if (-not $ok) {
throw "Python dependencies are missing and could not be installed (see messages above)"
}
Write-Host " [OK] Dependencies installed" -ForegroundColor Green
}
function Install-CLI {
Write-Host ""
Write-Host "Installing CLI..."
if (-not (Test-Path $BRAINSTEM_BIN)) {
New-Item -ItemType Directory -Force -Path $BRAINSTEM_BIN | Out-Null
}
# Wrappers launch the venv interpreter (issue #29) so `brainstem` always runs the
# same Python that install set up; if the venv is ever missing they fall back to
# the system Python captured here. Quote every interpreter path — the direct-path
# fallback (…\First Last\AppData\…\python.exe) contains spaces.
$venvPy = Get-VenvPython
$sysPy = Resolve-PythonExe
# Batch wrapper (works in cmd.exe and PowerShell). A goto (not an if/else block)
# avoids cmd.exe mis-parsing a path that happens to contain a parenthesis.
$cmdContent = @"
@echo off
cd /d "$BRAINSTEM_HOME\src\rapp_brainstem"
if exist "$venvPy" goto RAPP_VENV
"$sysPy" brainstem.py %*
goto :eof
:RAPP_VENV
"$venvPy" brainstem.py %*
"@
Set-Content -Path "$BRAINSTEM_BIN\brainstem.cmd" -Value $cmdContent
# PowerShell wrapper
$psContent = @"
Set-Location "$BRAINSTEM_HOME\src\rapp_brainstem"
if (Test-Path "$venvPy") { & "$venvPy" brainstem.py @args } else { & "$sysPy" brainstem.py @args }
"@
Set-Content -Path "$BRAINSTEM_BIN\brainstem.ps1" -Value $psContent
# Add to PATH if not already there
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($userPath -notlike "*$BRAINSTEM_BIN*") {
[Environment]::SetEnvironmentVariable("Path", "$BRAINSTEM_BIN;$userPath", "User")
$env:Path = "$BRAINSTEM_BIN;$env:Path"
Write-Host " Added to PATH" -ForegroundColor Green
}
Write-Host " [OK] CLI installed" -ForegroundColor Green
}
function Create-Env {
$envFile = "$BRAINSTEM_HOME\src\rapp_brainstem\.env"
$exampleFile = "$BRAINSTEM_HOME\src\rapp_brainstem\.env.example"
if (-not (Test-Path $envFile) -and (Test-Path $exampleFile)) {
Copy-Item $exampleFile $envFile
}
}
function Launch-Brainstem {
# Refresh from this installer's repo before launching (no-op if already current).
# Skip when a version is pinned — pulling main would move off the pinned tag.
if ((-not $PIN_VERSION) -and (Test-Path "$BRAINSTEM_HOME\src\.git")) {
Push-Location "$BRAINSTEM_HOME\src"
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
git remote set-url origin $REPO_URL 2>&1 | Out-Null
git pull --quiet origin main 2>&1 | Out-Null
$ErrorActionPreference = $prevEAP
Pop-Location
}
# Dependencies BEFORE auth: if they cannot be installed, fail now — not after
# walking the user through a GitHub device-code authorization they can't use.
Push-Location "$BRAINSTEM_HOME\src\rapp_brainstem"
if (-not (Check-PythonDeps)) {
Write-Host " [..] Installing missing dependencies..." -ForegroundColor Yellow
Run-PipInstall
if (-not (Check-PythonDeps)) {
Pop-Location
# Launching anyway would crash at `import requests` and strand the user
# on a browser tab pointing at a server that never bound port 7071.
throw "Python dependencies are missing and could not be installed (see messages above)"
}
}
Pop-Location
$tokenFile = "$BRAINSTEM_HOME\src\rapp_brainstem\.copilot_token"
$clientId = "Iv1.b507a08c87ecfe98"
# Check if already authenticated
$needsAuth = $true
if (Test-Path $tokenFile) {
try {
$tokenData = Get-Content $tokenFile -Raw | ConvertFrom-Json
$savedToken = $tokenData.access_token
if ($savedToken) {
$authPrefix = if ($savedToken.StartsWith("ghu_")) { "token" } else { "Bearer" }
$headers = @{
"Authorization" = "$authPrefix $savedToken"
"Accept" = "application/json"
"Editor-Version" = "vscode/1.95.0"
"Editor-Plugin-Version" = "copilot/1.0.0"
}
try {
$checkResp = Invoke-WebRequest -Uri "https://api.github.com/copilot_internal/v2/token" -Headers $headers -UseBasicParsing -TimeoutSec 10 -ErrorAction SilentlyContinue
if ($checkResp.StatusCode -eq 200) {
Write-Host " [OK] Already authenticated with GitHub Copilot" -ForegroundColor Green
$needsAuth = $false
}
} catch {
Write-Host " [..] Saved token expired — re-authenticating..." -ForegroundColor Yellow
Remove-Item $tokenFile -Force -ErrorAction SilentlyContinue
}
}
} catch {
Remove-Item $tokenFile -Force -ErrorAction SilentlyContinue
}
}
if ($needsAuth) {
Write-Host ""
Write-Host " Authenticating with GitHub Copilot..." -ForegroundColor Cyan
Write-Host ""
try {
$deviceResp = Invoke-RestMethod -Uri "https://github.com/login/device/code" -Method Post -ContentType "application/x-www-form-urlencoded" -Body "client_id=$clientId" -Headers @{"Accept"="application/json"} -TimeoutSec 10
$userCode = $deviceResp.user_code
$deviceCode = $deviceResp.device_code
$interval = if ($deviceResp.interval) { $deviceResp.interval } else { 5 }
$verifyUri = $deviceResp.verification_uri
if (-not $userCode -or -not $deviceCode) {
Write-Host " [!] Could not start auth — sign in at http://localhost:7071/login" -ForegroundColor Yellow
} else {
Write-Host " ┌─────────────────────────────────────────┐"
Write-Host " │ Your code: " -NoNewline; Write-Host $userCode -ForegroundColor Cyan -NoNewline; Write-Host " │"
Write-Host " └─────────────────────────────────────────┘"
Write-Host ""
Write-Host " Opening browser to authorize..."
Start-Process $verifyUri
Write-Host " Waiting for authorization..."
Write-Host ""
for ($i = 0; $i -lt 60; $i++) {
Start-Sleep -Seconds $interval
try {
$pollResp = Invoke-RestMethod -Uri "https://github.com/login/oauth/access_token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body "client_id=$clientId&device_code=$deviceCode&grant_type=urn:ietf:params:oauth:grant-type:device_code" -Headers @{"Accept"="application/json"} -TimeoutSec 10
if ($pollResp.access_token) {
$tokenJson = @{ access_token = $pollResp.access_token }
if ($pollResp.refresh_token) { $tokenJson.refresh_token = $pollResp.refresh_token }
$tokenJson | ConvertTo-Json | Set-Content $tokenFile
# Validate Copilot access
$authPrefix = if ($pollResp.access_token.StartsWith("ghu_")) { "token" } else { "Bearer" }
$headers = @{
"Authorization" = "$authPrefix $($pollResp.access_token)"
"Accept" = "application/json"
"Editor-Version" = "vscode/1.95.0"
"Editor-Plugin-Version" = "copilot/1.0.0"
}
try {
$copilotCheck = Invoke-WebRequest -Uri "https://api.github.com/copilot_internal/v2/token" -Headers $headers -UseBasicParsing -TimeoutSec 10 -ErrorAction SilentlyContinue
if ($copilotCheck.StatusCode -eq 200) {
Write-Host " [OK] Authenticated — Copilot access confirmed" -ForegroundColor Green
}
} catch {
$statusCode = $_.Exception.Response.StatusCode.value__
if ($statusCode -eq 403) {
Write-Host ""
Write-Host " [X] This GitHub account does NOT have Copilot access." -ForegroundColor Red
Write-Host ""
Write-Host " Either:"
Write-Host " 1. Sign up for Copilot: " -NoNewline; Write-Host "https://github.com/github-copilot/signup" -ForegroundColor Cyan
Write-Host " 2. Re-run this installer and sign in with a different account"
Write-Host ""
Remove-Item $tokenFile -Force -ErrorAction SilentlyContinue
} else {
Write-Host " [OK] Authenticated with GitHub" -ForegroundColor Green
}
}
break
}
$error_code = $pollResp.error
if ($error_code -eq "expired_token") {
Write-Host " [!] Auth timed out — sign in at http://localhost:7071/login" -ForegroundColor Yellow
break
}
if ($error_code -ne "authorization_pending" -and $error_code -ne "slow_down" -and $error_code) {
Write-Host " [!] Auth error: $error_code" -ForegroundColor Yellow
break
}
} catch {}
}
}
} catch {
Write-Host " [!] Could not start auth — sign in at http://localhost:7071/login" -ForegroundColor Yellow
}
}
# Launch the server
Write-Host ""
Write-Host " Starting RAPP Brainstem..." -ForegroundColor Cyan
Write-Host ""
Push-Location "$BRAINSTEM_HOME\src\rapp_brainstem"
# Free port 7071 before launching — an upgrade must not leave the OLD server
# running, or the health poll below would pass against it and report a false
# success while the new code never actually binds the port. Guarded for the
# absence of Get-NetTCPConnection (older/Server SKUs).
try {
$listeners = Get-NetTCPConnection -LocalPort 7071 -State Listen -ErrorAction SilentlyContinue
if ($listeners) {
$ownerPids = @($listeners | ForEach-Object { $_.OwningProcess } | Sort-Object -Unique)
foreach ($ownerPid in $ownerPids) {
if ($ownerPid -and $ownerPid -ne 0) {
Write-Host " [!] Stopping existing server (PID $ownerPid)..." -ForegroundColor Yellow
Stop-Process -Id $ownerPid -Force -ErrorAction SilentlyContinue
}
}
Start-Sleep -Seconds 1
}
} catch {}
# Open the browser once the server actually answers (#14) — a fixed delay
# races cold startups and lands the user on a dead-port error page. Poll
# /health, then open; after 60s open anyway so the user still gets the tab.
Start-Job -ScriptBlock {
for ($i = 0; $i -lt 60; $i++) {
try {
Invoke-WebRequest -Uri "http://localhost:7071/health" -UseBasicParsing -TimeoutSec 1 | Out-Null
break
} catch {
Start-Sleep -Seconds 1
}
}
Start-Process "http://localhost:7071"
} | Out-Null
$py = Resolve-RunPython
& $py brainstem.py
}
function Main {
Print-Banner
if ($PIN_VERSION) {
Write-Host " Pinning to version: $PIN_VERSION" -ForegroundColor Cyan
Write-Host ""
}
# Check if this is an upgrade of an existing install. Skip the fast path when a
# version is pinned — Install-Brainstem must run to check out the requested tag.
if ((-not $PIN_VERSION) -and (Test-Path "$BRAINSTEM_HOME\src\.git")) {
Write-Host "Checking for updates..."
if (-not (Check-ForUpgrade)) {
# Already up to date — still re-heal the environment before launching,
# exactly like install.sh's fast path: verify prerequisites, the venv and
# deps, rewrite the CLI wrappers, and restore a missing .env (issues #9, #3).
Check-Prerequisites
Setup-Venv
Ensure-Dependencies
Install-CLI
Create-Env
Launch-Brainstem
return
}