-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjl.ps1
More file actions
3470 lines (3066 loc) · 127 KB
/
Copy pathjl.ps1
File metadata and controls
3470 lines (3066 loc) · 127 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
param(
[string]$AppUrl = "http://127.0.0.1:8000"
)
$ErrorActionPreference = "Stop"
# The dashboard owns the console buffer. PowerShell progress (including module
# auto-loading and HTTP probes) saves/restores cells through the legacy console
# API, losing their ANSI RGB colors. Disable it before any cmdlet can draw it.
$ProgressPreference = "SilentlyContinue"
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
$FinalConfigPath = Join-Path $Root "config.py"
$FirstRunConfigPath = Join-Path $Root ".config.py.first-run"
$ConfigPath = $FinalConfigPath
$ConfigExamplePath = Join-Path $Root "config.example.py"
$LauncherDir = Join-Path $Root ".jin_launcher"
$RuntimeDir = Join-Path $Root ".jin_runtime"
$UvDir = Join-Path $RuntimeDir "uv"
$UvExe = Join-Path $UvDir "uv.exe"
$ManagedPythonDir = Join-Path $RuntimeDir "python"
$UvCacheDir = Join-Path $RuntimeDir "uv-cache"
$ManagedPythonVersion = "3.12"
$UvVersion = "0.12.19"
$LlamaBuild = "b11112"
$LlamaCudaVersion = "12.4"
$LlamaDir = Join-Path $RuntimeDir "llama"
$LlamaServerExe = Join-Path $LlamaDir "llama-server.exe"
$LlamaRuntimeMarker = Join-Path $LlamaDir ".jin_llama_runtime"
$LlamaMainAsset = "llama-$LlamaBuild-bin-win-cuda-$LlamaCudaVersion-x64.zip"
$LlamaCudaAsset = "cudart-llama-bin-win-cuda-$LlamaCudaVersion-x64.zip"
$LlamaMainSha256 = "f43f62912ef90878f4a1612066c6390fb0bd3d39c4060749e959ca2fdd316316"
$LlamaCudaSha256 = "8c79a9b226de4b3cacfd1f83d24f962d0773be79f1e7b75c6af4ded7e32ae1d6"
$EmbeddedModelsDir = Join-Path $RuntimeDir "models"
$DefaultEmbeddedModelRepo = "lmstudio-community/gemma-4-E4B-it-GGUF"
$DefaultEmbeddedModelFile = "gemma-4-E4B-it-Q4_K_M.gguf"
$DefaultEmbeddedModelPath = Join-Path $EmbeddedModelsDir $DefaultEmbeddedModelFile
$DefaultEmbeddedModelMarker = Join-Path $EmbeddedModelsDir ".jin_default_model"
$DefaultEmbeddedModelUrl = "https://huggingface.co/lmstudio-community/gemma-4-E4B-it-GGUF/resolve/main/gemma-4-E4B-it-Q4_K_M.gguf?download=true"
$DefaultEmbeddedModelSha256 = "0ffb122c8b6921f13cbc34186e052524d0b5803b17f4867b7197a561400b3770"
$DefaultEmbeddedModelLabel = "Gemma 4 E4B Q4_K_M"
$DefaultEmbeddedMmprojFile = "mmproj-gemma-4-E4B-it-BF16.gguf"
$DefaultEmbeddedMmprojPath = Join-Path $EmbeddedModelsDir $DefaultEmbeddedMmprojFile
$DefaultEmbeddedMmprojMarker = Join-Path $EmbeddedModelsDir ".jin_default_mmproj"
$DefaultEmbeddedMmprojUrl = "https://huggingface.co/lmstudio-community/gemma-4-E4B-it-GGUF/resolve/main/mmproj-gemma-4-E4B-it-BF16.gguf?download=true"
$DefaultEmbeddedMmprojSha256 = "bdfc4935857658dfdc8d1adebfa3897c2fec8b3323410f4f73ade36d6efa02be"
$DefaultEmbeddedMmprojLabel = "Gemma 4 E4B vision projector"
$EmbeddedBrainHost = "127.0.0.1"
$EmbeddedBrainPort = 12345
$EmbeddedBrainBaseUrl = "http://$EmbeddedBrainHost`:$EmbeddedBrainPort"
$LmStudioBaseUrl = "http://127.0.0.1:1234"
$EmbeddedBrainModelId = "google/gemma-4-e4b"
$EmbeddedBrainDefaultContext = 16384
$EmbeddedBrainMaxContext = 32768
$EmbeddedBrainContextPath = Join-Path $LauncherDir "brain_context.txt"
$script:EmbeddedBrainContext = $EmbeddedBrainDefaultContext
if (Test-Path -LiteralPath $EmbeddedBrainContextPath) {
try {
$savedEmbeddedContext = [int](Get-Content -Raw -LiteralPath $EmbeddedBrainContextPath)
if ($savedEmbeddedContext -in @(4096, 8192, 16384, 32768)) {
$script:EmbeddedBrainContext = $savedEmbeddedContext
}
}
catch {}
}
$LlamaStdOutPath = Join-Path $LauncherDir "brain.stdout.log"
$LlamaStdErrPath = Join-Path $LauncherDir "brain.stderr.log"
$StdOutPath = Join-Path $LauncherDir "backend.stdout.log"
$StdErrPath = Join-Path $LauncherDir "backend.stderr.log"
$LauncherMutex = $null
# Lock only this JIN installation. A single global mutex made a launcher from
# another folder silently kill clean-room / first-run tests.
$rootMutexBytes = [System.Text.Encoding]::UTF8.GetBytes(
([System.IO.Path]::GetFullPath($Root)).TrimEnd('\').ToLowerInvariant()
)
$rootMutexHasher = [System.Security.Cryptography.SHA256]::Create()
try {
$rootMutexHash = [System.BitConverter]::ToString(
$rootMutexHasher.ComputeHash($rootMutexBytes)
).Replace("-", "").Substring(0, 16)
}
finally {
$rootMutexHasher.Dispose()
}
$LauncherMutexName = "Global\JINCoreLauncher_$rootMutexHash"
$script:PythonExe = ""
$script:BackendProcess = $null
$script:BackendOwned = $false
$script:LlamaProcess = $null
$script:LlamaOwned = $false
$script:BrainIsEmbedded = $true
$script:BrowserOpened = $false
$script:SwitchJob = $null
$script:SwitchRole = ""
$script:SwitchModel = ""
$script:SwitchContext = 0
$script:PendingContextApply = $null
$script:ContextMode = $false
$script:ContextRole = ""
$script:ContextModel = ""
$script:ContextOptions = @()
$script:ContextIndex = 0
$script:AsyncKeyDown = @{}
$script:KeyRepeatState = @{}
$script:DashboardDirty = $true
$script:PrevChars = $null
$script:PrevCols = $null
$script:PrevW = 0
$script:PrevH = 0
$script:StdOutPosition = 0L
$script:StdErrPosition = 0L
$script:Events = New-Object System.Collections.ArrayList
$script:RuntimeMessage = "INITIALIZING COGNITIVE RUNTIME"
$script:BrainTemperature = "?"
$script:ServiceTemperature = "?"
$script:RuntimeLogsEnabled = "?"
$script:BootMode = $true
$script:BootStarted = $false
$script:BootTasks = [ordered]@{}
$script:BootDownload = $null
$script:ConfigExistedAtLaunch = $false
$script:FirstRunLmStudio = $false
$script:FirstRunLmStudioRuntime = $null
$script:LauncherInitializing = $false
$script:BootTopPadding = 2
$script:BootPrevText = @()
$script:BootPrevColor = @()
$script:BootPrevWidth = 0
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
try { [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false) } catch {}
Add-Type @"
using System;
using System.Runtime.InteropServices;
public static class JinConsoleVT {
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
public static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll")]
public static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
[DllImport("kernel32.dll")]
public static extern bool FlushConsoleInputBuffer(IntPtr hConsoleInput);
[DllImport("kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
[DllImport("user32.dll", SetLastError=true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError=true)]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError=true)]
private static extern bool SetWindowPos(
IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public static void DisableResize() {
IntPtr hWnd = GetConsoleWindow();
if (hWnd == IntPtr.Zero) return;
const int GWL_STYLE = -16;
const int WS_SIZEBOX = 0x00040000;
const int WS_MAXIMIZEBOX = 0x00010000;
const uint SWP_NOSIZE = 0x0001;
const uint SWP_NOMOVE = 0x0002;
const uint SWP_NOZORDER = 0x0004;
const uint SWP_FRAMECHANGED = 0x0020;
int style = GetWindowLong(hWnd, GWL_STYLE);
style &= ~WS_SIZEBOX;
style &= ~WS_MAXIMIZEBOX;
SetWindowLong(hWnd, GWL_STYLE, style);
SetWindowPos(hWnd, IntPtr.Zero, 0, 0, 0, 0,
SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
}
"@
$h = [JinConsoleVT]::GetStdHandle(-11)
[uint32]$consoleMode = 0
if ([JinConsoleVT]::GetConsoleMode($h, [ref]$consoleMode)) {
[void][JinConsoleVT]::SetConsoleMode($h, ($consoleMode -bor 0x0004))
}
# Keep ConHost from entering QuickEdit selection mode and swallowing navigation
# keys. Some Windows PowerShell 5.1 hosts also report KeyAvailable=false for
# arrow keys, so the launcher has a focused-window Win32 fallback below.
$inputHandle = [JinConsoleVT]::GetStdHandle(-10)
[uint32]$inputMode = 0
if ([JinConsoleVT]::GetConsoleMode($inputHandle, [ref]$inputMode)) {
$inputMode = ($inputMode -bor 0x0080) -band (-bnot 0x0040)
[void][JinConsoleVT]::SetConsoleMode($inputHandle, $inputMode)
}
# Clear stale key events once at startup. Do NOT flush on every input poll:
# doing so makes held/navigation keys feel sticky in Windows PowerShell 5.1.
try { [void][JinConsoleVT]::FlushConsoleInputBuffer($inputHandle) } catch {}
# The launcher UI is designed around a fixed 92x55 canvas. Remove the sizing
# frame and maximize button after the BAT has applied that console geometry so
# accidental drags cannot corrupt the dashboard layout.
try { [JinConsoleVT]::DisableResize() } catch {}
$esc = [char]27
$ansi = @(
"$esc[38;2;8;15;18m", # 0 almost black teal
"$esc[38;2;27;72;78m", # 1 dim teal
"$esc[38;2;36;112;120m", # 2 teal
"$esc[38;2;47;175;185m", # 3 cyan
"$esc[38;2;105;238;241m", # 4 bright cyan
"$esc[38;2;61;111;170m", # 5 blue
"$esc[38;2;218;151;65m", # 6 amber
"$esc[38;2;108;126;132m", # 7 gray
"$esc[38;2;191;210;213m", # 8 light
"$esc[38;2;216;83;83m", # 9 red
"$esc[38;2;86;191;133m" # 10 green
)
$reset = "$esc[0m"
$hideCursor = "$esc[?25l"
$showCursor = "$esc[?25h"
$clear = "$esc[2J$esc[H"
function Initialize-BootTasks {
if ($script:BootTasks.Count -gt 0) { return }
foreach ($spec in @(
[pscustomobject]@{ Key = "CONFIG"; Group = "1. CONFIG"; Title = "Load JIN configuration"; State = "PENDING"; Text = "waiting" }
[pscustomobject]@{ Key = "PYTHON"; Group = "1. CONFIG"; Title = "Prepare private Python runtime"; State = "PENDING"; Text = "waiting" }
[pscustomobject]@{ Key = "LLAMA"; Group = "2. SETUP"; Title = "Install llama.cpp runtime"; State = "PENDING"; Text = "waiting" }
[pscustomobject]@{ Key = "MODEL"; Group = "2. SETUP"; Title = "Install Gemma 4 E4B model"; State = "PENDING"; Text = "waiting" }
[pscustomobject]@{ Key = "BRAIN"; Group = "3. BRAIN"; Title = "Start local Gemma brain"; State = "PENDING"; Text = "waiting" }
[pscustomobject]@{ Key = "SERVICE"; Group = "3. BRAIN"; Title = "Check optional Service"; State = "PENDING"; Text = "waiting" }
[pscustomobject]@{ Key = "APP"; Group = "4. APP"; Title = "Start JIN backend"; State = "PENDING"; Text = "waiting" }
)) {
$script:BootTasks[$spec.Key] = [pscustomobject]@{
Key = $spec.Key
Group = $spec.Group
Title = $spec.Title
State = $spec.State
Text = $spec.Text
}
}
}
function Get-BootTaskVisual {
param([string]$State)
switch ($State) {
"OK" { return [pscustomobject]@{ Marker = "[x]"; Color = 10 } }
"WARN" { return [pscustomobject]@{ Marker = "[!]"; Color = 6 } }
"ERROR" { return [pscustomobject]@{ Marker = "[x]"; Color = 9 } }
"WORK" { return [pscustomobject]@{ Marker = "[>]"; Color = 4 } }
default { return [pscustomobject]@{ Marker = "[ ]"; Color = 7 } }
}
}
function Get-BootSectionDoneCount {
param([string]$Group)
$items = @($script:BootTasks.Values | Where-Object { $_.Group -eq $Group -and ($_.Key -ne 'SERVICE' -or $script:ServiceConfigured) })
if ($items.Count -eq 0) { return "0/0" }
$done = @($items | Where-Object { $_.State -eq "OK" }).Count
return "$done/$($items.Count)"
}
function Format-BootDownloadText {
param(
[string]$DisplayName,
[long]$Downloaded,
[long]$Total,
[double]$BytesPerSecond = 0,
[int]$BarWidth = 22
)
$downloadedText = Format-DownloadBytes $Downloaded
$rateText = Format-DownloadRate $BytesPerSecond
if ($Total -gt 0) {
$percent = [Math]::Max(0, [Math]::Min(100, [Math]::Floor(($Downloaded * 100.0) / $Total)))
$filled = [int][Math]::Floor(($percent * $BarWidth) / 100.0)
$bar = ("#" * $filled) + ("-" * ($BarWidth - $filled))
$sizeText = "$downloadedText / $(Format-DownloadBytes $Total)"
return [pscustomobject]@{
Title = $DisplayName
Progress = ("[{0}] {1,3}% {2,-11} {3}" -f $bar, $percent, $rateText, $sizeText)
}
}
$bar = ("-" * $BarWidth)
return [pscustomobject]@{
Title = $DisplayName
Progress = ("[{0}] --% {1,-11} {2}" -f $bar, $rateText, $downloadedText)
}
}
function Get-BootHintLines {
$lines = New-Object System.Collections.Generic.List[string]
if ($script:BootDownload -ne $null) {
[void]$lines.Add('Please wait. JIN is downloading and verifying the required local runtime.')
}
elseif ($script:BootTasks.Contains('BRAIN') -and $script:BootTasks['BRAIN'].State -eq 'WORK') {
[void]$lines.Add('Starting the downloaded Gemma model locally. No external model app is required.')
}
return ,$lines.ToArray()
}
function Render-BootScreen {
if (-not $script:BootMode) { return }
Start-BootScreen
Initialize-BootTasks
$width = [Math]::Max(92, [Console]::WindowWidth)
$usable = $width - 2
$lines = New-Object System.Collections.Generic.List[object]
$groups = @('1. CONFIG', '2. SETUP', '3. BRAIN', '4. APP')
for ($i = 0; $i -lt $script:BootTopPadding; $i++) {
[void]$lines.Add([pscustomobject]@{ Text = ''; Color = 8 })
}
[void]$lines.Add([pscustomobject]@{ Text = ' [ JIN CORE ENGINE // LAUNCHER ]'; Color = 8 })
[void]$lines.Add([pscustomobject]@{ Text = ''; Color = 8 })
[void]$lines.Add([pscustomobject]@{ Text = ' FIRST-RUN CHECKLIST'; Color = 4 })
[void]$lines.Add([pscustomobject]@{ Text = ''; Color = 8 })
foreach ($group in $groups) {
$countText = Get-BootSectionDoneCount $group
[void]$lines.Add([pscustomobject]@{ Text = (' ' + $group + ' [' + $countText + ']'); Color = 3 })
foreach ($task in @($script:BootTasks.Values | Where-Object { $_.Group -eq $group })) {
if ($task.Key -eq 'SERVICE' -and -not $script:ServiceConfigured) { continue }
$visual = Get-BootTaskVisual $task.State
$title = $task.Title
$text = $task.Text
$maxText = [Math]::Max(12, $usable - 8 - $title.Length - 3)
if ($text.Length -gt $maxText) {
$text = $text.Substring(0, [Math]::Max(1, $maxText - 1)) + '…'
}
$dots = '.' * [Math]::Max(2, $usable - 8 - $title.Length - $text.Length)
$line = (' {0} {1} {2} {3}' -f $visual.Marker, $title, $dots, $text)
[void]$lines.Add([pscustomobject]@{ Text = $line; Color = $visual.Color })
}
[void]$lines.Add([pscustomobject]@{ Text = ''; Color = 8 })
}
if ($script:BootDownload -ne $null) {
$dl = Format-BootDownloadText -DisplayName $script:BootDownload.DisplayName -Downloaded $script:BootDownload.Downloaded -Total $script:BootDownload.Total -BytesPerSecond $script:BootDownload.BytesPerSecond
[void]$lines.Add([pscustomobject]@{ Text = ' ACTIVE DOWNLOAD'; Color = 6 })
[void]$lines.Add([pscustomobject]@{ Text = (' ' + $dl.Title); Color = 8 })
[void]$lines.Add([pscustomobject]@{ Text = (' ' + $dl.Progress); Color = 6 })
[void]$lines.Add([pscustomobject]@{ Text = ''; Color = 8 })
}
foreach ($hint in @(Get-BootHintLines)) {
[void]$lines.Add([pscustomobject]@{ Text = (' ' + $hint); Color = 7 })
}
# Boot progress can update several times per second. Never clear/repaint the
# whole console here: on Windows that produces a very visible flash. Build
# the desired frame, compare it with the previous one and write only rows
# that actually changed. During a download this normally updates one row.
$currentText = New-Object System.Collections.Generic.List[string]
$currentColor = New-Object System.Collections.Generic.List[int]
foreach ($entry in $lines) {
$lineText = [string]$entry.Text
if ($lineText.Length -gt $usable) { $lineText = $lineText.Substring(0, $usable) }
[void]$currentText.Add($lineText.PadRight($usable))
[void]$currentColor.Add([int]$entry.Color)
}
$previousCount = @($script:BootPrevText).Count
$renderCount = [Math]::Max($currentText.Count, $previousCount)
$frame = New-Object System.Text.StringBuilder
[void]$frame.Append($hideCursor)
for ($i = 0; $i -lt $renderCount; $i++) {
$newText = if ($i -lt $currentText.Count) { $currentText[$i] } else { ''.PadRight($usable) }
$newColor = if ($i -lt $currentColor.Count) { $currentColor[$i] } else { 8 }
$oldText = if ($i -lt $previousCount) { [string]$script:BootPrevText[$i] } else { $null }
$oldColor = if ($i -lt @($script:BootPrevColor).Count) { [int]$script:BootPrevColor[$i] } else { -1 }
if ($script:BootPrevWidth -ne $usable -or $newText -ne $oldText -or $newColor -ne $oldColor) {
$row = $i + 1
[void]$frame.Append("$esc[$row;1H")
[void]$frame.Append("$esc[2K")
[void]$frame.Append($ansi[$newColor])
[void]$frame.Append($newText)
[void]$frame.Append($reset)
}
}
if ($frame.Length -gt $hideCursor.Length) {
[Console]::Write($frame.ToString())
}
$script:BootPrevText = @($currentText.ToArray())
$script:BootPrevColor = @($currentColor.ToArray())
$script:BootPrevWidth = $usable
}
function Start-BootScreen {
if ($script:BootStarted) { return }
$script:BootStarted = $true
try { [Console]::CursorVisible = $false } catch {}
try { [Console]::Clear() } catch { try { Clear-Host } catch {} }
$script:BootPrevText = @()
$script:BootPrevColor = @()
$script:BootPrevWidth = 0
[Console]::Write($hideCursor)
}
function Write-BootLine {
param(
[string]$Label,
[string]$Text,
[ValidateSet("WORK", "OK", "WARN", "ERROR")]
[string]$State = "WORK"
)
if (-not $script:BootMode) { return }
Start-BootScreen
Initialize-BootTasks
if (-not $script:BootTasks.Contains($Label)) {
$script:BootTasks[$Label] = [pscustomobject]@{
Key = $Label
Group = '4. APP'
Title = $Label
State = 'PENDING'
Text = 'waiting'
}
}
$task = $script:BootTasks[$Label]
$task.State = $State
$task.Text = $Text
Render-BootScreen
}
function Add-Event {
param(
[string]$Text,
[byte]$Color = 7
)
if ([string]::IsNullOrWhiteSpace($Text)) { return }
[void]$script:Events.Add([pscustomobject]@{
Text = $Text.Trim()
Color = $Color
})
while ($script:Events.Count -gt 80) {
$script:Events.RemoveAt(0)
}
$script:DashboardDirty = $true
}
function Fail-WithMessage {
param([string]$Message)
throw $Message
}
function Import-DotEnv {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) { return }
foreach ($line in [System.IO.File]::ReadAllLines($Path)) {
$candidate = $line.Trim()
if ($candidate.Length -eq 0 -or $candidate.StartsWith("#")) { continue }
if ($candidate.StartsWith("export ", [System.StringComparison]::OrdinalIgnoreCase)) {
$candidate = $candidate.Substring(7).TrimStart()
}
$separatorIndex = $candidate.IndexOf("=")
if ($separatorIndex -le 0) { continue }
$name = $candidate.Substring(0, $separatorIndex).Trim()
$value = $candidate.Substring($separatorIndex + 1).Trim()
if ($name -notmatch '^[A-Za-z_][A-Za-z0-9_]*$') { continue }
if ($value.Length -ge 2 -and (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
)) {
$value = $value.Substring(1, $value.Length - 2)
}
if ($null -eq [Environment]::GetEnvironmentVariable($name, "Process")) {
[Environment]::SetEnvironmentVariable($name, $value, "Process")
}
}
}
function Normalize-BaseUrl {
param([string]$BaseUrl)
if ($null -eq $BaseUrl) { return "" }
return $BaseUrl.Trim().TrimEnd("/")
}
function Ensure-JinConfig {
if (Test-Path -LiteralPath $ConfigPath) { return }
if (-not (Test-Path -LiteralPath $ConfigExamplePath)) {
Fail-WithMessage "Cannot find config.py or config.example.py."
}
Copy-Item -LiteralPath $ConfigExamplePath -Destination $ConfigPath
Add-Event "CONFIG prepared configuration from template" 3
}
function Get-PythonConfigValue {
param([string]$Name)
if (-not (Test-Path -LiteralPath $ConfigPath)) { return $null }
$content = Get-Content -Raw -LiteralPath $ConfigPath
$match = [regex]::Match($content, "(?m)^\s*$Name\s*=\s*(?<value>.*?)(?:\s+#.*)?$")
if (-not $match.Success) { return $null }
$rawValue = $match.Groups["value"].Value.Trim()
if ($rawValue -match '^"(.*)"$') { return $Matches[1] }
if ($rawValue -match "^'(.*)'$") { return $Matches[1] }
if ($rawValue -in @("None", '$null')) { return "" }
return $rawValue
}
function Get-PositiveIntValue {
param(
$Object,
[string[]]$Names
)
if ($null -eq $Object) { return 0 }
foreach ($name in $Names) {
if ($Object.PSObject.Properties.Name -contains $name) {
try {
$value = [long]$Object.$name
if ($value -gt 0) { return [int]$value }
}
catch {}
}
}
return 0
}
function Get-LoadedContextFromModelItem {
param($Item)
if ($null -eq $Item) { return 0 }
if ($Item.PSObject.Properties.Name -contains "loaded_instances") {
foreach ($instance in @($Item.loaded_instances)) {
if ($null -eq $instance) { continue }
$value = Get-PositiveIntValue $instance @(
"loaded_context_length",
"context_length",
"context_window",
"n_ctx",
"num_ctx"
)
if ($value -gt 0) { return $value }
if (
$instance.PSObject.Properties.Name -contains "config" -and
$null -ne $instance.config
) {
$value = Get-PositiveIntValue $instance.config @(
"loaded_context_length",
"context_length",
"context_window",
"n_ctx",
"num_ctx"
)
if ($value -gt 0) { return $value }
}
}
}
return 0
}
function Format-ContextTokens {
param([int]$Value)
if ($Value -le 0) { return "?" }
if (($Value % 1048576) -eq 0) {
return ([int]($Value / 1048576)).ToString() + "M"
}
if (($Value % 1024) -eq 0) {
return ([int]($Value / 1024)).ToString() + "K"
}
return [string]$Value
}
function Get-ContextOptions {
param([int]$MaxContext)
if ($MaxContext -le 0) { return @() }
$values = New-Object System.Collections.ArrayList
$value = 4096
while ($value -le $MaxContext -and $value -gt 0) {
[void]$values.Add([int]$value)
if ($value -gt 1073741823) { break }
$value = $value * 2
}
if ($values.Count -eq 0 -or [int]$values[$values.Count - 1] -ne $MaxContext) {
[void]$values.Add([int]$MaxContext)
}
return @($values | Sort-Object -Unique)
}
function Set-PythonConfigValue {
param(
[string]$Name,
[object]$Value
)
$content = Get-Content -Raw -LiteralPath $ConfigPath
if ($Value -is [bool]) {
$renderedValue = if ($Value) { "True" } else { "False" }
}
elseif ($Value -is [int] -or $Value -is [double]) {
$renderedValue = [string]$Value
}
else {
$escaped = ([string]$Value).Replace("\", "\\").Replace('"', '\"')
$renderedValue = '"' + $escaped + '"'
}
$pattern = "(?m)^\s*$Name\s*=.*$"
$replacement = "$Name = $renderedValue"
$safeReplacement = $replacement.Replace('$', '$$')
if ([regex]::IsMatch($content, $pattern)) {
$content = [regex]::Replace($content, $pattern, $safeReplacement, 1)
}
else {
$content = $content.TrimEnd() + "`r`n`r`n" + $replacement + "`r`n"
}
Set-Content -LiteralPath $ConfigPath -Value $content -Encoding UTF8
}
function Test-AutoModelValue {
param([string]$Value)
$normalized = [string]$Value
if ([string]::IsNullOrWhiteSpace($normalized)) { return $true }
return $normalized.Trim() -in @("brain-model", "service-model")
}
function Test-AutoBaseValue {
param(
[string]$Name,
[string]$Value
)
if ([string]::IsNullOrWhiteSpace([string]$Value)) { return $true }
$normalized = (Normalize-BaseUrl $Value).ToLowerInvariant()
if ($Name -eq "BRAIN_API_BASE") { return $normalized -eq "http://brain-host:1234" }
if ($Name -eq "SERVICE_API_BASE") { return $normalized -eq "http://service-host:1234" }
return $false
}
function Test-ExplicitBrainConfiguration {
if (-not $script:ConfigExistedAtLaunch) { return $false }
$brainBase = [string](Get-PythonConfigValue "BRAIN_API_BASE")
# An explicit Brain URL is enough to opt out of the embedded bootstrap.
# BRAIN_MODEL_UID may be empty: in that case the launcher discovers the
# catalog from this endpoint and lets the user choose a model.
if ([string]::IsNullOrWhiteSpace($brainBase)) { return $false }
if (Test-AutoBaseValue "BRAIN_API_BASE" $brainBase) { return $false }
# A config written by JIN's own embedded bootstrap is still embedded mode.
if ((Normalize-BaseUrl $brainBase).ToLowerInvariant() -eq $EmbeddedBrainBaseUrl.ToLowerInvariant()) {
return $false
}
return $true
}
function Get-ModelRecords {
param($Payload)
$items = @()
if ($null -eq $Payload) { return @() }
if ($Payload.PSObject.Properties.Name -contains "models") {
$items = @($Payload.models)
}
elseif ($Payload.PSObject.Properties.Name -contains "data") {
$items = @($Payload.data)
}
else {
$items = @($Payload)
}
$seen = @{}
$records = New-Object System.Collections.ArrayList
foreach ($item in $items) {
if ($null -eq $item) { continue }
$id = ""
$loaded = $false
$modelType = ""
$maxContext = 0
$loadedContext = 0
if ($item -is [string]) {
$id = $item.Trim()
}
else {
foreach ($field in @("id", "key", "model", "name")) {
if ($item.PSObject.Properties.Name -contains $field) {
$candidate = [string]$item.$field
if (-not [string]::IsNullOrWhiteSpace($candidate)) {
$id = $candidate.Trim()
break
}
}
}
foreach ($field in @("type", "model_type")) {
if ($item.PSObject.Properties.Name -contains $field) {
$modelType = [string]$item.$field
if ($modelType) { break }
}
}
$maxContext = Get-PositiveIntValue $item @(
"max_context_length",
"max_context_window",
"max_position_embeddings"
)
if ($item.PSObject.Properties.Name -contains "loaded_instances") {
$loaded = @($item.loaded_instances).Count -gt 0
if ($loaded) {
$loadedContext = Get-LoadedContextFromModelItem $item
}
}
elseif ($item.PSObject.Properties.Name -contains "state") {
$loaded = ([string]$item.state).ToLowerInvariant() -eq "loaded"
}
if ($loaded -and $loadedContext -le 0) {
$loadedContext = Get-PositiveIntValue $item @(
"loaded_context_length",
"context_length",
"context_window",
"n_ctx",
"num_ctx"
)
}
}
if ([string]::IsNullOrWhiteSpace($id)) { continue }
if ($modelType.ToLowerInvariant() -in @("embedding", "embeddings")) { continue }
if ($seen.ContainsKey($id)) { continue }
$seen[$id] = $true
[void]$records.Add([pscustomobject]@{
Id = $id
Loaded = $loaded
MaxContext = [int]$maxContext
LoadedContext = [int]$loadedContext
})
}
return @($records | Sort-Object -Property Id)
}
function Get-EndpointState {
param(
[string]$Role,
[string]$BaseUrl,
[string]$SelectedModel
)
$base = Normalize-BaseUrl $BaseUrl
if ([string]::IsNullOrWhiteSpace($base)) {
return [pscustomobject]@{
Role = $Role
BaseUrl = ""
Online = $false
Models = @()
Selected = $SelectedModel
Source = ""
Error = "not configured"
}
}
$errors = New-Object System.Collections.ArrayList
$candidates = New-Object System.Collections.ArrayList
# Prefer rich provider-native catalogs when available. LM Studio's
# /api/v1/models contains all downloaded models plus their type, load state
# and context metadata. /v1/models may expose only the currently visible
# models and can therefore accidentally surface an embedding model alone.
foreach ($suffix in @("/api/v1/models", "/api/v0/models", "/v1/models")) {
try {
$payload = Invoke-RestMethod -Method Get -Uri "$base$suffix" -TimeoutSec 2 -ErrorAction Stop
$records = @(Get-ModelRecords $payload)
if ($records.Count -gt 0) {
[void]$candidates.Add([pscustomobject]@{
Suffix = $suffix
Records = $records
Priority = if ($suffix -eq "/api/v1/models") { 3 } elseif ($suffix -eq "/api/v0/models") { 2 } else { 1 }
})
}
}
catch {
[void]$errors.Add(("$suffix // " + $_.Exception.Message))
}
}
if ($candidates.Count -gt 0) {
# Richest catalog wins; native API wins ties.
$best = @(
$candidates |
Sort-Object `
@{ Expression = { @($_.Records).Count }; Descending = $true }, `
@{ Expression = { [int]$_.Priority }; Descending = $true }
)[0]
return [pscustomobject]@{
Role = $Role
BaseUrl = $base
Online = $true
Models = @($best.Records)
Selected = $SelectedModel
Source = [string]$best.Suffix
Error = ""
}
}
return [pscustomobject]@{
Role = $Role
BaseUrl = $base
Online = $false
Models = @()
Selected = $SelectedModel
Source = ""
Error = ((@($errors) | Select-Object -First 1) -join "")
}
}
function Refresh-Runtimes {
param([switch]$UseInitialBrainProbe)
$script:BrainTemperature = [string](Get-PythonConfigValue "BRAIN_TEMPERATURE")
if ([string]::IsNullOrWhiteSpace($script:BrainTemperature)) { $script:BrainTemperature = "?" }
$script:ServiceTemperature = [string](Get-PythonConfigValue "SERVICE_TEMPERATURE")
if ([string]::IsNullOrWhiteSpace($script:ServiceTemperature)) { $script:ServiceTemperature = "?" }
$script:RuntimeLogsEnabled = [string](Get-PythonConfigValue "ENABLE_RUNTIME_LOGS")
if ([string]::IsNullOrWhiteSpace($script:RuntimeLogsEnabled)) { $script:RuntimeLogsEnabled = "?" }
if ($script:BrainIsEmbedded) {
# Fresh/default install: JIN owns the local Brain runtime.
$brainBase = $EmbeddedBrainBaseUrl
$brainSelected = $EmbeddedBrainModelId
Set-PythonConfigValue "BRAIN_API_BASE" $brainBase
Set-PythonConfigValue "BRAIN_MODEL_UID" $brainSelected
}
else {
# Existing explicit config is authoritative. Never replace it with the
# embedded bootstrap endpoint/model.
$brainBase = [string](Get-PythonConfigValue "BRAIN_API_BASE")
$brainSelected = [string](Get-PythonConfigValue "BRAIN_MODEL_UID")
}
$serviceBase = [string](Get-PythonConfigValue "SERVICE_API_BASE")
if (Test-AutoBaseValue "SERVICE_API_BASE" $serviceBase) { $serviceBase = "" }
$serviceSelected = [string](Get-PythonConfigValue "SERVICE_MODEL_UID")
if (Test-AutoModelValue $serviceSelected) { $serviceSelected = "" }
if ($script:BootMode) {
$probeText = if ($script:BrainIsEmbedded) { "checking local Gemma brain" } else { "checking configured Brain" }
Write-BootLine "BRAIN" $probeText "WORK"
}
if ($UseInitialBrainProbe -and $null -ne $script:FirstRunLmStudioRuntime) {
$script:BrainRuntime = $script:FirstRunLmStudioRuntime
$script:BrainRuntime.Selected = $brainSelected
}
else {
$script:BrainRuntime = Get-EndpointState "brain" $brainBase $brainSelected
}
if ($script:BrainIsEmbedded -and $script:BrainRuntime.Online) {
# llama-server already has the single embedded model loaded. Expose a
# stable model record so the dashboard shows Brain, not endpoint plumbing.
$script:BrainRuntime.Models = @(
[pscustomobject]@{
Id = $EmbeddedBrainModelId
Loaded = $true
MaxContext = [int]$EmbeddedBrainMaxContext
LoadedContext = [int]$script:EmbeddedBrainContext
}
)
$script:BrainRuntime.Selected = $EmbeddedBrainModelId
$script:BrainRuntime.Source = "embedded llama.cpp"
}
if ($script:BootMode) {
if ($script:BrainRuntime.Online) {
if ($script:BrainIsEmbedded) {
Write-BootLine "BRAIN" ("Gemma 4 E4B ready @ " + (Format-ContextTokens $script:EmbeddedBrainContext)) "OK"
}
else {
if ([string]::IsNullOrWhiteSpace($brainSelected)) {
Write-BootLine "BRAIN" ((@($script:BrainRuntime.Models).Count).ToString() + " model(s) loaded from configured URL") "OK"
}
else {
Write-BootLine "BRAIN" ("configured Brain ready // " + $brainSelected) "OK"
}
}
}
else {
$errorText = if ($script:BrainIsEmbedded) { "local Gemma brain unavailable" } else { "configured Brain endpoint unavailable" }
Write-BootLine "BRAIN" $errorText "ERROR"
}
}
if (-not [string]::IsNullOrWhiteSpace($serviceBase)) {
$script:ServiceRuntime = Get-EndpointState "service" $serviceBase $serviceSelected
$script:ServiceConfigured = $true
}
else {
$script:ServiceRuntime = [pscustomobject]@{
Role = "service"
BaseUrl = ""
Online = $script:BrainRuntime.Online
Models = @()
Selected = $brainSelected
Source = "brain fallback"
Error = ""
}
$script:ServiceConfigured = $false
}
}
function Test-PythonCommand {
param([string]$Executable)
if ([string]::IsNullOrWhiteSpace($Executable) -or -not (Test-Path -LiteralPath $Executable)) {
return $false
}
try {
$versionOutput = & $Executable --version 2>&1
$versionText = (@($versionOutput) -join " ").Trim()
return ($LASTEXITCODE -eq 0 -and $versionText -match '^Python 3(?:\.|\s|$)')
}
catch { return $false }
}
function Get-UvWindowsAsset {
$arch = [string]$env:PROCESSOR_ARCHITEW6432
if ([string]::IsNullOrWhiteSpace($arch)) {
$arch = [string]$env:PROCESSOR_ARCHITECTURE
}
switch ($arch.ToUpperInvariant()) {
"AMD64" { return "uv-x86_64-pc-windows-msvc.zip" }
"ARM64" { return "uv-aarch64-pc-windows-msvc.zip" }
"X86" { return "uv-i686-pc-windows-msvc.zip" }
default { Fail-WithMessage "Unsupported Windows architecture for JIN bootstrap: $arch" }
}
}
function Set-UvRuntimeEnvironment {
# Keep the complete Python toolchain private to the JIN folder. Nothing is
# registered in Windows and no user/system Python is consulted.
$env:UV_PYTHON_INSTALL_DIR = $ManagedPythonDir
$env:UV_PYTHON_BIN_DIR = (Join-Path $RuntimeDir "python-bin")
$env:UV_CACHE_DIR = $UvCacheDir
$env:UV_PYTHON_NO_REGISTRY = "1"
$env:UV_NO_CONFIG = "1"
$env:UV_MANAGED_PYTHON = "1"
}
function Test-UvExecutable {
if (-not (Test-Path -LiteralPath $UvExe)) { return $false }
try {
$versionOutput = & $UvExe --version 2>&1
$versionText = (@($versionOutput) -join " ").Trim()
return ($LASTEXITCODE -eq 0 -and $versionText -match '^uv\s+')
}
catch { return $false }
}
function Ensure-UvBootstrap {
Set-UvRuntimeEnvironment
if (Test-UvExecutable) { return $UvExe }
$script:RuntimeMessage = "PREPARING PYTHON BOOTSTRAP"
Write-BootLine "PYTHON" "preparing private runtime bootstrap" "WORK"
if (-not (Test-Path -LiteralPath $UvDir)) {