-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathinstall.ps1
More file actions
2035 lines (1736 loc) · 69.2 KB
/
install.ps1
File metadata and controls
2035 lines (1736 loc) · 69.2 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
# install.ps1 - Install opencode-multi-auth plugin for OpenCode Config Suites
# Auth path: env token -> cached token -> gh CLI -> secure prompt
#Requires -Version 5.1
param(
[string]$Version,
[string]$SourceBranch,
[string]$PwshPath
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# --- Config ---
$GITHUB_SOURCE_REPO = "andyvandaric/andyvand-opencode-config"
$REQUESTED_VERSION = if ($Version) { $Version.TrimStart('v') } elseif ($env:OCS_VERSION) { $env:OCS_VERSION.TrimStart('v') } else { "" }
$GITHUB_SOURCE_BRANCH = if ($SourceBranch) { $SourceBranch } elseif ($env:OCS_RELEASE_BRANCH) { $env:OCS_RELEASE_BRANCH } else { "beta" }
$DEFAULT_RELEASE_BRANCH = "beta"
$INSTALLER_DEFAULT_PROFILE = "codex-5.3-token-saver"
$INSTALLER_DEFAULT_MODE = "performance"
$ACCESS_LANDING_PAGE = "https://wa.me/6281289731212?text=Mau%20order%20OCS%20nya%2C%20mohon%20infonya%20ya"
$PLUGIN_DIR = "$env:USERPROFILE\.config\opencode\plugins\opencode-multi-auth"
$TOKEN_FILE = "$env:USERPROFILE\.opencode-suites\.token"
$script:ResolvedReleaseToken = ""
$script:ResolvedSourceBranch = $GITHUB_SOURCE_BRANCH
$TMP_DIR = [System.IO.Path]::Combine(
[System.IO.Path]::GetTempPath(),
"ocs-install-$([System.Guid]::NewGuid().ToString('N').Substring(0,8))"
)
function Get-EnvOrDefault {
param(
[string]$Name,
[string]$Default
)
$value = [Environment]::GetEnvironmentVariable($Name)
if ([string]::IsNullOrWhiteSpace($value)) {
return $Default
}
return $value
}
function Resolve-PwshPath {
$pwshCmd = Get-Command pwsh -ErrorAction SilentlyContinue
if ($pwshCmd -and $pwshCmd.Path) {
return $pwshCmd.Path
}
$candidates = @(
(Join-Path $env:ProgramFiles "PowerShell\7\pwsh.exe"),
(Join-Path $env:LOCALAPPDATA "Microsoft\PowerShell\7\pwsh.exe"),
(Join-Path $env:USERPROFILE "scoop\shims\pwsh.exe")
)
foreach ($candidate in $candidates) {
if ($candidate -and (Test-Path $candidate)) {
return $candidate
}
}
return $null
}
function Invoke-PwshRelaunch {
param([string]$PwshPath)
if (-not $PwshPath) {
return $false
}
if ($env:OCS_PWSH_RELAUNCHED -eq "1") {
return $false
}
Write-Host "Relaunching installer in PowerShell 7 for better compatibility..."
$previousRelaunchFlag = $env:OCS_PWSH_RELAUNCHED
$env:OCS_PWSH_RELAUNCHED = "1"
$scriptPath = $PSCommandPath
$exitCode = 0
$previousVersion = $env:OCS_VERSION
$previousBranch = $env:OCS_RELEASE_BRANCH
if ($REQUESTED_VERSION) {
$env:OCS_VERSION = $REQUESTED_VERSION
}
if ($GITHUB_SOURCE_BRANCH) {
$env:OCS_RELEASE_BRANCH = $GITHUB_SOURCE_BRANCH
}
try {
if ($scriptPath -and (Test-Path $scriptPath)) {
& $PwshPath -NoProfile -ExecutionPolicy Bypass -File $scriptPath
if ($LASTEXITCODE -ne $null) {
$exitCode = $LASTEXITCODE
}
if ($exitCode -ne 0) {
Write-Warning "Relaunched installer exited with code $exitCode"
return $false
}
return $true
}
$relaunchUrl = "https://raw.githubusercontent.com/andyvandaric/opencode-suites-installer/main/install.ps1"
$relaunchCommand = '$env:OCS_PWSH_RELAUNCHED=''1''; irm ''' + $relaunchUrl + ''' | iex'
& $PwshPath -NoProfile -ExecutionPolicy Bypass -Command $relaunchCommand
if ($LASTEXITCODE -ne $null) {
$exitCode = $LASTEXITCODE
}
if ($exitCode -ne 0) {
Write-Warning "Relaunched installer exited with code $exitCode"
return $false
}
return $true
} finally {
if ($previousVersion) {
$env:OCS_VERSION = $previousVersion
} else {
Remove-Item Env:OCS_VERSION -ErrorAction SilentlyContinue
}
if ($previousBranch) {
$env:OCS_RELEASE_BRANCH = $previousBranch
} else {
Remove-Item Env:OCS_RELEASE_BRANCH -ErrorAction SilentlyContinue
}
if ($previousRelaunchFlag) {
$env:OCS_PWSH_RELAUNCHED = $previousRelaunchFlag
} else {
Remove-Item Env:OCS_PWSH_RELAUNCHED -ErrorAction SilentlyContinue
}
}
}
function Ensure-PowerShellRuntime {
$psVersion = $PSVersionTable.PSVersion
if ($psVersion.Major -ge 7) {
Write-Host "PowerShell $($psVersion.ToString()) detected"
return $false
}
Write-Warning "Running on Windows PowerShell $($psVersion.ToString()). PowerShell 7+ is recommended."
$pwshPath = Resolve-PwshPath
if ($pwshPath) {
Write-Host "PowerShell 7 is already installed."
$relaunched = Invoke-PwshRelaunch -PwshPath $pwshPath
if ($relaunched) {
Write-Host "Relaunch completed. Keeping current terminal open."
return $true
}
Write-Host "Continuing in current shell."
return $false
}
$installed = $false
if (Get-Command winget -ErrorAction SilentlyContinue) {
Write-Host "Attempting PowerShell 7 install via winget..."
try {
& winget install --id Microsoft.PowerShell --source winget --accept-package-agreements --accept-source-agreements --silent
if ($LASTEXITCODE -eq 0) { $installed = $true }
} catch {
$installed = $false
}
}
if ((-not $installed) -and (Get-Command choco -ErrorAction SilentlyContinue)) {
Write-Host "Attempting PowerShell 7 install via Chocolatey..."
try {
& choco install powershell-core -y
if ($LASTEXITCODE -eq 0) { $installed = $true }
} catch {
$installed = $false
}
}
if ((-not $installed) -and (Get-Command scoop -ErrorAction SilentlyContinue)) {
Write-Host "Attempting PowerShell 7 install via Scoop..."
try {
& scoop install pwsh
if ($LASTEXITCODE -eq 0) { $installed = $true }
} catch {
$installed = $false
}
}
$pwshPath = Resolve-PwshPath
if ($pwshPath) {
Write-Host "PowerShell 7 detected after installation attempt."
$relaunched = Invoke-PwshRelaunch -PwshPath $pwshPath
if ($relaunched) {
Write-Host "Relaunch completed. Keeping current terminal open."
return $true
}
Write-Host "Continuing in current shell."
} else {
Write-Warning "PowerShell 7 installation was skipped or failed. Continuing with current shell."
}
return $false
}
function Refresh-SessionPath {
$machinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
if ($machinePath -and $userPath) {
$env:PATH = "$machinePath;$userPath"
} elseif ($machinePath) {
$env:PATH = $machinePath
} elseif ($userPath) {
$env:PATH = $userPath
}
$ghBinCandidates = @(
(Join-Path $env:ProgramFiles "GitHub CLI"),
(Join-Path $env:LOCALAPPDATA "Programs\GitHub CLI")
)
foreach ($ghBin in $ghBinCandidates) {
if ($ghBin -and (Test-Path (Join-Path $ghBin "gh.exe")) -and ($env:PATH -notlike "*$ghBin*")) {
$env:PATH = "$ghBin;$env:PATH"
}
}
$opencodeBinCandidates = @(
(Join-Path $env:USERPROFILE ".opencode\bin"),
(Join-Path $env:USERPROFILE ".bun\bin")
)
foreach ($opencodeBin in $opencodeBinCandidates) {
if (-not $opencodeBin) { continue }
$hasOpencodeBinary = (Test-Path (Join-Path $opencodeBin "opencode.exe")) -or (Test-Path (Join-Path $opencodeBin "opencode.cmd")) -or (Test-Path (Join-Path $opencodeBin "opencode.ps1"))
if ($hasOpencodeBinary -and ($env:PATH -notlike "*$opencodeBin*")) {
$env:PATH = "$opencodeBin;$env:PATH"
}
}
}
function Add-PathEntryToUserPath {
param([string]$PathEntry)
if (-not $PathEntry) { return }
if (-not (Test-Path $PathEntry)) { return }
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
$entries = @()
if ($userPath) {
$entries = $userPath -split ";"
}
$normalized = $PathEntry.TrimEnd("\\")
$alreadyPresent = $false
foreach ($entry in $entries) {
if ($entry -and ($entry.TrimEnd("\\") -ieq $normalized)) {
$alreadyPresent = $true
break
}
}
if (-not $alreadyPresent) {
$newPath = if ($userPath) { "$userPath;$PathEntry" } else { $PathEntry }
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")
}
if (($env:PATH -split ";") -notcontains $PathEntry) {
$env:PATH = "$PathEntry;$env:PATH"
}
}
function Ensure-OpencodePathEntries {
$pathCandidates = @(
(Join-Path $env:USERPROFILE ".opencode\bin"),
(Join-Path $env:USERPROFILE ".bun\bin"),
(Join-Path $env:USERPROFILE ".local\bin")
)
foreach ($candidate in $pathCandidates) {
Add-PathEntryToUserPath -PathEntry $candidate
}
Refresh-SessionPath
}
function Ensure-WindowsShellEnv {
if ($env:OS -ne "Windows_NT") {
return
}
$systemRoot = if ($env:SystemRoot) { $env:SystemRoot } else { "C:\Windows" }
$fallbackCmd = Join-Path $systemRoot "System32\cmd.exe"
$currentComSpecRaw = if ($env:ComSpec) { $env:ComSpec } else { $env:COMSPEC }
$currentComSpec = if ($currentComSpecRaw) {
$currentComSpecRaw.Trim().Trim('"')
} else {
""
}
if ((-not $currentComSpec) -or (-not (Test-Path $currentComSpec))) {
if (Test-Path $fallbackCmd) {
$env:ComSpec = $fallbackCmd
$env:COMSPEC = $fallbackCmd
Write-Host "Normalized COMSPEC to $fallbackCmd"
} else {
Write-Warning "cmd.exe not found at expected path: $fallbackCmd"
}
} else {
$env:ComSpec = $currentComSpec
$env:COMSPEC = $currentComSpec
}
}
function Should-RenderInstallerProgress {
if ($env:CI -eq "1" -or $env:CI -eq "true") {
return $false
}
return [bool]([Environment]::UserInteractive)
}
function Invoke-ExternalWithProgress {
param(
[Parameter(Mandatory = $true)]
[string]$Activity,
[Parameter(Mandatory = $true)]
[string]$Executable,
[string[]]$Arguments = @(),
[string]$WorkingDirectory = "",
[string]$LogPath = ""
)
if (-not $LogPath) {
$safeName = ($Activity -replace "[^a-zA-Z0-9]+", "-").Trim("-").ToLowerInvariant()
if (-not $safeName) {
$safeName = "installer-step"
}
if ($TMP_DIR -and -not (Test-Path $TMP_DIR)) {
New-Item -ItemType Directory -Force -Path $TMP_DIR | Out-Null
}
$LogPath = Join-Path $TMP_DIR ("$safeName.log")
}
$logDir = Split-Path -Parent $LogPath
if ($logDir -and -not (Test-Path $logDir)) {
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
}
if (Test-Path $LogPath) {
Remove-Item -Path $LogPath -Force -ErrorAction SilentlyContinue
}
$runSync = {
param(
[string]$SyncActivity,
[string]$SyncExecutable,
[string[]]$SyncArguments,
[string]$SyncWorkingDirectory,
[string]$SyncLogPath
)
$exitCode = 0
Write-Host "[...] $SyncActivity"
try {
if ($SyncWorkingDirectory) {
Push-Location $SyncWorkingDirectory
}
& $SyncExecutable @SyncArguments *> $SyncLogPath
if ($LASTEXITCODE -is [int]) {
$exitCode = $LASTEXITCODE
}
} catch {
$exitCode = 1
"ERROR: $($_.Exception.Message)" | Out-File -FilePath $SyncLogPath -Encoding UTF8 -Append
} finally {
if ($SyncWorkingDirectory) {
Pop-Location
}
}
$ok = ($exitCode -eq 0)
if ($ok) {
Write-Host "[OK] $SyncActivity"
} else {
Write-Warning "$SyncActivity failed (exit $exitCode). Log: $SyncLogPath"
}
return [PSCustomObject]@{
Success = $ok
ExitCode = $exitCode
LogPath = $SyncLogPath
}
}
if (-not (Get-Command Start-Job -ErrorAction SilentlyContinue)) {
return & $runSync $Activity $Executable $Arguments $WorkingDirectory $LogPath
}
try {
$job = Start-Job -ScriptBlock {
param(
[string]$Exe,
[string[]]$ArgList,
[string]$WorkDir,
[string]$OutLog
)
$exitCode = 0
try {
if ($WorkDir) {
Set-Location -Path $WorkDir
}
& $Exe @ArgList *> $OutLog
if ($LASTEXITCODE -is [int]) {
$exitCode = $LASTEXITCODE
}
} catch {
$exitCode = 1
"ERROR: $($_.Exception.Message)" | Out-File -FilePath $OutLog -Encoding UTF8 -Append
}
[PSCustomObject]@{
ExitCode = $exitCode
LogPath = $OutLog
}
} -ArgumentList $Executable, $Arguments, $WorkingDirectory, $LogPath
} catch {
Write-Warning "Could not start background job for '$Activity'. Falling back to synchronous execution."
return & $runSync $Activity $Executable $Arguments $WorkingDirectory $LogPath
}
$renderProgress = Should-RenderInstallerProgress
$spinnerFrames = @("|", "/", "-", "\\")
$frameIndex = 0
$startTime = Get-Date
$dotTicks = 0
while (($job.State -eq "Running") -or ($job.State -eq "NotStarted")) {
$elapsedSeconds = [Math]::Round(((Get-Date) - $startTime).TotalSeconds, 1)
if ($renderProgress) {
$status = "{0} {1}s" -f $spinnerFrames[$frameIndex], $elapsedSeconds
Write-Progress -Activity $Activity -Status $status
$frameIndex = ($frameIndex + 1) % $spinnerFrames.Count
} else {
if (($dotTicks % 20) -eq 0) {
Write-Host "[...] $Activity"
}
$dotTicks++
}
Start-Sleep -Milliseconds 200
$job = Get-Job -Id $job.Id
}
if ($renderProgress) {
Write-Progress -Activity $Activity -Completed
}
$result = Receive-Job -Job $job -ErrorAction SilentlyContinue | Select-Object -Last 1
Remove-Job -Job $job -Force -ErrorAction SilentlyContinue | Out-Null
if (-not $result) {
Write-Warning "$Activity failed: no process result was returned."
return [PSCustomObject]@{
Success = $false
ExitCode = 1
LogPath = $LogPath
}
}
$success = ([int]$result.ExitCode -eq 0)
if ($success) {
Write-Host "[OK] $Activity"
} else {
Write-Warning "$Activity failed (exit $($result.ExitCode)). Log: $($result.LogPath)"
}
return [PSCustomObject]@{
Success = $success
ExitCode = [int]$result.ExitCode
LogPath = [string]$result.LogPath
}
}
function Ensure-GitHubCli {
if (Get-Command gh -ErrorAction SilentlyContinue) {
return $true
}
Write-Warning "GitHub CLI (gh) not found. Attempting auto install..."
$installed = $false
if (Get-Command winget -ErrorAction SilentlyContinue) {
Write-Host "Attempting GitHub CLI install via winget..."
$wingetIds = @("GitHub.cli", "Microsoft.GitHub.CLI")
foreach ($wingetId in $wingetIds) {
if ($installed) { break }
try {
& winget install --id $wingetId --exact --silent --accept-package-agreements --accept-source-agreements
if ($LASTEXITCODE -eq 0) { $installed = $true }
} catch {
$installed = $false
}
}
}
if ((-not $installed) -and (Get-Command choco -ErrorAction SilentlyContinue)) {
Write-Host "Attempting GitHub CLI install via Chocolatey..."
try {
& choco install gh -y
if ($LASTEXITCODE -eq 0) { $installed = $true }
} catch {
$installed = $false
}
}
if ((-not $installed) -and (Get-Command scoop -ErrorAction SilentlyContinue)) {
Write-Host "Attempting GitHub CLI install via Scoop..."
try {
& scoop install gh
if ($LASTEXITCODE -eq 0) { $installed = $true }
} catch {
$installed = $false
}
}
Refresh-SessionPath
return [bool](Get-Command gh -ErrorAction SilentlyContinue)
}
function Save-TokenFile {
param([string]$Token)
if (-not $Token) { return }
try {
$tokenDir = Split-Path -Parent $TOKEN_FILE
if ($tokenDir -and (-not (Test-Path $tokenDir))) {
New-Item -ItemType Directory -Path $tokenDir -Force | Out-Null
}
Set-Content -Path $TOKEN_FILE -Value $Token -Encoding UTF8
} catch {
Write-Warning "Could not persist token cache to $TOKEN_FILE"
}
}
function Resolve-Token {
param(
[switch]$NonInteractive,
[switch]$SkipTokenCache
)
if ($env:GH_TOKEN) {
Write-Host "Auth: using GH_TOKEN environment variable"
return $env:GH_TOKEN.Trim()
}
if ($env:GITHUB_TOKEN) {
Write-Host "Auth: using GITHUB_TOKEN environment variable"
return $env:GITHUB_TOKEN.Trim()
}
if ((-not $SkipTokenCache) -and (Test-Path $TOKEN_FILE)) {
try {
$cachedToken = (Get-Content -Path $TOKEN_FILE -Raw -Encoding UTF8).Trim()
if ($cachedToken) {
Write-Host "Auth: using cached token file"
return $cachedToken
}
} catch {
Write-Warning "Token cache exists but could not be read: $TOKEN_FILE"
}
}
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
$ghInstalled = Ensure-GitHubCli
if (-not $ghInstalled) {
Write-Warning "GitHub CLI auto-install failed. Please install gh and authenticate via browser login."
}
}
if (Get-Command gh -ErrorAction SilentlyContinue) {
gh auth status 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {
Write-Host "GitHub CLI not authenticated. Opening browser login..."
& gh auth login
if ($LASTEXITCODE -eq 0) {
& gh config set -h github.com git_protocol https | Out-Null
& gh auth refresh -h github.com --scopes repo | Out-Null
}
if ($LASTEXITCODE -ne 0) {
Write-Warning "GitHub CLI login failed."
}
}
$ghToken = gh auth token 2>$null
if ((-not $ghToken) -or [string]::IsNullOrWhiteSpace($ghToken)) {
$statusWithToken = gh auth status --show-token 2>$null
if ($LASTEXITCODE -eq 0 -and $statusWithToken) {
$statusText = ($statusWithToken | Out-String)
$match = [regex]::Match($statusText, 'Token:\s*([^\s]+)')
if ($match.Success) {
$ghToken = $match.Groups[1].Value
}
}
}
if ($LASTEXITCODE -eq 0 -and $ghToken) {
$trimmed = $ghToken.Trim()
Write-Host "Auth: using gh CLI token"
Save-TokenFile -Token $trimmed
return $trimmed
}
}
if ($NonInteractive) {
Write-Error "Unable to resolve GitHub token in non-interactive mode. Set GH_TOKEN/GITHUB_TOKEN or authenticate gh."
exit 1
}
Write-Host "Run this command in terminal, then rerun installer:"
Write-Host "gh auth login"
Write-Host "Then choose: GitHub.com -> HTTPS -> Yes -> Login with a web browser"
Write-Host "If browser auto-open fails (WSL), open the shown URL manually and finish login"
Write-Host "Optional hardening: gh auth refresh -h github.com --scopes repo"
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
Write-Host "Install GitHub CLI first: https://cli.github.com/"
}
Write-Error "Unable to obtain GitHub token. Complete gh login first, then rerun installer."
exit 1
}
function Open-LandingPage {
Write-Output "Open purchase chat: $ACCESS_LANDING_PAGE"
try {
Start-Process $ACCESS_LANDING_PAGE | Out-Null
} catch {
Write-Warning "Could not open browser automatically. Visit: $ACCESS_LANDING_PAGE"
}
}
function Test-RepoAccess {
param(
[string]$Token,
[switch]$SuppressLandingPage
)
$headers = @{
Authorization = "token $Token"
Accept = "application/vnd.github+json"
}
try {
$response = Invoke-WebRequest -Uri "https://api.github.com/repos/$GITHUB_SOURCE_REPO/branches/$GITHUB_SOURCE_BRANCH" -Headers $headers -UseBasicParsing -ErrorAction Stop
Write-Host "Repo branch access verified: $GITHUB_SOURCE_REPO@$GITHUB_SOURCE_BRANCH (HTTP $($response.StatusCode))"
return $true
} catch {
$code = 0
if ($_.Exception.Response -and $_.Exception.Response.StatusCode) {
$code = $_.Exception.Response.StatusCode.value__
}
if ($code -in @(401, 403, 404)) {
Write-Warning "You do not have OCS access yet. Repo/branch: $GITHUB_SOURCE_REPO@$GITHUB_SOURCE_BRANCH"
Write-Host "GitHub API response: HTTP $code"
if (-not $SuppressLandingPage) {
Open-LandingPage
}
return $false
}
Write-Warning "Cannot access repo branch $GITHUB_SOURCE_REPO@$GITHUB_SOURCE_BRANCH (HTTP $code). Check network and GitHub auth state."
return $false
}
}
function Get-PluginBundleFromAssets {
param(
[string]$Token,
[string]$OutPath
)
$headers = @{
Authorization = "token $Token"
Accept = "application/vnd.github+json"
}
function Get-BranchAssets([string]$Branch) {
$assetsUri = "https://api.github.com/repos/$GITHUB_SOURCE_REPO/contents/assets?ref=$Branch"
return Invoke-RestMethod -Uri $assetsUri -Headers $headers -ErrorAction Stop
}
function Resolve-BundleFromAssets($Assets) {
$Assets |
Where-Object { $_.name -match '^opencode-config-suites-v(?<version>\d+\.\d+\.\d+)\.tar\.gz$' } |
ForEach-Object {
[PSCustomObject]@{
Asset = $_
Version = [version]$Matches.version
}
} |
Sort-Object Version -Descending
}
$resolvedBranch = $GITHUB_SOURCE_BRANCH
$assets = Get-BranchAssets $resolvedBranch
$bundle = Resolve-BundleFromAssets $assets
if ($REQUESTED_VERSION) {
$bundleName = "opencode-config-suites-v$REQUESTED_VERSION.tar.gz"
Write-Output "Requested bundle asset: $bundleName"
Write-Output "Checking branch $resolvedBranch for requested version..."
$selectedBundle = $bundle | Where-Object { $_.Asset.name -eq $bundleName } | Select-Object -First 1
if (-not $selectedBundle) {
Write-Output "Requested version v$REQUESTED_VERSION not found on branch $resolvedBranch."
Write-Output "Checking fallback branch $DEFAULT_RELEASE_BRANCH..."
if ($resolvedBranch -eq $DEFAULT_RELEASE_BRANCH) {
$fallbackAssets = $assets
} else {
$fallbackAssets = Get-BranchAssets $DEFAULT_RELEASE_BRANCH
}
$fallbackBundle = (Resolve-BundleFromAssets $fallbackAssets | Where-Object { $_.Asset.name -eq $bundleName } | Select-Object -First 1)
if ($fallbackBundle) {
Write-Warning "Requested version $REQUESTED_VERSION not found in assets/ for $GITHUB_SOURCE_REPO@$resolvedBranch. Falling back to $DEFAULT_RELEASE_BRANCH."
$selectedBundle = $fallbackBundle
$resolvedBranch = $DEFAULT_RELEASE_BRANCH
} else {
throw "Requested version $REQUESTED_VERSION not found in assets/ for $GITHUB_SOURCE_REPO@$resolvedBranch. Checked branches $resolvedBranch and $DEFAULT_RELEASE_BRANCH, and the asset is missing on both."
}
}
$bundle = $selectedBundle
} else {
$bundle = $bundle | Select-Object -First 1
}
if (-not $bundle) {
throw "No plugin bundle found in assets/ for $GITHUB_SOURCE_REPO@$resolvedBranch"
}
$bundleName = $bundle.Asset.name
$script:ResolvedSourceBranch = $resolvedBranch
Write-Output "Resolved bundle source branch: $($script:ResolvedSourceBranch)"
Write-Output "Resolved bundle asset: $bundleName"
$downloadHeaders = @{
Authorization = "token $Token"
Accept = "application/vnd.github.raw"
}
$downloadUri = "https://api.github.com/repos/$GITHUB_SOURCE_REPO/contents/assets/${bundleName}?ref=$($script:ResolvedSourceBranch)"
Invoke-WebRequest -Uri $downloadUri -Headers $downloadHeaders -OutFile $OutPath -UseBasicParsing -ErrorAction Stop
return $bundleName
}
function Get-Asset {
param(
[string]$Token,
[string]$PrimaryUrl,
[string]$FallbackUrl,
[string]$OutPath
)
$headers = @{
Authorization = "token $Token"
Accept = "application/octet-stream"
}
if ($PrimaryUrl) {
try {
Invoke-WebRequest -Uri $PrimaryUrl -Headers $headers -OutFile $OutPath -UseBasicParsing -ErrorAction Stop
return
} catch {
if (-not $FallbackUrl) {
throw
}
}
}
if ($FallbackUrl) {
Invoke-WebRequest -Uri $FallbackUrl -Headers $headers -OutFile $OutPath -UseBasicParsing -ErrorAction Stop
return
}
throw "No release asset URL available."
}
function Extract-TarGz {
param(
[string]$ArchivePath,
[string]$Destination,
[switch]$StripFirstComponent
)
$systemTarPath = Join-Path $env:SystemRoot "System32\tar.exe"
if (Test-Path $systemTarPath) {
$tarCommand = @{ Source = $systemTarPath }
} else {
$tarCommand = Get-Command tar.exe -ErrorAction SilentlyContinue
if (-not $tarCommand) {
$tarCommand = Get-Command tar -ErrorAction SilentlyContinue
}
}
if (-not $tarCommand) {
throw "tar command not found. Please ensure tar.exe is available on PATH."
}
$archiveFullPath = (Resolve-Path $ArchivePath).Path
$destinationFullPath = (Resolve-Path $Destination).Path
$args = @("-xzf", $archiveFullPath, "-C", $destinationFullPath)
if ($StripFirstComponent) {
$args += "--strip-components=1"
}
& $tarCommand.Source @args
if ($LASTEXITCODE -ne 0) {
throw "tar extraction failed with exit code $LASTEXITCODE"
}
}
function Test-SHA256Sums {
param([string]$SumsFile, [string]$TargetDir)
Write-Output "Verifying SHA256SUMS..."
$lines = Get-Content $SumsFile -Encoding UTF8
foreach ($line in $lines) {
$trimmed = $line.Trim()
if (-not $trimmed) { continue }
$parts = $trimmed -split " ", 2
if ($parts.Count -ne 2) { continue }
$expectedHash = $parts[0].Trim()
$relativePath = $parts[1].Trim()
$fullPath = Join-Path $TargetDir $relativePath
if (-not (Test-Path $fullPath)) { continue }
$actualHash = (Get-FileHash -Path $fullPath -Algorithm SHA256).Hash.ToLower()
if ($actualHash -ne $expectedHash.ToLower()) {
Write-Error "Checksum mismatch for $relativePath"
exit 1
}
}
Write-Output "Checksum verification passed"
}
function Ensure-Bun {
$bunBin = Join-Path $env:USERPROFILE ".bun\bin"
Add-PathEntryToUserPath -PathEntry $bunBin
Refresh-SessionPath
$bunCmd = Get-Command bun -ErrorAction SilentlyContinue
if ($bunCmd) {
$bunVersion = bun --version
$bunMajor = [int]($bunVersion -split "\.")[0]
if ($bunMajor -ge 1) {
Write-Output "Bun $bunVersion detected"
return
}
Write-Warning "Bun version $bunVersion is too old. Attempting upgrade..."
} else {
Write-Warning "Bun not found. Attempting auto install..."
}
try {
if (-not (Test-Path $TMP_DIR)) {
New-Item -ItemType Directory -Force $TMP_DIR | Out-Null
}
$bunInstallerPath = Join-Path $TMP_DIR "bun-install.ps1"
Invoke-WebRequest -Uri "https://bun.sh/install.ps1" -UseBasicParsing -OutFile $bunInstallerPath -ErrorAction Stop
$runner = if (Get-Command pwsh -ErrorAction SilentlyContinue) { "pwsh" } else { "powershell" }
$bunInstallRun = Invoke-ExternalWithProgress `
-Activity "Installing Bun runtime" `
-Executable $runner `
-Arguments @("-NoProfile", "-ExecutionPolicy", "Bypass", "-File", $bunInstallerPath) `
-WorkingDirectory $TMP_DIR `
-LogPath (Join-Path $TMP_DIR "bun-runtime-install.log")
if (-not $bunInstallRun.Success) {
throw "Bun installer exited with code $($bunInstallRun.ExitCode). See log: $($bunInstallRun.LogPath)"
}
} catch {
Write-Error "Failed to auto-install Bun: $($_.Exception.Message)"
Write-Error "Install Bun manually at https://bun.sh and retry."
exit 1
}
Add-PathEntryToUserPath -PathEntry $bunBin
Refresh-SessionPath
if (-not (Get-Command bun -ErrorAction SilentlyContinue)) {
Write-Error "Bun installed but bun command is still unavailable. Restart terminal and retry."
exit 1
}
$installedVersion = bun --version
$installedMajor = [int]($installedVersion -split "\.")[0]
if ($installedMajor -lt 1) {
Write-Error "Bun >= 1.0.0 required (found $installedVersion)."
exit 1
}
Write-Output "Bun $installedVersion detected"
}
function Test-OcsWorks {
$preferredCmd = Join-Path $env:USERPROFILE ".bun\bin\ocs.cmd"
$commandToRun = ""
if (Test-Path $preferredCmd) {
$commandToRun = $preferredCmd
} else {
$resolved = Get-Command ocs -ErrorAction SilentlyContinue
if (-not $resolved) {
return $false
}
$commandToRun = $resolved.Source
}
& $commandToRun --version *> $null
if ($LASTEXITCODE -ne 0) {
return $false
}
& $commandToRun --help *> $null
if ($LASTEXITCODE -ne 0) {
return $false
}
return $true
}
function Test-OcsPowerShellPolicyBlocked {
param([ref]$Diagnostic)
$Diagnostic.Value = ""
if ($env:OS -ne "Windows_NT") {
return $false
}
$ps1Path = Join-Path $env:USERPROFILE ".bun\bin\ocs.ps1"
if (-not (Test-Path $ps1Path)) {
return $false
}
$escapedPath = $ps1Path.Replace("'", "''")
try {
$probeOutput = (& powershell -NoProfile -Command "& '$escapedPath' --help" 2>&1 | Out-String).Trim()
$probeExit = $LASTEXITCODE
if ($probeExit -ne 0 -and $probeOutput -match "running scripts is disabled|PSSecurityException|cannot be loaded because running scripts is disabled") {
$Diagnostic.Value = $probeOutput
return $true
}
} catch {
$message = $_.Exception.Message
if ($message -match "running scripts is disabled|PSSecurityException|cannot be loaded because running scripts is disabled") {
$Diagnostic.Value = $message
return $true
}
}
return $false
}
function Test-OpencodeWorks {
param([int]$TimeoutSeconds = 8)
$resolved = Get-Command opencode -ErrorAction SilentlyContinue
if (-not $resolved) {
return $false
}
if ($resolved.CommandType -notin @("Application", "ExternalScript")) {
return $false
}
$commandToRun = $resolved.Source
$job = Start-Job -ScriptBlock {
param([string]$Cmd)
try {
& $Cmd --version *> $null
if ($LASTEXITCODE -eq 0) {
return $true
}