forked from JanDeDobbeleer/oh-my-posh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathomp.ps1
More file actions
1616 lines (1402 loc) · 67.9 KB
/
Copy pathomp.ps1
File metadata and controls
1616 lines (1402 loc) · 67.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
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
if ($null -ne (Get-Module -Name "oh-my-posh-core")) {
Remove-Module -Name "oh-my-posh-core" -Force
}
$env:VIRTUAL_ENV_DISABLE_PROMPT = 1
$env:PYENV_VIRTUALENV_DISABLE_PROMPT = 1
# Helper functions which need to be defined before the module is loaded
# See https://github.com/JanDeDobbeleer/oh-my-posh/discussions/2300
function global:Get-PoshStackCount {
$locations = Get-Location -Stack
if ($locations) {
return $locations.Count
}
return 0
}
$global:_ompJobCount = $false
$global:_ompFTCSMarks = $false
$global:_ompPoshGit = $false
$global:_ompAzure = $false
$global:_ompExecutable = ::OMP::
$global:_ompTransientPrompt = $false
$global:_ompStreaming = $false
New-Module -Name "oh-my-posh-core" -ScriptBlock {
$script:ConstrainedLanguageMode = $ExecutionContext.SessionState.LanguageMode -eq "ConstrainedLanguage"
# The persistent `oh-my-posh serve` daemon needs ProcessStartInfo.ArgumentList,
# System.Diagnostics.Process and [powershell]::Create() runspaces, none of which
# are usable/available under ConstrainedLanguage mode or on Windows PowerShell
# 5.1 (.NET Framework, no ArgumentList support). Both cases keep using the
# legacy per-prompt stream spawn.
$script:ServeSupported = -not $script:ConstrainedLanguageMode -and $PSVersionTable.PSVersion.Major -ge 6
# Async mode: state is threaded through $global:_ompAsyncInit (set by the
# trampoline installed in the profile) and consumed once here, then
# cleared so a later *sync* re-source of this same file takes the sync
# branch below. Read via Get-Variable, not a bare $global: dereference -
# a plain sync source never sets this global, and a bare read of an
# unset variable throws under Set-StrictMode.
$script:AsyncInit = [bool](Get-Variable -Name _ompAsyncInit -Scope Global -ErrorAction Ignore -ValueOnly)
$global:_ompAsyncInit = $false
# In async mode this ends up capturing whatever wraps the trampoline at
# first-draw time (e.g. another tool's prompt hook), not the true pre-omp
# prompt - $global:_ompOriginalPromptFunction (captured by the trampoline
# itself, before anything can wrap it) is authoritative there instead.
# Kept here unconditionally for the sync path.
$script:OriginalPromptFunction = $Function:prompt
$originalPSReadLineOptions = Get-PSReadLineOption
$script:OriginalContinuationPrompt = $originalPSReadLineOptions.ContinuationPrompt
$script:OriginalPromptText = $originalPSReadLineOptions.PromptText
$script:OriginalViModeIndicator = $originalPSReadLineOptions.ViModeIndicator
$script:OriginalViModeChangeHandler = $originalPSReadLineOptions.ViModeChangeHandler
$script:NoExitCode = $true
$script:ErrorCode = 0
$script:ExecutionTime = 0
$script:ShellName = "pwsh"
$script:PSVersion = $PSVersionTable.PSVersion.ToString()
$script:TransientPrompt = $false
$script:TooltipCommand = ''
$script:JobCount = 0
$script:Streaming = [hashtable]::Synchronized(@{
Process = $null
Prompt = ''
Transient = ''
State = 'NEW'
Dirty = $false
# Session-scoped `oh-my-posh serve` process state (PowerShell 6+ only).
# ServeProcess/StdIn live for the whole session; CycleId increments once
# per render request so stale records from an aborted cycle can be
# discarded by comparing against it.
CycleId = 0
ServeProcess = $null
StdIn = $null
# The serve reader runspace's PSDataCollection. It lives for the
# daemon's lifetime and only grows - records are never removed.
Output = $null
# Cursor into Output, shared by the synchronous waiter in
# Get-PoshStreamingPrompt and the async drain in the OnIdle action.
# Both run on the engine thread and never overlap (OnIdle is only
# raised while the runspace is idle), so sharing is race-free.
# Records are never removed from Output.
RecordIndex = 0
# Set by the reader runspace after each record lands in Output (and on
# EOF), so the waiter can block on it instead of sleep-polling -
# Start-Sleep quantizes to ~15.6ms Windows timer ticks, the wait
# handle wakes sub-millisecond.
Signal = $null
# Set the first time either the serve or legacy path kicks off a
# cycle; lets the shared PowerShell.OnIdle handler below know
# whether a streaming prompt cycle is active at all, regardless
# of which of the two mechanisms is driving it.
CycleStarted = $false
# Counts daemon failures (start failure, dead pipe, response
# timeout). Deliberately never reset on success: a flapping daemon
# should eventually stop taxing prompts with restarts.
FailureCount = 0
# True from the moment a wait-mode render request is (even
# partially) written until its reply is consumed or given up on.
# A wait cycle cannot be aborted daemon-side, so when the waiter
# is unwound mid-cycle (Ctrl+C), Stop-ActiveRenderCycle must kill
# the daemon instead of writing into it - see both functions.
WaitPending = $false
# Drains records the reader appended to Output: async segment
# updates and the transient refresh. Serve records carry an
# "<id>\x1f" prefix (stale cycles are discarded); legacy stream
# records are the bare payload. Engine-thread only - shared by the
# OnIdle action (which can't call module functions, hence a
# scriptblock on the state it already holds) and the prompt
# function's transient branch.
Drain = {
param($s)
$output = $s.Output
if ($null -eq $output) {
return
}
while ($s.RecordIndex -lt $output.Count) {
$record = $output[$s.RecordIndex]
$s.RecordIndex++
if (-not $record) {
continue
}
$sep = $record.IndexOf([char]0x1F)
if ($sep -ge 0) {
if ($record.Substring(0, $sep) -ne [string]$s.CycleId) {
# Stale record from an aborted/previous cycle - discard.
continue
}
$payload = $record.Substring($sep + 1)
}
else {
$payload = $record
}
# A payload prefixed with U+001E carries the transient prompt:
# cache it for the Enter/Ctrl+C key handlers, never repaint.
if ($payload -and $payload[0] -eq [char]0x1E) {
$s.Transient = $payload.Substring(1)
continue
}
if ($payload -ceq $s.Prompt) {
continue
}
$s.Prompt = $payload
$s.Dirty = $true
}
}
})
# Engine-event actions can't receive state via -MessageData (arrives as $null) and lose
# closure bindings when created inside a module function, so expose the streaming state
# globally for the OnIdle action to pick up.
$global:_ompStreamingState = $script:Streaming
$script:StreamingOnIdleJob = $null
$script:StreamingExitingJob = $null
# Wait mode: render requests carry "wait":true, the daemon resolves every
# segment before replying (print primary semantics, same records contract
# as cmd/Clink) and the PowerShell.OnIdle subscriber is never registered -
# there are no incremental records to repaint from. Used under PowerShell
# Editor Services, where registering OnIdle is what crashes the host (see
# Enable-PoshStreaming).
$script:StreamingWait = $false
$env:POWERLINE_COMMAND = "oh-my-posh"
$env:POSH_SHELL = "pwsh"
$env:POSH_SHELL_VERSION = $script:PSVersion
$env:CONDA_PROMPT_MODIFIER = ''
function Invoke-Utf8Posh {
param([string[]]$Arguments = @())
if ($script:ConstrainedLanguageMode) {
$output = Invoke-Expression "& `$global:_ompExecutable `$Arguments 2>&1"
$output -join "`n"
return
}
$Process = New-Object System.Diagnostics.Process
$StartInfo = $Process.StartInfo
$StartInfo.FileName = $global:_ompExecutable
if ($StartInfo.ArgumentList.Add) {
# ArgumentList is supported in PowerShell 6.1 and later (built on .NET Core 2.1+)
# ref-1: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.argumentlist?view=net-6.0
# ref-2: https://docs.microsoft.com/en-us/powershell/scripting/whats-new/differences-from-windows-powershell?view=powershell-7.2#net-framework-vs-net-core
$Arguments | ForEach-Object -Process { $StartInfo.ArgumentList.Add($_) }
}
else {
# escape arguments manually in lower versions, refer to https://docs.microsoft.com/en-us/previous-versions/17w5ykft(v=vs.85)
$escapedArgs = $Arguments | ForEach-Object {
# escape N consecutive backslash(es), which are followed by a double quote, to 2N consecutive ones
$s = $_ -replace '(\\+)"', '$1$1"'
# escape N consecutive backslash(es), which are at the end of the string, to 2N consecutive ones
$s = $s -replace '(\\+)$', '$1$1'
$s = $s -replace '"', '\"'
"`"$s`""
}
$StartInfo.Arguments = $escapedArgs -join ' '
}
$StartInfo.StandardErrorEncoding = $StartInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
$StartInfo.RedirectStandardError = $StartInfo.RedirectStandardInput = $StartInfo.RedirectStandardOutput = $true
$StartInfo.UseShellExecute = $false
if ($PWD.Provider.Name -eq 'FileSystem') {
if (-not (Test-Path -LiteralPath $PWD)) {
Write-Host "Unable to find the current directory, falling back to $HOME" -ForegroundColor Red
Set-Location $HOME
}
$StartInfo.WorkingDirectory = $PWD.ProviderPath
}
$StartInfo.CreateNoWindow = $true
[void]$Process.Start()
# Remove deadlock potential on Windows.
$stdoutTask = $Process.StandardOutput.ReadToEndAsync()
$stderrTask = $Process.StandardError.ReadToEndAsync()
$Process.WaitForExit()
$stderr = $stderrTask.Result.Trim()
if ($stderr) {
$Host.UI.WriteErrorLine($stderr)
}
$stdoutTask.Result
}
function Get-NonFSWD {
if ($PWD.Provider.Name -ne 'FileSystem') {
return $PWD.ToString()
}
}
function Get-TerminalWidth {
$terminalWidth = $Host.UI.RawUI.WindowSize.Width
if (-not $terminalWidth) {
return 0
}
$terminalWidth
}
function Set-TransientPrompt {
$previousOutputEncoding = [Console]::OutputEncoding
try {
$script:TransientPrompt = $true
[Console]::OutputEncoding = [Text.Encoding]::UTF8
[Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
}
catch [System.ArgumentOutOfRangeException] {
}
finally {
[Console]::OutputEncoding = $previousOutputEncoding
}
}
function Set-PoshPromptType {
if ($script:TransientPrompt -eq $true) {
$script:PromptType = "transient"
$script:TransientPrompt = $false
return
}
# for details about the trick to detect a debugging context, see these comments:
# 1) https://github.com/JanDeDobbeleer/oh-my-posh/issues/2483#issuecomment-1175761456
# 2) https://github.com/JanDeDobbeleer/oh-my-posh/issues/2502#issuecomment-1179968052
# 3) https://github.com/JanDeDobbeleer/oh-my-posh/issues/5153
if ($Host.Runspace.Debugger.InBreakpoint) {
$script:PromptType = "debug"
return
}
$script:PromptType = "primary"
if ($global:_ompJobCount) {
$script:JobCount = (Get-Job -State Running).Count
}
if ($global:_ompAzure) {
try {
$env:POSH_AZURE_SUBSCRIPTION = Get-AzContext | ConvertTo-Json
}
catch {
}
}
if ($global:_ompPoshGit) {
try {
$global:GitStatus = Get-GitStatus
$env:POSH_GIT_STATUS = $global:GitStatus | ConvertTo-Json
}
catch {
}
}
}
function Update-PoshErrorCode {
$lastHistory = Get-History -ErrorAction Ignore -Count 1
# error code should be updated only when a non-empty command is run
if (($null -eq $lastHistory) -or ($script:LastHistoryId -eq $lastHistory.Id)) {
$script:ExecutionTime = 0
$script:NoExitCode = $true
return
}
$script:NoExitCode = $false
$script:LastHistoryId = $lastHistory.Id
$script:ExecutionTime = ($lastHistory.EndExecutionTime - $lastHistory.StartExecutionTime).TotalMilliseconds
if ($script:OriginalLastExecutionStatus) {
$script:ErrorCode = 0
return
}
$invocationInfo = try {
$global:Error | Where-Object { $_.GetType().Name -eq 'ErrorRecord' } | Select-Object -First 1 -ExpandProperty InvocationInfo
}
catch {
$null
}
# Check if the error occurred in the current command scope
if ($null -ne $invocationInfo -and
$invocationInfo.HistoryId -eq $lastHistory.Id) {
$script:ErrorCode = 1
return
}
if ($script:OriginalLastExitCode -is [int] -and $script:OriginalLastExitCode -ne 0) {
# native app exit code
$script:ErrorCode = $script:OriginalLastExitCode
return
}
}
function Get-PoshPrompt {
param(
[string]$Type,
[string[]]$Arguments
)
$nonFSWD = Get-NonFSWD
$stackCount = Get-PoshStackCount
$terminalWidth = Get-TerminalWidth
Invoke-Utf8Posh @(
"print", $Type
"--save-cache"
"--shell=$script:ShellName"
"--shell-version=$script:PSVersion"
"--status=$script:ErrorCode"
"--no-status=$script:NoExitCode"
"--execution-time=$script:ExecutionTime"
"--pswd=$nonFSWD"
"--stack-count=$stackCount"
"--terminal-width=$terminalWidth"
"--job-count=$script:JobCount"
if ($Arguments) {
$Arguments
}
)
}
function Register-PoshStreamingOnIdle {
if ($null -ne $script:StreamingOnIdleJob) {
return
}
# PSReadLine anchors the prompt position when ReadLine starts, and PowerShell.OnIdle
# can only fire while ReadLine is waiting for input, i.e. after that anchor exists.
# That makes OnIdle the earliest safe point to allow redraws (State = 'RUNNING') and
# to flush updates that arrived before the anchor existed. Calling InvokePrompt()
# any earlier redraws at the previous prompt's coordinates.
#
# OnIdle is also the ONLY async consumer of streamed records. It is an
# engine-generated event on the pipeline thread: consuming records here
# instead of in a DataAdded subscription means no PSEvent is ever raised
# from a background thread. Cross-thread event delivery can re-enter the
# engine's pulse pipeline and crash the host with
# InvalidPipelineStateException ("Cannot invoke pipeline because it has
# already been invoked") under rapid prompt cycles.
$script:StreamingOnIdleJob = Register-EngineEvent -SourceIdentifier PowerShell.OnIdle -Action {
$s = $global:_ompStreamingState
# No streaming prompt cycle has ever been started (neither serve nor legacy).
if (-not $s.CycleStarted) {
return
}
if ($s.State -eq 'NEW') {
$s.State = 'RUNNING'
}
# Drain records the reader appended while idle: async segment
# updates and the transient refresh. This runs on the same thread
# as the synchronous waiter, so sharing the cursor is race-free.
& $s.Drain $s
if (-not $s.Dirty) {
return
}
$s.Dirty = $false
$previousOutputEncoding = [Console]::OutputEncoding
try {
[Console]::OutputEncoding = [Text.Encoding]::UTF8
[Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
}
catch {}
finally {
[Console]::OutputEncoding = $previousOutputEncoding
}
}
}
function Stop-StreamingProcess {
if (-not $global:_ompStreaming) {
return
}
if ($null -ne $script:Streaming.Process -and -not $script:Streaming.Process.HasExited) {
try {
$script:Streaming.Process.Kill()
}
catch {
}
}
$script:Streaming.Process = $null
$script:Streaming.State = 'NEW'
$script:Streaming.Dirty = $false
}
function Stop-ActiveRenderCycle {
# Serve mode: the daemon persists across cycles, only the in-flight
# render needs to be interrupted - write abort instead of killing anything.
if ($null -ne $script:Streaming.ServeProcess -and -not $script:Streaming.ServeProcess.HasExited) {
# Except for an abandoned wait cycle. A wait render cannot be
# interrupted: abort makes the daemon block on the in-flight
# render's completion (engine.Abort is a no-op when StreamPrimary
# never ran) and it stops reading stdin while it waits - so if
# the waiter was unwound mid-cycle (Ctrl+C), writing abort here
# and then the next request's multi-KB env blob into that daemon
# can block the engine thread on a full pipe with no deadline.
# Kill it instead; the next render restarts it fresh. Not a
# daemon fault - no failure is counted.
if ($script:StreamingWait -and $script:Streaming.WaitPending) {
try {
$script:Streaming.ServeProcess.Kill()
}
catch {
}
$script:Streaming.ServeProcess = $null
$script:Streaming.WaitPending = $false
$script:Streaming.State = 'NEW'
$script:Streaming.Dirty = $false
return
}
# The abort write is three statements - a Ctrl+C landing between
# them tears it and desyncs the protocol stream: the daemon
# blocks reading the never-written env blob and consumes the next
# request as blob records. Cover the write with the same flag the
# render writes use, so a torn (or thrown) abort routes into the
# kill branch above at the next prompt instead of hanging the
# deadline-less wait-mode waiter. Inert in streaming mode, where
# the flag is assigned $false and never read.
$script:Streaming.WaitPending = $script:StreamingWait
try {
# Every request line - even one with no env of its own - must
# be followed by a blob; a bare NUL is an empty one (see
# readEnvBlob/Get-PoshServeEnvRaw).
$script:Streaming.StdIn.WriteLine('{"command":"abort"}')
$script:Streaming.StdIn.Write([char]0)
$script:Streaming.StdIn.Flush()
$script:Streaming.WaitPending = $false
}
catch {
}
$script:Streaming.State = 'NEW'
$script:Streaming.Dirty = $false
return
}
# Legacy per-prompt process: nothing to abort, kill it outright.
Stop-StreamingProcess
}
# Chunked reader for NUL-delimited prompt records, shared by the serve
# daemon (which passes a wake signal) and the legacy per-prompt stream
# (which passes $null). Runs in its own runspace for the lifetime of the
# stream it reads.
#
# Reads in 4KB chunks and splits on NUL via [Array]::IndexOf instead of
# one $stream.ReadByte() call per byte: a gradient-heavy prompt record
# can run 1-2KB, and a PowerShell method call per byte to drain it was
# measured adding tens of ms per cycle - enough to push a spammed Enter
# past the ~33ms key-repeat interval and turn "stops instantly on
# release" into "keeps draining for seconds".
$script:StreamingReaderScript = {
param($stream, $signal)
$bufferSize = 4096
$buffer = [byte[]]::new($bufferSize)
$pending = [System.Collections.Generic.List[byte]]::new()
$appendSegment = {
param($segStart, $segEnd)
$segLen = $segEnd - $segStart
if ($segLen -le 0) {
return
}
$segment = [byte[]]::new($segLen)
[Array]::Copy($buffer, $segStart, $segment, 0, $segLen)
$pending.AddRange($segment)
}
while ($true) {
$read = $stream.Read($buffer, 0, $bufferSize)
if ($read -le 0) {
if ($pending.Count -gt 0) {
Write-Output ([Text.Encoding]::UTF8.GetString($pending.ToArray()))
}
# Wake the waiter - also on EOF, so a dying daemon triggers
# the fallback path immediately instead of after the timeout.
if ($signal) {
$signal.Set()
}
return
}
$offset = 0
while ($offset -lt $read) {
$nul = [Array]::IndexOf($buffer, [byte]0, $offset, $read - $offset)
if ($nul -lt 0) {
& $appendSegment $offset $read
$offset = $read
continue
}
& $appendSegment $offset $nul
if ($pending.Count -gt 0) {
Write-Output ([Text.Encoding]::UTF8.GetString($pending.ToArray()))
$pending.Clear()
}
if ($signal) {
$signal.Set()
}
$offset = $nul + 1
}
}
}
function Start-PoshServe {
$Process = New-Object System.Diagnostics.Process
$StartInfo = $Process.StartInfo
$StartInfo.FileName = $global:_ompExecutable
# ArgumentList is supported in PowerShell 6.1+; $script:ServeSupported already
# requires major version 6, but guard defensively like Invoke-Utf8Posh does.
if ($StartInfo.ArgumentList.Add) {
$StartInfo.ArgumentList.Add("serve")
$StartInfo.ArgumentList.Add("--shell=$script:ShellName")
}
else {
$StartInfo.Arguments = "serve --shell=$script:ShellName"
}
# IMPORTANT: BOM-less UTF-8 for stdin. [System.Text.Encoding]::UTF8
# emits a BOM preamble on the writer's first write, which would
# corrupt the first JSON request line and make the daemon silently
# drop the first render of every fresh process.
$StartInfo.StandardInputEncoding = [System.Text.UTF8Encoding]::new($false)
$StartInfo.StandardOutputEncoding = [System.Text.UTF8Encoding]::new($false)
$StartInfo.RedirectStandardInput = $true
$StartInfo.RedirectStandardOutput = $true
# stdout carries ONLY protocol records; redirect stderr too so a Go
# panic in the daemon can never spew into the user's terminal - it's
# simply discarded (not read) since we never attach a consumer to it.
$StartInfo.RedirectStandardError = $true
$StartInfo.UseShellExecute = $false
$StartInfo.CreateNoWindow = $true
if ($PWD.Provider.Name -eq 'FileSystem') {
$StartInfo.WorkingDirectory = $PWD.ProviderPath
}
try {
[void]$Process.Start()
}
catch {
return $false
}
# Drain stderr fire-and-forget: an undrained redirected pipe can fill
# up and block the daemon mid-write (e.g. an unrecovered panic's stack
# trace). The content is deliberately discarded.
$null = $Process.StandardError.ReadToEndAsync()
# Read the persistent stdout stream asynchronously for the lifetime of the session.
$output = New-Object 'System.Management.Automation.PSDataCollection[PSObject]'
$inputData = New-Object 'System.Management.Automation.PSDataCollection[PSObject]'
$inputData.Complete()
$signal = [System.Threading.ManualResetEventSlim]::new($false)
$ps = [powershell]::Create().AddScript($script:StreamingReaderScript).AddArgument($Process.StandardOutput.BaseStream).AddArgument($signal)
# There is deliberately NO DataAdded subscription on the collection:
# the reader appends from a background thread, and a PSEvent raised
# from a non-engine thread can re-enter the engine's pulse pipeline
# and crash the host (InvalidPipelineStateException) under rapid
# prompt cycles. Records are consumed exclusively on the engine
# thread: synchronously by Get-PoshStreamingPrompt's waiter, and
# asynchronously by the OnIdle action's drain.
$ps.BeginInvoke($inputData, $output) | Out-Null
$script:Streaming.ServeProcess = $Process
$script:Streaming.StdIn = $Process.StandardInput
# Fresh daemon, fresh collection: nothing consumed yet. The previous
# daemon's signal (if any) is intentionally not disposed - its reader
# may still hold a reference; the GC reclaims it.
$script:Streaming.Output = $output
$script:Streaming.RecordIndex = 0
$script:Streaming.Signal = $signal
return $true
}
function ConvertTo-PoshServeJsonString($Value) {
if ($null -eq $Value) {
return '""'
}
# Minimal, fast escaping for the flat string values we send: backslash
# and double-quote first (order matters), then control characters.
$escaped = $Value.Replace('\', '\\').Replace('"', '\"')
$escaped = $escaped -replace "`r", '\r' -replace "`n", '\n' -replace "`t", '\t'
return '"' + $escaped + '"'
}
function Get-PoshFSWD {
# Serve needs an actual filesystem path for the daemon to os.Chdir into;
# a non-filesystem provider (e.g. a registry drive) has no such path -
# let the daemon keep its previous/last-good working directory.
if ($PWD.Provider.Name -eq 'FileSystem') {
return $PWD.ProviderPath
}
return ''
}
function Get-PoshServeEnvRaw {
# The full exported environment as "KEY=VALUE\0" records, terminated
# by one extra bare NUL (an empty record) - see readEnvBlob on the
# daemon side. No escaping is needed: env values can never contain a
# NUL byte on any OS, and GetEnvironmentVariables() already returns
# each variable's real, single-string value - no array-join
# subtlety like fish's list variables to worry about here.
$sb = [System.Text.StringBuilder]::new()
foreach ($entry in [Environment]::GetEnvironmentVariables().GetEnumerator()) {
[void]$sb.Append($entry.Key).Append('=').Append($entry.Value).Append([char]0)
}
[void]$sb.Append([char]0)
return $sb.ToString()
}
function Suspend-PoshServeOnFailure {
$script:Streaming.FailureCount++
if ($script:Streaming.FailureCount -lt 3) {
return
}
# Degrade to the per-prompt stream path for the rest of the
# session - a repeatedly failing daemon must not add a restart
# plus a response timeout to every single prompt.
$script:ServeSupported = $false
# Serve is off for good, but the daemon can still be alive here (the
# empty-primary path keeps it running on purpose). Without this it
# would idle until session end while Stop-ActiveRenderCycle keeps
# writing it an abort every prompt. Ask it to quit (flushes its
# caches) and close stdin - the EOF exit signal that works even if
# the quit line is lost; the daemon's stdout EOF then releases the
# reader runspace.
if ($null -ne $script:Streaming.ServeProcess -and -not $script:Streaming.ServeProcess.HasExited) {
try {
$script:Streaming.StdIn.WriteLine('{"command":"quit"}')
$script:Streaming.StdIn.Write([char]0)
$script:Streaming.StdIn.Flush()
$script:Streaming.StdIn.Close()
}
catch {
}
}
$script:Streaming.ServeProcess = $null
}
function Get-PoshStreamingPromptFallback {
# Daemon-failure fallback. Wait mode must never reach the legacy
# per-prompt stream: it registers PowerShell.OnIdle (the exact hazard
# wait mode exists to avoid under PSES) and depends on it to repaint
# everything past its first record.
if ($script:StreamingWait) {
# No daemon rendered this cycle, and two of the callers (the
# ServeSupported guard and a failed daemon start) bail out before
# the per-cycle transient reset - drop the previous cycle's
# cached transient so Enter renders a fresh one instead of
# replaying stale context. The legacy branch resets it itself.
$script:Streaming.Transient = ''
return Get-PoshPrompt 'primary'
}
Get-PoshStreamingPromptLegacy
}
function Get-PoshStreamingPrompt {
if (-not $script:ServeSupported) {
return Get-PoshStreamingPromptFallback
}
if (-not $script:StreamingWait) {
Register-PoshStreamingOnIdle
}
# The reader's record collection only grows - both consumers key off
# add-time indices, so in-place trimming would corrupt their cursors.
# Recycle the daemon once the collection gets large: one slower prompt
# every few thousand beats unbounded growth in long-lived sessions.
if ($null -ne $script:Streaming.Output -and $script:Streaming.Output.Count -ge 4096) {
try {
$script:Streaming.StdIn.WriteLine('{"command":"quit"}')
$script:Streaming.StdIn.Write([char]0)
$script:Streaming.StdIn.Flush()
}
catch {
}
$script:Streaming.ServeProcess = $null
}
if ($null -eq $script:Streaming.ServeProcess -or $script:Streaming.ServeProcess.HasExited) {
if (-not (Start-PoshServe)) {
Suspend-PoshServeOnFailure
return Get-PoshStreamingPromptFallback
}
}
$script:Streaming.CycleId++
$script:Streaming.Transient = ''
$script:Streaming.CycleStarted = $true
$json = '{' +
'"command":"render"' +
',"id":' + $script:Streaming.CycleId +
',"shell":' + (ConvertTo-PoshServeJsonString $script:ShellName) +
',"shell-version":' + (ConvertTo-PoshServeJsonString $script:PSVersion) +
',"status":' + [int]$script:ErrorCode +
',"no-status":' + $(if ($script:NoExitCode) { 'true' } else { 'false' }) +
',"execution-time":' + $script:ExecutionTime +
',"pwd":' + (ConvertTo-PoshServeJsonString (Get-PoshFSWD)) +
',"pswd":' + (ConvertTo-PoshServeJsonString (Get-NonFSWD)) +
',"stack-count":' + (Get-PoshStackCount) +
',"terminal-width":' + (Get-TerminalWidth) +
',"job-count":' + $script:JobCount +
',"wait":' + $(if ($script:StreamingWait) { 'true' } else { 'false' }) +
',"cleared":false' +
'}'
# The full environment follows the header, unconditionally - see
# Get-PoshServeEnvRaw. Both writes go through the same StdIn, so they
# can never interleave with another request.
$envRaw = Get-PoshServeEnvRaw
# From here until the reply is consumed or given up on, the daemon
# owns a wait cycle this client might abandon: Ctrl+C can unwind the
# waiter at any point, and even a partially written request poisons
# the protocol stream. Stop-ActiveRenderCycle keys off this to kill a
# possibly-wedged daemon instead of writing into it.
$script:Streaming.WaitPending = $script:StreamingWait
try {
$script:Streaming.StdIn.WriteLine($json)
$script:Streaming.StdIn.Write($envRaw)
$script:Streaming.StdIn.Flush()
}
catch {
# The daemon died between the health check above and this write - restart once.
# Kill before dropping the reference (mirroring the death path
# below), so a process with a broken stdin but a live body can
# never be leaked.
try {
$script:Streaming.ServeProcess.Kill()
}
catch {
}
$script:Streaming.ServeProcess = $null
Suspend-PoshServeOnFailure
# A third strike just disabled serve for the session - don't
# start a daemon that nothing would ever talk to again.
if (-not $script:ServeSupported -or -not (Start-PoshServe)) {
$script:Streaming.WaitPending = $false
return Get-PoshStreamingPromptFallback
}
try {
$script:Streaming.StdIn.WriteLine($json)
$script:Streaming.StdIn.Write($envRaw)
$script:Streaming.StdIn.Flush()
}
catch {
# The legacy path repoints $script:Streaming.Output at its own
# collection - a live daemon must not linger with an orphaned one.
try {
$script:Streaming.ServeProcess.Kill()
}
catch {
}
$script:Streaming.ServeProcess = $null
$script:Streaming.WaitPending = $false
return Get-PoshStreamingPromptFallback
}
}
# Wait for the first primary record of THIS cycle by scanning the
# reader's PSDataCollection with the waiter's PRIVATE cursor. The
# DataAdded action cannot be relied on here (whether it fires during
# this loop depends on the calling context) and must not be raced
# against either - records stay in the collection, so this scan works
# regardless of whether the action also processed them, and the action
# dedupes on unchanged content. Between scans, block on the reader's
# signal (sub-millisecond wake) rather than Start-Sleep (~15.6ms timer
# tick). The bounded Wait keeps the Stopwatch timeout authoritative,
# and re-scanning after every wake makes lost wakeups impossible:
# a record landing after a scan leaves the signal set, so the next
# Wait returns immediately.
$s = $script:Streaming
$output = $s.Output
$signal = $s.Signal
$firstPrompt = $null
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
# Streaming keeps a 2s deadline: its first record is a fast paint
# that a healthy daemon produces near-instantly, so a longer silence
# means the daemon is gone. A wait render instead resolves every
# segment before its first record - it legitimately takes as long as
# print primary would, and print primary has no deadline at all (only
# opt-in per-segment timeouts) - so wait mode blocks like Clink does
# and treats daemon death as the only failure: the reader EOFs and
# sets the signal, one grace pass drains records the dying pipe still
# buffered, then the fallback takes over. A daemon that survives but
# never replies (a cycle-setup panic) blocks like a hung print
# primary would - Ctrl+C unwinds this waiter, and the next prompt
# then kills the daemon via the WaitPending flag.
$serveExited = $false
while ($null -eq $firstPrompt) {
while ($s.RecordIndex -lt $output.Count) {
$record = $output[$s.RecordIndex]
$s.RecordIndex++
if (-not $record) {
continue
}
$sep = $record.IndexOf([char]0x1F)
if ($sep -lt 0) {
continue
}
$id = $record.Substring(0, $sep)
if ($id -ne [string]$s.CycleId) {
# Stale record from an aborted/previous cycle - discard.
continue
}
$payload = $record.Substring($sep + 1)
if ($payload -and $payload[0] -eq [char]0x1E) {
$s.Transient = $payload.Substring(1)
continue
}
# Keep scanning instead of stopping at the primary: records
# that already arrived in the same burst (typically the
# transient) are consumed for free, without waiting. Later
# records are drained by the OnIdle action.
$s.Prompt = $payload
$firstPrompt = $payload
}
if ($null -ne $firstPrompt) {
break
}
if ($script:StreamingWait) {
if ($s.ServeProcess.HasExited) {
if ($serveExited) {
break
}
$serveExited = $true
}
}
elseif ($stopwatch.ElapsedMilliseconds -ge 2000) {
break
}
[void]$signal.Wait(100)
$signal.Reset()
}
# However this cycle ended, the daemon no longer holds a request this
# client walked away from - the next Stop-ActiveRenderCycle can use
# the regular abort write again.
$s.WaitPending = $false
if ($null -eq $firstPrompt) {
# Streaming: the daemon went silent past its deadline. Wait mode:
# the daemon died mid-render. Kill it (a no-op on a corpse,
# load-bearing for a silent-but-alive one) before counting the
# failure, then fall back for this cycle.
try {
$s.ServeProcess.Kill()
}
catch {
}
$s.ServeProcess = $null
Suspend-PoshServeOnFailure
return Get-PoshStreamingPromptFallback
}
# An empty primary is the daemon's failed-render signal: a panic in
# the primary render is recovered and answered with "" plus an empty
# transient rather than a missing reply, and the daemon lives on. (A
# panic during the transient render still delivers a real primary; a
# panic during cycle setup emits nothing at all and is handled as a
# silent daemon above.) Same contract handling as Clink: count the
# failure and fall back to a one-shot render for this prompt, without
# killing the daemon.
if ($script:StreamingWait -and $firstPrompt -eq '') {
Suspend-PoshServeOnFailure
return Get-PoshStreamingPromptFallback
}
return $firstPrompt
}
function Get-PoshStreamingPromptLegacy {
Register-PoshStreamingOnIdle
# State stays 'NEW' until the first OnIdle event confirms PSReadLine has rendered the initial prompt.
$script:Streaming.Process = New-Object System.Diagnostics.Process
$StartInfo = $script:Streaming.Process.StartInfo
$StartInfo.FileName = $global:_ompExecutable
# The transient prompt for this cycle streams in alongside the primary
# prompt updates, invalidate the previous cycle's version.
$script:Streaming.Transient = ''
$script:Streaming.CycleStarted = $true
$Arguments = @(
"stream"
"--save-cache"
"--shell=$script:ShellName"
"--shell-version=$script:PSVersion"
"--status=$script:ErrorCode"
"--no-status=$script:NoExitCode"
"--execution-time=$script:ExecutionTime"
"--pswd=$(Get-NonFSWD)"
"--stack-count=$(Get-PoshStackCount)"
"--terminal-width=$(Get-TerminalWidth)"
"--job-count=$script:JobCount"
)
if ($StartInfo.ArgumentList.Add) {
$Arguments | ForEach-Object -Process { $StartInfo.ArgumentList.Add($_) }
}
else {
# escape arguments manually in lower versions, refer to https://docs.microsoft.com/en-us/previous-versions/17w5ykft(v=vs.85)
$escapedArgs = $Arguments | ForEach-Object {
# escape N consecutive backslash(es), which are followed by a double quote, to 2N consecutive ones
$s = $_ -replace '(\\+)"', '$1$1"'
# escape N consecutive backslash(es), which are at the end of the string, to 2N consecutive ones
$s = $s -replace '(\\+)$', '$1$1'
$s = $s -replace '"', '\"'
"`"$s`""