-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-MiOS.ps1
More file actions
5620 lines (5297 loc) · 305 KB
/
Copy pathGet-MiOS.ps1
File metadata and controls
5620 lines (5297 loc) · 305 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
# AI-hint: Primary entry point for MiOS installation; handles admin elevation, environment validation, and fresh-clone of the bootstrap repo to initiate the preflight, VM setup, and OCI build pipeline.
# AI-doc: usr/share/doc/mios/manual/root.md
<#
.SYNOPSIS
'MiOS' bootstrap -- canonical Windows one-liner entry point.
.DESCRIPTION
Designed for: irm https://raw.githubusercontent.com/mios-dev/mios-bootstrap/main/Get-MiOS.ps1 | iex
Thin entrypoint that:
1. Elevates to Administrator (re-launches a NEW window so the
operator sees a clean, properly-sized terminal).
2. Resizes the host window to ~100x40 so the build dashboard
frame (80 cols + breathing room) fits without wrapping.
3. Verifies Git + Podman are present.
4. Force-cleans + fresh-clones the mios-bootstrap repo into
$env:TEMP\mios-bootstrap. Every run is fresh; no persistent
working tree, no fetch/pull update branch.
5. Hands off to bootstrap.ps1 -- the new split-bootstrap entry
(default: -BootstrapOnly = preflight + dev VM + Windows
install; the deployable OCI image is built later via the
"Build MiOS" Start Menu shortcut bootstrap.ps1 drops).
Pre-v0.2.4 this script wrapped the run in Start-Transcript --
that captured the dashboard's cursor escapes and broke the
in-place repaint. Removed: build-mios.ps1 writes its own unified
log directly via [IO.File]::AppendAllText (no transcript needed).
Pass -FullBuild to chain the OCI image build immediately
(legacy one-shot behavior).
.PARAMETER RepoUrl
git URL for mios-bootstrap (default: GitHub upstream).
.PARAMETER Branch
Branch to clone (default: main).
.PARAMETER RepoDir
Temp clone target. Default: $env:TEMP\mios-bootstrap-<random8>.
Each invocation gets a fresh GUID-suffixed dir so a locked
leftover from a previous run never blocks a new start. Operators
who genuinely want to point at a local checkout (e.g. for
development) can pass an explicit -RepoDir; the script will
refuse to delete it if it's outside %TEMP%. There is NO update /
fetch / pull branch here -- always fresh-clone. A persistent path
like $env:USERPROFILE\MiOS-bootstrap is FORBIDDEN as the bootstrap
working tree (it accumulates stale state across runs and was the
root cause of every "FATAL: From https://...", "FATAL: Cloning
into ...", and "FATAL: vm already exists" surface we kept fixing).
.PARAMETER FullBuild
Run the full pipeline in one shot (preflight + dev VM + Windows
install + OCI build + deploy). Equivalent to passing -FullBuild
through to bootstrap.ps1.
.PARAMETER Unattended
Take all defaults; skip interactive prompts.
.PARAMETER Workflow
Optional preset workflow name (legacy parameter; passed through
via $env:MIOS_WORKFLOW for any consumer that reads it).
#>
param(
[Parameter(Mandatory=$false)]
[ValidateSet('Default', 'BuildXboxISO', 'FlashUSB', 'OfflineSync', 'Install', 'Configure')]
[string]$Action = 'Default',
[string]$RepoUrl = "https://github.com/mios-dev/mios-bootstrap.git",
[string]$Branch = "main",
[string]$RepoDir = "M:\MiOS\repo\mios-bootstrap",
[switch]$FullBuild,
[switch]$Unattended,
[string]$Workflow = ""
)
$ErrorActionPreference = "Stop"
# Invoke-Expression runs this body inside its caller's PowerShell process.
# This entrypoint uses `exit` for explicit pipeline exit codes, so executing it
# directly with `irm ... | iex` would close the operator's terminal. Re-run the
# fetched entrypoint as a script file in a child process; exit then returns to
# the caller's prompt. The environment guard prevents the child's cache-busted
# in-process refresh from spawning another child.
if (-not $PSCommandPath -and -not $env:MIOS_GETMIOS_FILE_RELAUNCHED) {
$entryUrl = 'https://raw.githubusercontent.com/mios-dev/mios-bootstrap/main/Get-MiOS.ps1'
$entryPath = Join-Path $env:TEMP ('mios-entry-' + [guid]::NewGuid().ToString('N') + '.ps1')
try {
$entryResponse = Invoke-WebRequest -Uri $entryUrl `
-Headers @{ 'Cache-Control' = 'no-cache, no-store, max-age=0'; 'Pragma' = 'no-cache' } `
-UseBasicParsing -ErrorAction Stop
if (-not $entryResponse.Content -or $entryResponse.Content.Length -lt 1000) {
throw 'The fetched Get-MiOS.ps1 response was empty or incomplete.'
}
[IO.File]::WriteAllText($entryPath, [string]$entryResponse.Content, (New-Object System.Text.UTF8Encoding($true)))
$engine = Join-Path $PSHOME $(if ($PSVersionTable.PSEdition -eq 'Core') { 'pwsh.exe' } else { 'powershell.exe' })
if (-not (Test-Path -LiteralPath $engine -PathType Leaf)) { $engine = 'powershell.exe' }
$childArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $entryPath,
'-Action', $Action, '-RepoUrl', $RepoUrl, '-Branch', $Branch, '-RepoDir', $RepoDir)
if ($Workflow) { $childArgs += @('-Workflow', $Workflow) }
if ($FullBuild) { $childArgs += '-FullBuild' }
if ($Unattended) { $childArgs += '-Unattended' }
$oldRelaunchFlag = $env:MIOS_GETMIOS_FILE_RELAUNCHED
$env:MIOS_GETMIOS_FILE_RELAUNCHED = '1'
try {
& $engine @childArgs
$childExit = $LASTEXITCODE
} finally {
if ($null -eq $oldRelaunchFlag) { Remove-Item Env:MIOS_GETMIOS_FILE_RELAUNCHED -ErrorAction SilentlyContinue }
else { $env:MIOS_GETMIOS_FILE_RELAUNCHED = $oldRelaunchFlag }
}
} catch {
Write-Host ("[!] Could not start the MiOS installer in a child PowerShell process: " + $_.Exception.Message) -ForegroundColor Red
$childExit = 1
} finally {
Remove-Item -LiteralPath $entryPath -Force -ErrorAction SilentlyContinue
}
if ($null -ne $childExit) { $global:LASTEXITCODE = [int]$childExit }
return
}
if ($PSCommandPath) { $global:MIOS_GETMIOS_FILE_RELAUNCHED = $true }
# Set TLS 1.2 explicitly for down-level/.NET-old hosts
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
} catch {}
# Disable console QuickEdit immediately so an accidental click/select in the
# (elevated) window can't freeze the installer on its next write -- Windows
# "mark" mode blocks the process until Enter/Esc is pressed (a click
# during the long install read as a dead hang). build-mios.ps1 re-applies this;
# the type guard makes the second call a no-op. Best-effort; never fatal.
function Disable-ConsoleQuickEdit {
try {
if (-not ('MiosConsole.Win32' -as [type])) {
Add-Type -Namespace MiosConsole -Name Win32 -MemberDefinition '[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)] public static extern System.IntPtr GetStdHandle(int nStdHandle); [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)] public static extern bool GetConsoleMode(System.IntPtr hConsoleHandle, out uint lpMode); [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError=true)] public static extern bool SetConsoleMode(System.IntPtr hConsoleHandle, uint dwMode);' -ErrorAction Stop
}
$h = [MiosConsole.Win32]::GetStdHandle(-10) # STD_INPUT_HANDLE
[uint32]$mode = 0
if ([MiosConsole.Win32]::GetConsoleMode($h, [ref]$mode)) {
$mode = ($mode -band (-bnot [uint32]0x40)) -bor [uint32]0x80 # -QUICK_EDIT +EXTENDED_FLAGS
[void][MiosConsole.Win32]::SetConsoleMode($h, $mode)
}
} catch {}
}
Disable-ConsoleQuickEdit
function Center-MiosBootstrapWindow {
try {
if (-not ([System.Management.Automation.PSTypeName]'MiosBootstrapWindow').Type) {
Add-Type -TypeDefinition @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class MiosBootstrapWindow {
[StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] public struct MonitorInfo { public int cbSize; public Rect monitor, work; public uint flags; }
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetClassName(IntPtr h, StringBuilder name, int count);
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out Rect rect);
[DllImport("user32.dll")] public static extern IntPtr MonitorFromWindow(IntPtr h, uint flags);
[DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern bool GetMonitorInfo(IntPtr h, ref MonitorInfo info);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int width, int height, uint flags);
public static bool CenterForegroundTerminal() {
IntPtr h = GetForegroundWindow();
if (h == IntPtr.Zero) return false;
StringBuilder cls = new StringBuilder(128);
GetClassName(h, cls, cls.Capacity);
string name = cls.ToString();
if (name != "CASCADIA_HOSTING_WINDOW_CLASS" && name != "ConsoleWindowClass") return false;
IntPtr previous = IntPtr.Zero;
try { previous = SetThreadDpiAwarenessContext(new IntPtr(-4)); } catch (EntryPointNotFoundException) {}
try {
Rect rect;
MonitorInfo info = new MonitorInfo();
info.cbSize = Marshal.SizeOf(typeof(MonitorInfo));
IntPtr monitor = MonitorFromWindow(h, 2);
if (monitor == IntPtr.Zero || !GetMonitorInfo(monitor, ref info) || !GetWindowRect(h, out rect)) return false;
int width = Math.Min(rect.Right - rect.Left, info.work.Right - info.work.Left);
int height = Math.Min(rect.Bottom - rect.Top, info.work.Bottom - info.work.Top);
if (width <= 0 || height <= 0) return false;
int x = info.work.Left + (info.work.Right - info.work.Left - width) / 2;
int y = info.work.Top + (info.work.Bottom - info.work.Top - height) / 2;
return SetWindowPos(h, IntPtr.Zero, x, y, width, height, 0x14);
} finally { if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous); }
}
}
"@ -ErrorAction Stop
}
[void][MiosBootstrapWindow]::CenterForegroundTerminal()
} catch {}
}
Center-MiosBootstrapWindow
function Start-MiosBuildMonitor {
if ($env:MIOS_NO_MONITOR -in @('1','true','yes','on') -or
$env:MIOS_HEADLESS -in @('1','true','yes','on')) { return }
$monitorCols = [int](Get-MiosTomlValue -Section 'terminal.install' -Key 'cols' -Default 80)
$monitorRows = [int](Get-MiosTomlValue -Section 'terminal.install' -Key 'rows' -Default 40)
$cellWidth = [int](Get-MiosTomlValue -Section 'theme.font' -Key 'cell_w_px' -Default 10)
$cellHeight = [int](Get-MiosTomlValue -Section 'theme.font' -Key 'cell_h_px' -Default 20)
$chromeWidth = [int](Get-MiosTomlValue -Section 'theme.font' -Key 'chrome_w_px' -Default 20)
$chromeHeight = [int](Get-MiosTomlValue -Section 'theme.font' -Key 'chrome_h_px' -Default 12)
$monitorWidthPx = ($monitorCols * $cellWidth) + $chromeWidth
$monitorHeightPx = ($monitorRows * $cellHeight) + $chromeHeight
$monitorScript = @(
$env:MIOS_MONITOR_SCRIPT,
'C:\MiOS\usr\libexec\mios\mios-mon.py',
'M:\usr\libexec\mios\mios-mon.py'
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
if (-not $monitorScript) { return }
try {
if (-not ([System.Management.Automation.PSTypeName]'MiosDeskLauncher').Type) {
$typeDef = @"
using System;
using System.Text;
using System.Runtime.InteropServices;
public static class MiosDeskLauncher {
public delegate bool EnumDesktopWindowsProc(IntPtr hWnd, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO {
public int cb; public string lpReserved; public string lpDesktop; public string lpTitle;
public int dwX; public int dwY; public int dwXSize; public int dwYSize;
public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute;
public int dwFlags; public short wShowWindow; public short cbReserved2;
public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION {
public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId;
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CreateProcess(
string lpApp, string lpCmd, IntPtr pAttr, IntPtr tAttr, bool bInherit,
uint flags, IntPtr env, string dir, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(IntPtr h);
[DllImport("user32.dll")] public static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags, bool fInherit, uint dwDesiredAccess);
[DllImport("user32.dll")] public static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDesktopWindowsProc lpfn, IntPtr lParam);
[DllImport("user32.dll")] public static extern bool CloseDesktop(IntPtr hDesktop);
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", SetLastError=true)] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
[DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int width, int height, bool repaint);
[DllImport("user32.dll")] public static extern IntPtr MonitorFromWindow(IntPtr hWnd, uint flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool GetMonitorInfo(IntPtr monitor, ref MONITORINFO info);
[DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr hWnd);
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] public struct MONITORINFO { public int cbSize; public RECT monitor; public RECT work; public uint flags; }
public static bool HasVisibleMonitorWindow() {
IntPtr hDesk = OpenDesktop("Default", 0, false, 0x01FF);
if (hDesk == IntPtr.Zero) return false;
bool found = false;
EnumDesktopWindows(hDesk, (hWnd, lParam) => {
if (IsWindowVisible(hWnd)) {
StringBuilder sb = new StringBuilder(256);
if (GetWindowText(hWnd, sb, 256) > 0) {
if (sb.ToString().IndexOf("MiOS Build Monitor", StringComparison.OrdinalIgnoreCase) >= 0) {
found = true;
ShowWindow(hWnd, 9);
BringWindowToTop(hWnd);
SetForegroundWindow(hWnd);
return false;
}
}
}
return true;
}, IntPtr.Zero);
CloseDesktop(hDesk);
return found;
}
public static bool CenterVisibleMonitorWindow(int wantedWidth, int wantedHeight) {
IntPtr hDesk = OpenDesktop("Default", 0, false, 0x01FF);
if (hDesk == IntPtr.Zero) return false;
bool found = false;
EnumDesktopWindows(hDesk, (hWnd, lParam) => {
if (IsWindowVisible(hWnd)) {
StringBuilder sb = new StringBuilder(256);
if (GetWindowText(hWnd, sb, 256) > 0 &&
sb.ToString().IndexOf("MiOS Build Monitor", StringComparison.OrdinalIgnoreCase) >= 0) {
ShowWindow(hWnd, 1);
IntPtr oldDpi = IntPtr.Zero;
try { oldDpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); } catch (EntryPointNotFoundException) {}
try {
RECT rect;
MONITORINFO info = new MONITORINFO();
info.cbSize = Marshal.SizeOf(typeof(MONITORINFO));
IntPtr monitor = MonitorFromWindow(hWnd, 2);
if (GetWindowRect(hWnd, out rect) && monitor != IntPtr.Zero && GetMonitorInfo(monitor, ref info)) {
uint dpi = 96;
try { dpi = GetDpiForWindow(hWnd); } catch (EntryPointNotFoundException) {}
int requestedWidth = (int)Math.Round(wantedWidth * dpi / 96.0);
int requestedHeight = (int)Math.Round(wantedHeight * dpi / 96.0);
int width = Math.Min(Math.Min(rect.Right - rect.Left, requestedWidth), info.work.Right - info.work.Left);
int height = Math.Min(Math.Min(rect.Bottom - rect.Top, requestedHeight), info.work.Bottom - info.work.Top);
if (width > 0 && height > 0) {
int x = info.work.Left + ((info.work.Right - info.work.Left - width) / 2);
int y = info.work.Top + ((info.work.Bottom - info.work.Top - height) / 2);
BringWindowToTop(hWnd);
SetForegroundWindow(hWnd);
MoveWindow(hWnd, x, y, width, height, true);
}
}
} finally { if (oldDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(oldDpi); }
found = true;
return false;
}
}
return true;
}, IntPtr.Zero);
CloseDesktop(hDesk);
return found;
}
public static int Launch(string cmd, string title) {
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = @"winsta0\default";
si.lpTitle = title;
PROCESS_INFORMATION pi;
if (CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, false, 0x00000010, IntPtr.Zero, null, ref si, out pi)) {
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return pi.dwProcessId;
}
return -1;
}
}
"@
Add-Type -TypeDefinition $typeDef -ErrorAction SilentlyContinue
}
if (([System.Management.Automation.PSTypeName]'MiosDeskLauncher').Type) {
if ([MiosDeskLauncher]::CenterVisibleMonitorWindow($monitorWidthPx, $monitorHeightPx)) { return }
} else {
$runningProcs = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '^python' -and $_.CommandLine -match 'mios-mon\.py' })
$hasActive = $false
foreach ($rp in $runningProcs) {
$p = Get-Process -Id $rp.ProcessId -ErrorAction SilentlyContinue
if ($p -and -not $p.HasExited) { $hasActive = $true; break }
}
if ($hasActive) { return }
}
$python = Get-Command python.exe -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source
if (-not $python) {
foreach ($c in @(
'C:\Users\Administrator\AppData\Local\Programs\Python\Python314\python.exe',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python313\python.exe',
'C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe',
'C:\Python314\python.exe',
'C:\Python312\python.exe'
)) { if (Test-Path -LiteralPath $c) { $python = $c; break } }
}
if (-not $python) { return }
$wtExe = Get-Command wt.exe -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Source
if (-not $wtExe) {
foreach ($candidate in @(
"$env:LOCALAPPDATA\Microsoft\WindowsApps\wt.exe",
"$env:ProgramFiles\WindowsApps\Microsoft.WindowsTerminal*\wt.exe"
)) {
$found = Get-Item $candidate -ErrorAction SilentlyContinue | Select-Object -First 1
if ($found) { $wtExe = $found.FullName; break }
}
}
# Windows Terminal is required by the bootstrap. If it is not ready
# yet, wait for the post-profile-setup invocation below instead of
# opening a plain conhost window that can mask the SSOT terminal.
if (-not $wtExe -or -not (Test-Path -LiteralPath $wtExe)) { return }
$spawnedPid = -1
if ($wtExe -and (Test-Path -LiteralPath $wtExe)) {
$monitorProfile = [string](Get-MiosTomlValue -Section 'theme.terminal' -Key 'profile_name' -Default 'MiOS-WIN')
if ([string]::IsNullOrWhiteSpace($monitorProfile)) { $monitorProfile = 'MiOS-WIN' }
$monitorScheme = [string](Get-MiosTomlValue -Section 'theme.terminal' -Key 'scheme_name' -Default 'MiOS')
if ([string]::IsNullOrWhiteSpace($monitorScheme)) { $monitorScheme = 'MiOS' }
$monitorLaunchMode = [string](Get-MiosTomlValue -Section 'theme' -Key 'launch_mode' -Default 'focus')
$monitorX = 0; $monitorY = 0
$displayCols = $monitorCols; $displayRows = $monitorRows
try {
Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop
$cursor = [System.Windows.Forms.Cursor]::Position
$workArea = [System.Windows.Forms.Screen]::FromPoint($cursor).WorkingArea
$displayCols = [math]::Min($monitorCols, [math]::Max(40, [math]::Floor(($workArea.Width - $chromeWidth - 28) / $cellWidth)))
$displayRows = [math]::Min($monitorRows, [math]::Max(12, [math]::Floor(($workArea.Height - $chromeHeight - 32) / $cellHeight)))
$monitorWidthPx = ($displayCols * $cellWidth) + $chromeWidth
$monitorHeightPx = ($displayRows * $cellHeight) + $chromeHeight
$monitorX = [int]($workArea.X + (($workArea.Width - $monitorWidthPx) / 2))
$monitorY = [int]($workArea.Y + (($workArea.Height - $monitorHeightPx) / 2))
if ($monitorX -lt $workArea.X) { $monitorX = $workArea.X }
if ($monitorY -lt $workArea.Y) { $monitorY = $workArea.Y }
} catch {}
$wtWindowArgs = switch ($monitorLaunchMode) {
'focus' { @('--focus') }
'maximized' { @('--maximized') }
'maximizedFocus' { @('--maximized','--focus') }
'fullscreen' { @('--fullscreen') }
'focusFullscreen'{ @('--fullscreen','--focus') }
default { @() }
}
$profileReady = $false
foreach ($settingsPath in @(
(Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'),
(Join-Path $env:LOCALAPPDATA 'Packages\Microsoft.WindowsTerminalPreview_8wekyb3d8bbwe\LocalState\settings.json')
)) {
if (-not (Test-Path -LiteralPath $settingsPath)) { continue }
try {
$settingsText = [IO.File]::ReadAllText($settingsPath)
$settingsText = [regex]::Replace($settingsText, '(?ms)/\*.*?\*/', '')
$settingsText = [regex]::Replace($settingsText, '(?m)^\s*//.*$', '')
$settingsText = [regex]::Replace($settingsText, ',(\s*[\}\]])', '$1')
$settings = $settingsText | ConvertFrom-Json -ErrorAction Stop
if (@($settings.profiles.list | Where-Object { $_.name -eq $monitorProfile }).Count) {
$profileReady = $true
break
}
} catch {}
}
# On a first install, wait until Install-MiOSTerminalProfile has
# created the SSOT profile; the caller invokes this launcher again
# immediately after that setup step. This avoids a plain-profile
# monitor that masks a failed themed launch.
if (-not $profileReady) { return }
$wtWindowArgsText = $wtWindowArgs -join ' '
$monitorCommand = "while (`$true) { & '$($python.Replace("'", "''"))' '$($monitorScript.Replace("'", "''"))' --pipeline; if (`$LASTEXITCODE -eq 0) { break }; Write-Host 'MiOS monitor exited unexpectedly; restarting in 2 seconds' -ForegroundColor Yellow; Start-Sleep -Seconds 2 }"
$monitorEncoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($monitorCommand))
$monitorShell = "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe"
$wtArgsString = "$wtWindowArgsText --pos `"$monitorX,$monitorY`" --size `"$displayCols,$displayRows`" -w `"MiOS-Monitor`" new-tab --profile `"$monitorProfile`" --colorScheme `"$monitorScheme`" --title `"MiOS Build Monitor`" `"$monitorShell`" -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand $monitorEncoded"
$cmdLine = "`"$wtExe`" $wtArgsString"
if (([System.Management.Automation.PSTypeName]'MiosDeskLauncher').Type) {
$spawnedPid = [MiosDeskLauncher]::Launch($cmdLine, 'MiOS Build Monitor')
}
if ($spawnedPid -le 0) {
$monitorProcess = Start-Process -FilePath $wtExe `
-ArgumentList $wtArgsString `
-WindowStyle Normal -PassThru -ErrorAction SilentlyContinue
if ($monitorProcess) { $spawnedPid = $monitorProcess.Id }
}
if ($spawnedPid -gt 0 -and ([System.Management.Automation.PSTypeName]'MiosDeskLauncher').Type) {
$centerDeadline = (Get-Date).AddSeconds(6)
while ((Get-Date) -lt $centerDeadline) {
[void][MiosDeskLauncher]::CenterVisibleMonitorWindow($monitorWidthPx, $monitorHeightPx)
Start-Sleep -Milliseconds 250
}
}
}
if ($spawnedPid -le 0) {
Write-Host ' [!] MiOS monitor could not launch in the SSOT Windows Terminal profile.' -ForegroundColor Yellow
}
} catch {
Write-Host " [!] MiOS monitor launch failed: $($_.Exception.Message)" -ForegroundColor Yellow
}
}
function Ensure-MiosBootstrapRepo {
param(
[string]$TargetDir = 'C:\mios-bootstrap',
[string]$RepoUrl = 'https://github.com/mios-dev/mios-bootstrap.git',
[string]$ZipUrl = 'https://codeload.github.com/mios-dev/mios-bootstrap/zip/refs/heads/main',
[string]$SentinelFile = 'field\autounattend\Build-MiOSXboxISO.ps1'
)
if (Get-Command Get-MiosTomlValue -ErrorAction SilentlyContinue) {
# The clone URL lives in [urls].bootstrap_repo -- NOT [bootstrap].mios_repo,
# which is the LOCAL MiOS checkout path (C:/MiOS). Reading mios_repo here
# would hand a filesystem path to `git clone <url>`.
$cfgRepo = Get-MiosTomlValue -Key 'urls.bootstrap_repo' -Default $RepoUrl
if ($cfgRepo) { $RepoUrl = $cfgRepo }
$cfgDir = Get-MiosTomlValue -Key 'bootstrap.bootstrap_repo' -Default $TargetDir
if ($cfgDir) { $TargetDir = $cfgDir }
}
$sentinelPath = Join-Path $TargetDir $SentinelFile
if (Test-Path $sentinelPath) { return $TargetDir }
Write-Host " [*] mios-bootstrap repo missing -- fetching to $TargetDir ..." -ForegroundColor Cyan
if (Get-Command git -ErrorAction SilentlyContinue) {
try { & git clone --depth 1 $RepoUrl $TargetDir 2>&1 | Out-Null } catch {}
}
if (-not (Test-Path $sentinelPath)) {
$zip = Join-Path $env:TEMP 'mios-bootstrap.zip'
$tmp = Join-Path $env:TEMP ('mios-bs-' + [System.Guid]::NewGuid().ToString('N').Substring(0,8))
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri $ZipUrl -OutFile $zip -UseBasicParsing -ErrorAction Stop
Expand-Archive -Path $zip -DestinationPath $tmp -Force
$inner = Get-ChildItem $tmp -Directory | Select-Object -First 1
if ($inner) {
New-Item -ItemType Directory -Force -Path $TargetDir | Out-Null
Copy-Item -Path (Join-Path $inner.FullName '*') -Destination $TargetDir -Recurse -Force
}
} catch {
Write-Host " [!] Could not fetch mios-bootstrap: $($_.Exception.Message)" -ForegroundColor Yellow
} finally {
Remove-Item $zip,$tmp -Recurse -Force -ErrorAction SilentlyContinue
}
}
if (-not (Test-Path $sentinelPath)) {
Write-Error "Failed to fetch mios-bootstrap repository to $TargetDir (sentinel $SentinelFile missing)"
exit 1
}
return $TargetDir
}
# Consolidated Action Router
if ($Action -ne 'Default') {
if ($Action -eq 'BuildXboxISO') {
Write-Host "[*] Action: BuildXboxISO. Invoking Build-MiOSXboxISO..." -ForegroundColor Cyan
$repoRoot = Ensure-MiosBootstrapRepo
$buildScript = Join-Path $repoRoot "field\autounattend\Build-MiOSXboxISO.ps1"
if (-not (Test-Path $buildScript)) {
Write-Error "Build-MiOSXboxISO.ps1 not found after fetch -- check network / GitHub access."
exit 1
}
# Run using a dynamic free-space work directory
$v = (Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.SizeRemaining -gt 15GB } | Sort-Object SizeRemaining -Descending | Select-Object -First 1)
$work = if ($v) { "$($v.DriveLetter):\MiOS\isobuild_live" } else { "C:\MiOS\isobuild_live" }
Write-Host " Using WorkDir: $work" -ForegroundColor Cyan
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $buildScript -WorkDir $work -SkipWsl -SkipPrereqs
exit $LASTEXITCODE
}
if ($Action -eq 'FlashUSB') {
Write-Host "[*] Action: FlashUSB. Staging and launching interactive MiOS-Field installer..." -ForegroundColor Cyan
# 1. Locate source folder
$sourceRoot = Ensure-MiosBootstrapRepo
$srcDir = Join-Path $sourceRoot "field"
if (-not (Test-Path $srcDir)) {
Write-Error "MiOS-Field (field) folder not found after fetch -- check network / GitHub access."
exit 1
}
# 2. Resolve staging directory
$v = Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.SizeRemaining -gt 25GB } | Sort-Object SizeRemaining -Descending | Select-Object -First 1
$stageDir = if ($v) { Join-Path "$($v.DriveLetter):\" "MiOS\field_stage" } else { Join-Path $env:TEMP "field_stage" }
$targetDir = Join-Path $stageDir "field"
Write-Host " Staging directory: $targetDir" -ForegroundColor Cyan
# Preserve the repository layout required by the shared field backend.
# Stage only runtime source paths; never copy Git metadata or scratch files.
New-Item -ItemType Directory -Force -Path $stageDir | Out-Null
foreach ($relativePath in @('field', 'installation', 'automation', 'src', 'etc', 'usr', 'var',
'Get-MiOS.ps1', 'bootstrap.ps1', 'bootstrap.sh', 'build-mios.ps1', 'build-mios.sh',
'install.ps1', 'install.sh', 'seed-merge.ps1', 'seed-merge.sh', 'mios.toml',
'VERSION', 'system-prompt.md')) {
$sourcePath = Join-Path $sourceRoot $relativePath
if (Test-Path -LiteralPath $sourcePath) {
Copy-Item -LiteralPath $sourcePath -Destination $stageDir -Recurse -Force -ErrorAction Stop
}
}
$fieldScript = Join-Path $targetDir "MiOS-Field.bat"
foreach ($requiredPath in @($fieldScript, (Join-Path $stageDir 'installation\mios-common.ps1'),
(Join-Path $stageDir 'installation\MiOS-Field.bat'))) {
if (-not (Test-Path -LiteralPath $requiredPath -PathType Leaf)) {
throw "MiOS-Field runtime file was not staged: $requiredPath"
}
}
Start-Process -FilePath "$env:SystemRoot\System32\cmd.exe" -ArgumentList "/c start `"MiOS-Field`" cmd.exe /k `"$fieldScript`" flash"
Write-Host "[+] Interactive MiOS-Field launcher spawned from staged directory." -ForegroundColor Green
exit 0
}
if ($Action -eq 'OfflineSync') {
Write-Host "[*] Action: OfflineSync. Staging repositories to USB..." -ForegroundColor Cyan
$drive = 'D'
$toml = 'C:\mios-bootstrap\mios.toml'
if (-not (Test-Path $toml)) { $toml = 'C:\MiOS\usr\share\mios\mios.toml' }
if (-not (Test-Path $toml)) { $toml = 'C:\MiOS\mios.toml' }
if (Test-Path $toml) {
$drive = (Get-Content $toml | Select-String -Pattern '^\s*drivepath\s*=\s*\"(.*)\"' | ForEach-Object { $_.Matches.Groups[1].Value })
if (-not $drive) { $drive = 'D' }
}
Write-Host "[*] Target USB Drive: $($drive):" -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path "$($drive):\repos\mios-bootstrap" | Out-Null
New-Item -ItemType Directory -Force -Path "$($drive):\repos\MiOS" | Out-Null
robocopy "C:\mios-bootstrap" "$($drive):\repos\mios-bootstrap" /E /XD .git .npm node_modules build cache isobuild isobuild2 /R:2 /W:2 | Out-Null
robocopy "C:\MiOS" "$($drive):\repos\MiOS" /E /XD .git .npm node_modules build cache isobuild isobuild2 /R:2 /W:2 | Out-Null
Write-Host "[+] Sync completed successfully." -ForegroundColor Green
exit 0
}
if ($Action -eq 'Install') {
# The web door hands into the ONE guided surface: fetch the repo, then run
# installation\mios-install.ps1 (the SSOT-themed menu that explains every
# target and dispatches to the right local entrypoint). This replaces
# "re-implement each launch here" with "hand into the single installer".
Write-Host "[*] Action: Install. Fetching the repo and opening the guided MiOS installer..." -ForegroundColor Cyan
$installer = Join-Path (Ensure-MiosBootstrapRepo) "installation\mios-install.ps1"
if (-not (Test-Path $installer)) {
Write-Error "installation\mios-install.ps1 not found after fetch -- check network / GitHub access."
exit 1
}
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installer
exit $LASTEXITCODE
}
if ($Action -eq 'Configure') {
# Same door, straight to the one SSOT editor: mios-install's `configure`
# target opens the MiOS Portal / configurator (:8640/configure, else the
# MiOS-DEV launcher, else the offline HTML).
Write-Host "[*] Action: Configure. Fetching the repo and opening the MiOS configurator (Portal)..." -ForegroundColor Cyan
$installer = Join-Path (Ensure-MiosBootstrapRepo) "installation\mios-install.ps1"
if (-not (Test-Path $installer)) {
Write-Error "installation\mios-install.ps1 not found after fetch -- check network / GitHub access."
exit 1
}
& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installer configure
exit $LASTEXITCODE
}
}
try {
$_curW = [Console]::WindowWidth
if ($_curW -gt 80) {
# Shrink window first, then buffer.
[Console]::SetWindowSize(80, 40)
[Console]::SetBufferSize(80, 9000)
} else {
# Enlarge buffer first, then window.
[Console]::SetBufferSize(80, 9000)
[Console]::SetWindowSize(80, 40)
}
} catch {}
# Center on cursor's active monitor via Win32 MoveWindow. Wrap each
# Add-Type separately so a "type already defined" exception on a
# re-entry doesn't skip the MoveWindow call.
try { Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue } catch {}
if (-not ('MiOSWinR.N' -as [type])) {
try {
Add-Type -Namespace MiOSWinR -Name N -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern System.IntPtr GetConsoleWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool MoveWindow(System.IntPtr hWnd, int x, int y, int w, int h, bool repaint);
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
'@ -ErrorAction Stop
} catch {}
}
try { [MiOSWinR.N]::SetProcessDPIAware() | Out-Null } catch {}
try {
# Geist Mono 12pt @ 100% DPI: cell 10x20 px, chrome 20x12 px.
# 80x40 cells -> 820 x 812 px outer rect.
$_winWPx = 820
$_winHPx = 812
$_cur = [System.Windows.Forms.Cursor]::Position
$_work = [System.Windows.Forms.Screen]::FromPoint($_cur).WorkingArea
$_x = $_work.X + [int](([math]::Max(0, $_work.Width - $_winWPx)) / 2)
$_y = $_work.Y + [int](([math]::Max(0, $_work.Height - $_winHPx)) / 2)
$_hwnd = [MiOSWinR.N]::GetConsoleWindow()
if ($_hwnd -ne [IntPtr]::Zero) {
[MiOSWinR.N]::MoveWindow($_hwnd, $_x, $_y, $_winWPx, $_winHPx, $true) | Out-Null
}
} catch {}
try {
$_legacyProfile = Join-Path $env:USERPROFILE 'MiOS-bootstrap'
if (Test-Path -LiteralPath $_legacyProfile) {
Remove-Item -LiteralPath $_legacyProfile -Recurse -Force -ErrorAction SilentlyContinue
# Also rewrite the redirector to point at the M:\ canonical
# location so the NEXT pwsh launch loads a clean profile (or
# no-ops via the redirector's `if (Test-Path)` guard if Pass-1
# hasn't yet staged the M:\ copy on this run).
$_profilePath = $PROFILE.CurrentUserAllHosts
if (-not $_profilePath) { $_profilePath = $PROFILE }
if ($_profilePath -and (Test-Path -LiteralPath $_profilePath)) {
try {
$_existing = Get-Content -LiteralPath $_profilePath -Raw -ErrorAction SilentlyContinue
$_marker = '# >>> MiOS oh-my-posh init >>>'
$_endMark = '# <<< MiOS oh-my-posh init <<<'
if ($_existing -match [regex]::Escape($_marker)) {
$_pattern = "(?s)$([regex]::Escape($_marker)).*?$([regex]::Escape($_endMark))"
$_cleaned = [regex]::Replace($_existing, $_pattern, '').TrimEnd()
Set-Content -LiteralPath $_profilePath -Value $_cleaned -Encoding UTF8 -NoNewline
}
} catch {}
}
}
} catch {}
if (-not $env:MIOS_CACHE_BUSTED -and -not $env:MIOS_GETMIOS_RELAUNCHED) {
$env:MIOS_CACHE_BUSTED = '1'
try {
$cb = [int][double]::Parse((Get-Date -UFormat %s))
$bustedUrl = "https://raw.githubusercontent.com/mios-dev/mios-bootstrap/main/Get-MiOS.ps1?cb=$cb"
$noCacheHdr = @{ 'Cache-Control' = 'no-cache, no-store, max-age=0'; 'Pragma' = 'no-cache' }
$freshSrc = Invoke-RestMethod -Uri $bustedUrl -Headers $noCacheHdr -ErrorAction Stop
if ($freshSrc -and $freshSrc.Length -gt 1000) {
# Got a real script back -- relaunch with the fresh copy.
& ([scriptblock]::Create($freshSrc)) -RepoUrl "$RepoUrl" -Branch "$Branch" -RepoDir "$RepoDir" -Workflow "$Workflow" $(if ($FullBuild) { '-FullBuild' }) $(if ($Unattended) { '-Unattended' })
return
}
# Empty / suspiciously small response -- fall through to the
# cached copy we already have running.
} catch {
# Network blip / DNS / Fastly outage -- fall through to the
# cached copy. Better to run something stale than nothing at all.
}
}
$installModuleDir = Join-Path $PSScriptRoot 'automation\lib\MiOS.Install'
if (Test-Path $installModuleDir) {
Get-ChildItem -Path $installModuleDir -Filter '*.psm1' -ErrorAction SilentlyContinue | ForEach-Object {
Import-Module $_.FullName -Force -ErrorAction SilentlyContinue
}
}
$script:_MiosTomlCache = @{}
function Resolve-MiosTomlText {
if ($script:_MiosTomlCache.ContainsKey('_text')) {
return $script:_MiosTomlCache['_text']
}
# Only a saved operator file is a host layer. The bootstrap checkout's
# mios.toml is a template and must never shadow the full system SSOT.
$path = Join-Path $env:USERPROFILE '.config\mios\mios.toml'
if ($path -and (Test-Path -LiteralPath $path -PathType Leaf)) {
try {
$script:_MiosTomlCache['_text'] = [IO.File]::ReadAllText($path, (New-Object System.Text.UTF8Encoding($false)))
$script:_MiosTomlCache['_source'] = $path
return $script:_MiosTomlCache['_text']
} catch {}
}
$script:_MiosTomlCache['_text'] = ''
$script:_MiosTomlCache['_source'] = '(no operator override)'
return ''
}
function Resolve-MiosVendorTomlText {
if ($script:_MiosTomlCache.ContainsKey('_vendor_text')) { return $script:_MiosTomlCache['_vendor_text'] }
# Phase 0 discards local install state; fetch the complete system SSOT
# from the current repository ref used by this fresh bootstrap run.
try {
$cb = [int][double]::Parse((Get-Date -UFormat %s))
$rawBase = if ($Script:MiosRawBase) { $Script:MiosRawBase } else { 'https://raw.githubusercontent.com/mios-dev/MiOS/main' }
$url = "$rawBase/usr/share/mios/mios.toml?cb=$cb"
$resp = Invoke-WebRequest -Uri $url `
-Headers @{ 'Cache-Control'='no-cache, no-store, max-age=0'; 'Pragma'='no-cache' } `
-UseBasicParsing -ErrorAction Stop
if ($resp.Content -is [byte[]]) { $script:_MiosTomlCache['_vendor_text'] = [System.Text.Encoding]::UTF8.GetString($resp.Content) }
else { $script:_MiosTomlCache['_vendor_text'] = [string]$resp.Content }
return $script:_MiosTomlCache['_vendor_text']
} catch {
$script:_MiosTomlCache['_vendor_text'] = ''
return ''
}
}
function Get-MiosTomlValue {
param(
[Parameter(Mandatory)] [string]$Section, # e.g. "terminal" or "bootstrap.host_storage"
[Parameter(Mandatory)] [string]$Key, # e.g. "cols"
[Parameter(Mandatory)] [AllowEmptyString()] $Default # returned if not found / unparseable
)
foreach ($txt in @((Resolve-MiosTomlText), (Resolve-MiosVendorTomlText))) {
if (-not $txt) { continue }
# Slice the section body: from `[Section]` (line-anchored) to the next
# `[other.section]` header or EOF.
$rxSec = '(?ms)^\[' + [regex]::Escape($Section) + '\][ \t]*\r?\n(?<body>.*?)(?=^\[[^\]]+\]|\z)'
$mSec = [regex]::Match($txt, $rxSec)
if (-not $mSec.Success) { continue }
$body = $mSec.Groups['body'].Value
# Within the body, find `key = value` (TOML allows leading whitespace).
$rxKey = '(?m)^[ \t]*' + [regex]::Escape($Key) + '[ \t]*=[ \t]*(?<val>.+?)[ \t]*(?:#.*)?$'
$mKey = [regex]::Match($body, $rxKey)
if (-not $mKey.Success) { continue }
$raw = $mKey.Groups['val'].Value.Trim()
# Coerce by Default's type. Strings get unquoted; arrays get split.
if ($Default -is [int]) {
$n = 0
if ([int]::TryParse(($raw -replace '_',''), [ref]$n)) { return $n }
continue
}
if ($Default -is [bool]) {
if ($raw -match '^(?i)true$') { return $true }
if ($raw -match '^(?i)false$') { return $false }
continue
}
if ($Default -is [double] -or $Default -is [single]) {
$d = 0.0
if ([double]::TryParse($raw, [ref]$d)) { return $d }
continue
}
if ($Default -is [array]) {
if ($raw -match '^\[(.*)\]$') {
$inner = $Matches[1]
$items = @(
$inner -split ',' |
ForEach-Object {
$s = $_.Trim().Trim('"', "'", ' ', "`t", "`r", "`n")
if ($s) { $s }
}
)
# If Default is an int[] try to coerce each item.
if ($Default.Length -gt 0 -and $Default[0] -is [int]) {
$coerced = @()
foreach ($it in $items) {
$n = 0
if ([int]::TryParse($it, [ref]$n)) { $coerced += $n } else { $coerced = $null; break }
}
if ($null -ne $coerced) { return $coerced }
continue
}
return $items
}
continue
}
if ($raw.Length -ge 2) {
$first = $raw[0]; $last = $raw[$raw.Length - 1]
if ($first -eq '"' -and $last -eq '"') {
$_bs = [string][char]0x01 + 'BS' + [string][char]0x01
$inner = $raw.Substring(1, $raw.Length - 2)
$inner = $inner -replace '\\\\', $_bs # placeholder for literal backslash
$inner = $inner -replace '\\"', '"'
$inner = $inner -replace '\\n', "`n"
$inner = $inner -replace '\\t', "`t"
$inner = $inner -replace '\\r', "`r"
$inner = $inner -replace [regex]::Escape($_bs), '\'
if (-not [string]::IsNullOrWhiteSpace($inner)) { return $inner }
continue
}
if ($first -eq "'" -and $last -eq "'") {
# Literal string: strip; no unescaping (TOML literal-string semantics).
$inner = $raw.Substring(1, $raw.Length - 2)
if (-not [string]::IsNullOrWhiteSpace($inner)) { return $inner }
continue
}
}
# Bare value, no surrounding quotes -- return as-is.
if (-not [string]::IsNullOrWhiteSpace($raw)) { return $raw }
}
return $Default
}
# The monitor must use the profile named by the operator SSOT. Delay launch
# until the TOML resolver exists so the WT profile is not inferred from a
# stale global default.
Start-MiosBuildMonitor
function ConvertTo-MiosRawBase {
param([Parameter(Mandatory)][string]$GitUrl, [Parameter(Mandatory)][string]$Ref)
if ($GitUrl -match '^[A-Za-z]:') {
return $GitUrl
}
$base = $GitUrl -replace '^https://github\.com/', 'https://raw.githubusercontent.com/' -replace '\.git$', ''
return "$base/$Ref"
}
$Script:MiosRepoUrl = Get-MiosTomlValue -Section 'bootstrap' -Key 'mios_repo' -Default 'https://github.com/mios-dev/MiOS.git'
$Script:MiosBootstrapUrl = Get-MiosTomlValue -Section 'bootstrap' -Key 'bootstrap_repo' -Default 'https://github.com/mios-dev/mios-bootstrap.git'
$Script:MiosRef = Get-MiosTomlValue -Section 'bootstrap' -Key 'mios_ref' -Default 'main'
$Script:MiosBootstrapRef = Get-MiosTomlValue -Section 'bootstrap' -Key 'bootstrap_ref' -Default 'main'
$Script:MiosRawBase = ConvertTo-MiosRawBase $Script:MiosRepoUrl $Script:MiosRef # vendor mios.git raw tree base
$Script:MiosBootstrapRaw = ConvertTo-MiosRawBase $Script:MiosBootstrapUrl $Script:MiosBootstrapRef # bootstrap repo raw tree base
# Release number: VERSION in $LocalRoot (a checkout), else $MiosRawBase/VERSION (irm | iex
# has no local copy), else [meta].mios_version, else 'unknown'. Never a literal.
function Get-MiosReleaseVersion {
param([string]$LocalRoot = '')
$v = ''
foreach ($root in @($LocalRoot, $Script:MiosRawBase)) {
if ($v -or -not $root) { continue }
try { $v = if ($root -match '^[A-Za-z]:|^[\\/]') { [IO.File]::ReadAllText((Join-Path $root 'VERSION')) } else { [string](Invoke-WebRequest -Uri "$root/VERSION" -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop).Content } } catch { $v = '' }
$v = ([string]$v).Trim(); if ($v -notmatch '^v?\d+(\.\d+)+') { $v = '' }
}
if (-not $v) { $v = [string](Get-MiosTomlValue -Section 'meta' -Key 'mios_version' -Default '') }
if (-not $v) { $v = 'unknown' }
return ($v -replace '^v', '')
}
function Show-MiOSBanner {
param([string]$Subtitle = '')
$art = @(
' ___ ___ ___',
' /\__\ ___ /\ \ /\ \',
' /::| | /\ \ /::\ \ /::\ \',
' /:|:| | \:\ \ /:/\:\ \ /:/\ \ \',
' /:/|:|__|__ /::\__\ /:/ \:\ \ _\:\~\ \ \',
' /:/ |::::\__\ __/:/\/__/ /:/__/ \:\__\ /\ \:\ \ \__\',
' \/__/~~/:/ / /\/:/ / \:\ \ /:/ / \:\ \:\ \/__/',
' /:/ / \::/__/ \:\ /:/ / \:\ \:\__\',
' /:/ / \:\__\ \:\/:/ / \:\/:/ /',
' /:/ / \/__/ \::/ / \::/ /',
' \/__/ \/__/ \/__/'
)
$sub = if ($Subtitle) { $Subtitle } else { Get-MiosTomlValue -Section 'branding' -Key 'tagline_app' -Default (Get-MiosTomlValue -Section 'branding' -Key 'tagline' -Default 'My Personal Operating System') }
$_bCols = Get-MiosTomlValue -Section 'terminal.install' -Key 'cols' -Default (Get-MiosTomlValue -Section 'terminal' -Key 'cols' -Default 80)
$_bRightMgn = Get-MiosTomlValue -Section 'terminal' -Key 'right_margin' -Default 0
$inner = [math]::Max(20, $_bCols - $_bRightMgn - 2)
# Block-center: pad every art line by the SAME left-pad so internal
# diagonal alignment is preserved.
$maxArt = ($art | Measure-Object -Property Length -Maximum).Maximum
$blockL = ' ' * [math]::Max(0, [math]::Floor(($inner - $maxArt) / 2))
# Subtitle centered on its own (different width than the art block).
$subPad = [math]::Max(0, $inner - $sub.Length)
$subL = ' ' * [math]::Floor($subPad / 2)
$subR = ' ' * ($subPad - [math]::Floor($subPad / 2))
$_hbar = ([char]0x2500).ToString() * $inner
$top = [char]0x256d + $_hbar + [char]0x256e
$bottom = [char]0x2570 + $_hbar + [char]0x256f
$rows = @($top)
foreach ($a in $art) {
$line = $blockL + $a
# Right-pad to fill inner width.
$line = $line + (' ' * [math]::Max(0, $inner - $line.Length))
$rows += [char]0x2502 + $line + [char]0x2502
}
$rows += [char]0x2502 + $subL + $sub + $subR + [char]0x2502
$rows += $bottom
$rows -join "`n"
}
function Show-MiOSAgreement {
$banner = Show-MiOSBanner -Subtitle 'Project Acknowledgement'
@"
$banner
The full document lives at AGREEMENTS.md (in the mios-bootstrap repo,
fetched in step 5 below). The summary you are reading is the abridged
operator-facing extract -- it is enough to make an informed accept-or-
decline decision before any code runs.
--------------------------------------------------------------------------------
1. WHAT MiOS IS
--------------------------------------------------------------------------------
MiOS (pronounced "MyOS") is a research-grade, single-user-oriented
Linux operating system delivered as an OCI bootc image. It is NOT a
commercial product, NOT a hardened distribution backed by a vendor
SLA, and NOT an audited reference platform. Treat every script,
postcheck, and architectural claim as an artifact under ongoing
review -- correct in the cases that have been exercised, likely to
need adjustment in cases that have not.
--------------------------------------------------------------------------------
2. LICENSING
--------------------------------------------------------------------------------
* MiOS-owned source is Apache-2.0 (LICENSE)
* Bundled vendor components retain their upstream licenses (LICENSES.md)
* Attribution to every upstream project is recorded in usr/share/doc/mios/reference/credits.md
--------------------------------------------------------------------------------
3. THIRD-PARTY AGREEMENTS THAT APPLY IMPLICITLY
--------------------------------------------------------------------------------
* NVIDIA proprietary GPU drivers + CUDA -- NVIDIA Software License
* Steam (Flatpak) -- Steam Subscriber Agreement on first launch
* Microsoft Windows VM guests (libvirt/QEMU) -- bring your own license
* Flathub apps installed via mios.toml [desktop].flatpaks -- each carries
its own license
* Sigstore-signed images (opt-in via bootc switch --enforce-container-
sigpolicy) -- accept the transparency-log + Fulcio identity model
These are NOT MiOS-specific terms. They are the upstream vendor terms
MiOS surfaces at install time.
--------------------------------------------------------------------------------
4. DATA AND NETWORK POSTURE
--------------------------------------------------------------------------------
* No telemetry. There is no built-in telemetry channel in the image.
* Outbound network calls from a default deployment are limited to:
- Fedora / RPMFusion / Flathub mirrors during build / bootc upgrade
- GitHub Container Registry (ghcr.io) during image fetch
- User-chosen Quadlet workloads (Forgejo, LocalAI, Ollama, Guacamole,...)
- The local AI runtime at MIOS_AI_ENDPOINT (default localhost)
* Operators can audit by inspecting /etc/containers/systemd/,
/usr/lib/systemd/system/, and the active firewalld policy.
* MiOS does not exfiltrate any user data to a vendor cloud.
--------------------------------------------------------------------------------
5. NO WARRANTY
--------------------------------------------------------------------------------
Apache-2.0 'AS IS' clause governs MiOS-owned source. CI covers the
build pipeline, image lint, and postcheck invariants -- NOT full
hardware matrix testing, multi-host upgrade drills, long-running
stability, or production failure modes.
--------------------------------------------------------------------------------
6. TRADEMARKS
--------------------------------------------------------------------------------
Third-party trademarks (Fedora, Universal Blue, NVIDIA, OpenAI,
Anthropic, Google, GitHub, Microsoft, Cline, Cursor, ...) belong to
their respective owners. MiOS references them solely to identify the
upstream component or specification each is part of.
--------------------------------------------------------------------------------
7. YOUR CHOICE