-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPC-AI.ps1
More file actions
2453 lines (2040 loc) · 83 KB
/
PC-AI.ps1
File metadata and controls
2453 lines (2040 loc) · 83 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
#Requires -Version 5.1
<#
.SYNOPSIS
PC-AI - Local LLM-Powered PC Diagnostics Framework
.DESCRIPTION
Unified CLI for PC diagnostics, optimization, USB management, and LLM-powered analysis.
Provides a comprehensive interface to all PC-AI modules including:
- Hardware diagnostics (devices, disks, USB, network adapters)
- Virtualization management (WSL2, Hyper-V, Docker)
- USB/WSL passthrough management
- Network diagnostics and VSock optimization
- Performance monitoring and optimization
- System cleanup (PATH, temp files, duplicates)
- LLM-powered analysis via pcai-inference
.PARAMETER Command
Main command: diagnose, optimize, usb, analyze, chat, llm, cleanup, perf, doctor, status, version, help
.PARAMETER Arguments
Additional arguments for the command
.EXAMPLE
.\PC-AI.ps1 diagnose all
Run full system diagnostics
.EXAMPLE
.\PC-AI.ps1 analyze --report "report.txt"
Analyze diagnostic report with LLM
.EXAMPLE
.\PC-AI.ps1 usb list
List all USB devices
.EXAMPLE
.\PC-AI.ps1 optimize wsl --dry-run
Preview WSL optimization changes
.NOTES
Author: PC_AI Framework
Version: 1.0.0
Requires: Windows 10/11 with PowerShell 5.1+
#>
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[ValidateSet('diagnose', 'optimize', 'usb', 'analyze', 'chat', 'llm', 'cleanup', 'perf', 'media', 'doctor', 'status', 'version', 'help')]
[string]$Command,
[Parameter(Position = 1, ValueFromRemainingArguments)]
[string[]]$Arguments,
# Inference backend selection
[Parameter()]
[ValidateSet('auto', 'llamacpp', 'mistralrs', 'http')]
[string]$InferenceBackend = 'auto',
# Model path for native inference
[Parameter()]
[string]$ModelPath,
# GPU layers for native inference (-1 = all, 0 = CPU only)
[Parameter()]
[int]$GpuLayers = -1,
# Use native inference via FFI instead of HTTP
[Parameter()]
[switch]$UseNativeInference
)
#region Script Configuration
$script:Version = '1.0.0'
$script:ModulesPath = Join-Path $PSScriptRoot 'Modules'
$script:ConfigPath = Join-Path $PSScriptRoot 'Config'
$script:ReportsPath = Join-Path $PSScriptRoot 'Reports'
$script:LoadedModules = @{}
$script:Settings = $null
$script:LLMConfig = $null
$script:InferenceMode = 'http' # 'http' or 'native'
$script:NativeInferenceReady = $false
#endregion
#region Core Module Loading
# Load common module for shared UI and utilities
$script:CommonPath = Join-Path $script:ModulesPath 'PC-AI.Common\PC-AI.Common.psm1'
if (Test-Path $script:CommonPath) {
Import-Module $script:CommonPath -Force
}
#endregion
#region Module Loading Functions
function Ensure-Module {
<#
.SYNOPSIS
Lazy-loads a PC-AI module only when needed
#>
param(
[Parameter(Mandatory)]
[string]$ModuleName
)
if ($script:LoadedModules[$ModuleName]) {
return $true
}
$modulePath = Join-Path $script:ModulesPath "$ModuleName\$ModuleName.psd1"
if (-not (Test-Path $modulePath)) {
Write-Error "Module not found: $ModuleName"
Write-Info "Expected path: $modulePath"
return $false
}
try {
Import-Module $modulePath -Force -ErrorAction Stop
$script:LoadedModules[$ModuleName] = $true
return $true
} catch {
Write-Error "Failed to load module $ModuleName`: $_"
return $false
}
}
function Get-LoadedModules {
return $script:LoadedModules.Keys | Sort-Object
}
#endregion
#region Configuration Functions
function Load-Settings {
if ($null -ne $script:Settings) {
return $script:Settings
}
$settingsPath = Join-Path $script:ConfigPath 'settings.json'
if (Test-Path $settingsPath) {
try {
$script:Settings = Get-Content $settingsPath -Raw | ConvertFrom-Json
return $script:Settings
} catch {
Write-Warning "Could not load settings: $_"
return $null
}
}
return $null
}
function Load-LLMConfig {
if ($null -ne $script:LLMConfig) {
return $script:LLMConfig
}
$llmConfigPath = Join-Path $script:ConfigPath 'llm-config.json'
if (Test-Path $llmConfigPath) {
try {
$script:LLMConfig = Get-Content $llmConfigPath -Raw | ConvertFrom-Json
return $script:LLMConfig
} catch {
Write-Warning "Could not load LLM config: $_"
return $null
}
}
return $null
}
function Initialize-InferenceBackend {
<#
.SYNOPSIS
Initialize the inference backend based on parameters
#>
param(
[string]$Backend,
[string]$ModelPath,
[int]$GpuLayers
)
# Skip if HTTP mode
if ($Backend -eq 'http') {
Write-Verbose 'Using HTTP inference backend'
$script:InferenceMode = 'http'
return $true
}
# Try native inference
Write-Verbose 'Attempting to initialize native inference backend...'
try {
# Load PcaiInference module
$modulePath = Join-Path $script:ModulesPath 'PcaiInference.psm1'
if (-not (Test-Path $modulePath)) {
Write-Warning 'PcaiInference module not found. Falling back to HTTP.'
$script:InferenceMode = 'http'
return $false
}
Import-Module $modulePath -Force -ErrorAction Stop
# Check DLL availability
$status = Get-PcaiInferenceStatus
if (-not $status.DllExists) {
Write-Warning 'pcai_inference.dll not found. Build instructions:'
Write-Warning ' .\Build.ps1 -Component inference'
Write-Warning ' .\Build.ps1 -Component mistralrs # backend-specific'
Write-Warning 'Falling back to HTTP inference.'
$script:InferenceMode = 'http'
return $false
}
# Initialize backend
$backendName = if ($Backend -eq 'auto') { 'mistralrs' } else { $Backend }
$initResult = Initialize-PcaiInference -Backend $backendName -Verbose:$VerbosePreference
if (-not $initResult.Success) {
Write-Warning 'Failed to initialize native backend. Falling back to HTTP.'
$script:InferenceMode = 'http'
return $false
}
# Load model if path provided
if ($ModelPath) {
Write-Verbose "Loading model: $ModelPath"
$loadResult = Import-PcaiModel -ModelPath $ModelPath -GpuLayers $GpuLayers -Verbose:$VerbosePreference
if (-not $loadResult.Success) {
Write-Warning 'Failed to load model. Falling back to HTTP.'
Close-PcaiInference
$script:InferenceMode = 'http'
return $false
}
Write-Info "Native inference ready (backend: $backendName, model: $ModelPath)"
$script:InferenceMode = 'native'
$script:NativeInferenceReady = $true
return $true
} else {
Write-Info "Native backend initialized (backend: $backendName). Model not loaded yet."
Write-Info 'Use Import-PcaiModel to load a model, or inference will fall back to HTTP.'
$script:InferenceMode = 'http' # Fall back until model is loaded
return $false
}
} catch {
Write-Warning "Error initializing native inference: $_"
Write-Warning 'Falling back to HTTP inference.'
$script:InferenceMode = 'http'
return $false
}
}
#endregion
#region Admin Detection Functions
function Test-Administrator {
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Require-Administrator {
param([string]$Operation = 'this operation')
if (-not (Test-Administrator)) {
Write-Error "Administrator privileges required for $Operation"
Write-Info 'Please run PowerShell as Administrator and try again.'
return $false
}
return $true
}
function Warn-NonAdministrator {
param([string]$Operation = 'this operation')
if (-not (Test-Administrator)) {
Write-Warning "Some features of $Operation may require Administrator privileges"
Write-Warning 'Consider running as Administrator for full functionality'
}
}
#endregion
#region Argument Parsing Functions
function Get-ParsedArguments {
param(
[string[]]$InputArgs,
[hashtable]$Defaults = @{}
)
if (-not (Ensure-Module 'PC-AI.CLI')) {
Write-Error 'CLI module unavailable; cannot parse arguments.'
$fallback = @{
SubCommand = $null
Flags = @{}
Values = @{}
Positional = @()
}
foreach ($key in $Defaults.Keys) {
$fallback.Values[$key] = $Defaults[$key]
}
return $fallback
}
return Resolve-PCArguments -InputArgs $InputArgs -Defaults $Defaults
}
#endregion
#region Help System
function Show-MainHelp {
Write-Header "PC-AI v$script:Version - Local LLM-Powered PC Diagnostics"
Write-Host 'USAGE:' -ForegroundColor Yellow
Write-Host ' .\PC-AI.ps1 <command> [subcommand] [options]'
Write-Host ''
Write-Host 'COMMANDS:' -ForegroundColor Yellow
$commandSummaries = @()
if (Ensure-Module 'PC-AI.CLI') {
$commandSummaries = Get-PCCommandSummary -ProjectRoot $PSScriptRoot
}
if ($commandSummaries -and $commandSummaries.Count -gt 0) {
if (-not ($commandSummaries.Command -contains 'doctor')) {
$commandSummaries += [PSCustomObject]@{
Command = 'doctor'
Description = 'Run a one-command health check for common runtime failures.'
}
}
foreach ($summary in $commandSummaries) {
if ($summary.Description) {
Write-Host " $($summary.Command) - $($summary.Description)" -ForegroundColor White
} else {
Write-Host " $($summary.Command)" -ForegroundColor White
}
}
} else {
$commands = @('diagnose', 'optimize', 'usb', 'analyze', 'chat', 'llm', 'cleanup', 'perf', 'media', 'status', 'doctor', 'version', 'help')
foreach ($cmd in $commands) {
Write-Host " $cmd" -ForegroundColor White
}
}
Write-Host ''
Write-Host 'EXAMPLES:' -ForegroundColor Yellow
$examples = @()
if (Ensure-Module 'PC-AI.CLI') {
$examples = Get-PCModuleHelpIndex -ProjectRoot $PSScriptRoot |
Where-Object { $_.Examples -and $_.Examples.Count -gt 0 } |
Select-Object -First 6
}
if ($examples -and $examples.Count -gt 0) {
foreach ($entry in $examples) {
foreach ($example in ($entry.Examples | Select-Object -First 1)) {
$formatted = $example -replace "(`r`n|`n)", "`n "
Write-Host " $formatted"
}
}
} else {
Write-Host ' .\PC-AI.ps1 diagnose all'
Write-Host ' .\PC-AI.ps1 optimize wsl --dry-run'
Write-Host ' .\PC-AI.ps1 usb list'
Write-Host ' .\PC-AI.ps1 analyze'
Write-Host ' .\PC-AI.ps1 help diagnose'
}
Write-Host ''
Write-Host 'Module help is generated dynamically from module implementations.' -ForegroundColor DarkGray
Write-Host "Run '.\\PC-AI.ps1 help <command>' to see module function help." -ForegroundColor DarkGray
}
function Show-ModuleHelp {
param(
[Parameter(Mandatory)]
[string]$CommandName
)
if (-not (Ensure-Module 'PC-AI.CLI')) {
Write-Warning 'Help module unavailable. Showing basic help.'
Show-MainHelp
return
}
$modules = Get-PCCommandModules -CommandName $CommandName -ProjectRoot $PSScriptRoot
if (-not $modules -or $modules.Count -eq 0) {
Show-MainHelp
return
}
$helpEntries = Get-PCModuleHelpIndex -Modules $modules -ProjectRoot $PSScriptRoot
Write-Header "$CommandName - Module Help"
Write-Host 'USAGE:' -ForegroundColor Yellow
Write-Host " .\\PC-AI.ps1 $CommandName <subcommand> [options]"
Write-Host ''
foreach ($group in ($helpEntries | Group-Object Module)) {
Write-SubHeader "$($group.Name)"
foreach ($entry in $group.Group | Sort-Object Name) {
if ($entry.Synopsis) {
Write-Bullet "$($entry.Name) - $($entry.Synopsis)"
} else {
Write-Bullet "$($entry.Name)"
}
}
Write-Host ''
}
}
function Show-HelpEntry {
param(
[Parameter(Mandatory)]
[object]$Entry
)
Write-Header "$($Entry.Name) - Help"
if ($Entry.Synopsis) {
Write-SubHeader 'Synopsis'
Write-Host $Entry.Synopsis
Write-Host ''
}
if ($Entry.Parameters -and $Entry.Parameters.Count -gt 0) {
Write-SubHeader 'Parameters'
if ($Entry.ParameterHelp -and $Entry.ParameterHelp.Count -gt 0) {
foreach ($paramName in $Entry.Parameters) {
$paramDesc = $Entry.ParameterHelp[$paramName]
if ($paramDesc) {
Write-Host (' {0} - {1}' -f $paramName, $paramDesc)
} else {
Write-Host (' {0}' -f $paramName)
}
}
} else {
Write-Host ($Entry.Parameters -join ', ')
}
Write-Host ''
}
if ($Entry.Description) {
Write-SubHeader 'Description'
Write-Host $Entry.Description
Write-Host ''
}
if ($Entry.Examples -and $Entry.Examples.Count -gt 0) {
Write-SubHeader 'Examples'
foreach ($example in $Entry.Examples) {
$formatted = $example -replace "(`r`n|`n)", "`n "
Write-Host " $formatted"
Write-Host ''
}
}
if ($Entry.SourcePath) {
Write-SubHeader 'Source'
Write-Host $Entry.SourcePath -ForegroundColor DarkGray
}
}
function Show-Help {
param([string]$Topic)
$knownCommands = @()
if (Ensure-Module 'PC-AI.CLI') {
$knownCommands = Get-PCCommandList -ProjectRoot $PSScriptRoot
}
if (-not $knownCommands -or $knownCommands.Count -eq 0) {
$knownCommands = @('diagnose', 'optimize', 'usb', 'analyze', 'chat', 'llm', 'cleanup', 'perf', 'media', 'doctor', 'status', 'version', 'help')
}
if (-not $Topic) {
Show-MainHelp
return
}
if ($knownCommands -contains $Topic) {
Show-ModuleHelp -CommandName $Topic
return
}
if (Ensure-Module 'PC-AI.CLI') {
$entry = Get-PCModuleHelpEntry -Name $Topic -ProjectRoot $PSScriptRoot | Select-Object -First 1
if ($entry) {
Show-HelpEntry -Entry $entry
return
}
}
Show-MainHelp
}
#endregion
#region Command Implementations
#region Diagnose Commands
function Invoke-DiagnoseCommand {
param([string[]]$CmdArgs)
$parsed = Get-ParsedArguments -InputArgs $CmdArgs -Defaults @{
output = $null
format = 'txt'
days = 3
}
$subCommand = $parsed.SubCommand
switch ($subCommand) {
'hardware' {
Warn-NonAdministrator 'hardware diagnostics'
if (-not (Ensure-Module 'PC-AI.Hardware')) { return }
Write-Header 'Hardware Diagnostics'
Write-SubHeader 'Device Manager Errors'
$deviceErrors = Get-DeviceErrors
if ($deviceErrors) {
$deviceErrors | ForEach-Object {
Write-Bullet "$($_.Name) - Error Code: $($_.ConfigManagerErrorCode)" -Color Red
}
} else {
Write-Success 'No device errors found'
}
Write-SubHeader 'Disk Health (SMART)'
$diskHealth = Get-DiskHealth
$diskHealth | ForEach-Object {
$color = if ($_.Status -eq 'OK') { 'Green' } else { 'Red' }
Write-Bullet "$($_.Model) - Status: $($_.Status)" -Color $color
}
Write-SubHeader 'USB Device Status'
$usbStatus = Get-UsbStatus
Write-Bullet "USB Controllers: $($usbStatus.Controllers)"
Write-Bullet "Connected Devices: $($usbStatus.Devices)"
Write-SubHeader 'Network Adapters'
$adapters = Get-NetworkAdapters
$adapters | Where-Object { $_.PhysicalAdapter } | ForEach-Object {
$status = if ($_.NetEnabled) { 'Connected' } else { 'Disconnected' }
$color = if ($_.NetEnabled) { 'Green' } else { 'Yellow' }
Write-Bullet "$($_.Name) - $status" -Color $color
}
}
'wsl' {
if (-not (Ensure-Module 'PC-AI.Virtualization')) { return }
Write-Header 'WSL2 Diagnostics'
$wslStatus = Get-WSLStatus
Write-SubHeader 'WSL Status'
Write-Bullet "Version: $($wslStatus.Version)"
Write-Bullet "Default Distribution: $($wslStatus.DefaultDistribution)"
if ($wslStatus.Distributions) {
Write-SubHeader 'Distributions'
$wslStatus.Distributions | ForEach-Object {
$color = if ($_.State -eq 'Running') { 'Green' } else { 'Gray' }
Write-Bullet "$($_.Name) (WSL$($_.Version)) - $($_.State)" -Color $color
}
}
if ($wslStatus.NetworkInfo) {
Write-SubHeader 'Network Configuration'
Write-Bullet "IP Address: $($wslStatus.NetworkInfo.IPAddress)"
Write-Bullet "Gateway: $($wslStatus.NetworkInfo.Gateway)"
}
}
'network' {
if (-not (Ensure-Module 'PC-AI.Network')) { return }
Write-Header 'Network Diagnostics'
$netDiag = Get-NetworkDiagnostics
Write-SubHeader 'Network Adapters'
$netDiag.Adapters | ForEach-Object {
$color = if ($_.Status -eq 'Up') { 'Green' } else { 'Yellow' }
Write-Bullet "$($_.Name) - $($_.Status)" -Color $color
}
Write-SubHeader 'Connectivity Tests'
$netDiag.Connectivity | ForEach-Object {
$color = if ($_.Success) { 'Green' } else { 'Red' }
Write-Bullet "$($_.Target): $(if ($_.Success) { 'OK' } else { 'Failed' })" -Color $color
}
}
'hyperv' {
if (-not (Require-Administrator 'Hyper-V diagnostics')) { return }
if (-not (Ensure-Module 'PC-AI.Virtualization')) { return }
Write-Header 'Hyper-V Diagnostics'
$hypervStatus = Get-HyperVStatus
Write-SubHeader 'Hyper-V Status'
$color = if ($hypervStatus.Enabled) { 'Green' } else { 'Red' }
Write-Bullet "Hyper-V Enabled: $($hypervStatus.Enabled)" -Color $color
if ($hypervStatus.VMs) {
Write-SubHeader 'Virtual Machines'
$hypervStatus.VMs | ForEach-Object {
Write-Bullet "$($_.Name) - $($_.State)"
}
}
}
'docker' {
if (-not (Ensure-Module 'PC-AI.Virtualization')) { return }
Write-Header 'Docker Diagnostics'
$dockerStatus = Get-DockerStatus
Write-SubHeader 'Docker Desktop Status'
$color = if ($dockerStatus.Running) { 'Green' } else { 'Red' }
Write-Bullet "Running: $($dockerStatus.Running)" -Color $color
if ($dockerStatus.Version) {
Write-Bullet "Version: $($dockerStatus.Version)"
}
if ($dockerStatus.Containers) {
Write-SubHeader 'Containers'
Write-Bullet "Running: $($dockerStatus.Containers.Running)"
Write-Bullet "Stopped: $($dockerStatus.Containers.Stopped)"
}
}
'events' {
Warn-NonAdministrator 'event log analysis'
if (-not (Ensure-Module 'PC-AI.Hardware')) { return }
$days = [int]$parsed.Values['days']
Write-Header "System Events (Last $days Days)"
$events = Get-SystemEvents -Days $days
if ($events.Critical) {
Write-SubHeader 'Critical Events'
$events.Critical | Select-Object -First 10 | ForEach-Object {
Write-Bullet "$($_.TimeCreated): $($_.Message)" -Color Red
}
}
if ($events.Error) {
Write-SubHeader 'Error Events'
$events.Error | Select-Object -First 10 | ForEach-Object {
Write-Bullet "$($_.TimeCreated): $($_.Message)" -Color Yellow
}
}
if (-not $events.Critical -and -not $events.Error) {
Write-Success 'No critical or error events found'
}
}
'all' {
Warn-NonAdministrator 'full system diagnostics'
if (-not (Ensure-Module 'PC-AI.Hardware')) { return }
Write-Header 'Full System Diagnostics'
$outputPath = $parsed.Values['output']
if (-not $outputPath) {
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$outputPath = Join-Path $script:ReportsPath "Diagnostics-$timestamp.txt"
}
# Ensure Reports directory exists
$reportsDir = Split-Path $outputPath -Parent
if (-not (Test-Path $reportsDir)) {
New-Item -Path $reportsDir -ItemType Directory -Force | Out-Null
}
Write-Info 'Generating comprehensive diagnostic report...'
Write-Info "Output: $outputPath"
try {
$report = New-DiagnosticReport -OutputPath $outputPath
Write-Success 'Diagnostic report generated successfully'
Write-Info "Report saved to: $outputPath"
# Show summary
if ($report.Summary) {
Write-SubHeader 'Summary'
Write-Bullet "Device Errors: $($report.Summary.DeviceErrors)"
Write-Bullet "Disk Issues: $($report.Summary.DiskIssues)"
Write-Bullet "Network Issues: $($report.Summary.NetworkIssues)"
}
} catch {
Write-Error "Failed to generate report: $_"
}
}
default {
if ($subCommand) {
Write-Error "Unknown diagnose subcommand: $subCommand"
}
Show-ModuleHelp -CommandName 'diagnose'
}
}
}
#endregion
#region Optimize Commands
function Invoke-OptimizeCommand {
param([string[]]$CmdArgs)
$parsed = Get-ParsedArguments -InputArgs $CmdArgs -Defaults @{
profile = 'default'
backup = 'true'
}
$subCommand = $parsed.SubCommand
$dryRun = $parsed.Flags['dry-run'] -or $parsed.Flags['n']
$force = $parsed.Flags['force'] -or $parsed.Flags['f']
switch ($subCommand) {
'wsl' {
if (-not (Require-Administrator 'WSL optimization')) { return }
if (-not (Ensure-Module 'PC-AI.Virtualization')) { return }
Write-Header 'WSL2 Optimization'
if ($dryRun) {
Write-Info '[DRY RUN] Showing proposed changes...'
}
try {
$result = Optimize-WSLConfig -DryRun:$dryRun -Force:$force
if ($result.Changes) {
Write-SubHeader 'Proposed/Applied Changes'
$result.Changes | ForEach-Object {
Write-Bullet $_
}
}
if (-not $dryRun -and $result.Success) {
Write-Success 'WSL optimization completed successfully'
if ($result.RestartRequired) {
Write-Warning 'WSL restart required. Run: wsl --shutdown'
}
}
} catch {
Write-Error "WSL optimization failed: $_"
}
}
'disk' {
if (-not (Require-Administrator 'disk optimization')) { return }
if (-not (Ensure-Module 'PC-AI.Performance')) { return }
Write-Header 'Disk Optimization'
if ($dryRun) {
Write-Info '[DRY RUN] Showing disk optimization plan...'
}
try {
$result = Optimize-Disks -DryRun:$dryRun -Force:$force
if ($result.Disks) {
Write-SubHeader 'Optimization Results'
$result.Disks | ForEach-Object {
$action = if ($_.IsSSD) { 'TRIM' } else { 'Defrag' }
Write-Bullet "$($_.DriveLetter): $action - $($_.Status)"
}
}
} catch {
Write-Error "Disk optimization failed: $_"
}
}
'vsock' {
if (-not (Require-Administrator 'VSock optimization')) { return }
if (-not (Ensure-Module 'PC-AI.Network')) { return }
Write-Header 'VSock Optimization'
$profile = $parsed.Values['profile']
if ($dryRun) {
Write-Info "[DRY RUN] Profile: $profile"
}
try {
$result = Optimize-VSock -Profile $profile -DryRun:$dryRun
if ($result.Settings) {
Write-SubHeader 'VSock Settings'
$result.Settings | ForEach-Object {
Write-Bullet "$($_.Name): $($_.Value)"
}
}
if ($result.Success -and -not $dryRun) {
Write-Success 'VSock optimization completed'
}
} catch {
Write-Error "VSock optimization failed: $_"
}
}
'defender' {
if (-not (Require-Administrator 'Defender exclusions')) { return }
if (-not (Ensure-Module 'PC-AI.Virtualization')) { return }
Write-Header 'Windows Defender Exclusions'
if ($dryRun) {
Write-Info '[DRY RUN] Showing proposed exclusions...'
}
try {
$result = Set-WSLDefenderExclusions -DryRun:$dryRun
if ($result.Exclusions) {
Write-SubHeader 'Exclusions'
$result.Exclusions | ForEach-Object {
Write-Bullet "$($_.Type): $($_.Path)"
}
}
if ($result.Success -and -not $dryRun) {
Write-Success 'Defender exclusions configured'
}
} catch {
Write-Error "Failed to set exclusions: $_"
}
}
'network' {
if (-not (Require-Administrator 'network repair')) { return }
if (-not (Ensure-Module 'PC-AI.Virtualization')) { return }
Write-Header 'WSL Network Repair'
if ($dryRun) {
Write-Info '[DRY RUN] Showing repair actions...'
}
try {
$result = Repair-WSLNetworking -DryRun:$dryRun
if ($result.Actions) {
Write-SubHeader 'Repair Actions'
$result.Actions | ForEach-Object {
Write-Bullet $_
}
}
if ($result.Success -and -not $dryRun) {
Write-Success 'Network repair completed'
}
} catch {
Write-Error "Network repair failed: $_"
}
}
default {
if ($subCommand) {
Write-Error "Unknown optimize subcommand: $subCommand"
}
Show-ModuleHelp -CommandName 'optimize'
}
}
}
#endregion
#region USB Commands
function Invoke-UsbCommand {
param([string[]]$CmdArgs)
$parsed = Get-ParsedArguments -InputArgs $CmdArgs -Defaults @{
distribution = $null
busid = $null
}
$subCommand = $parsed.SubCommand
$unbind = $parsed.Flags['unbind']
if (-not (Ensure-Module 'PC-AI.USB')) { return }
switch ($subCommand) {
'list' {
Write-Header 'USB Devices'
try {
$devices = Get-UsbDeviceList
if ($devices) {
$devices | ForEach-Object {
$state = if ($_.Attached) { '[Attached to WSL]' } else { '' }
$color = if ($_.Attached) { 'Green' } else { 'White' }
Write-Host " $($_.BusId) " -NoNewline -ForegroundColor Cyan
Write-Host "$($_.Description) $state" -ForegroundColor $color
}
} else {
Write-Info 'No USB devices found'
}
} catch {
Write-Error "Failed to list USB devices: $_"
}
}
'attach' {
if (-not (Require-Administrator 'USB attach')) { return }
$busid = $parsed.Values['busid']
if (-not $busid -and $parsed.Positional) {
$busid = $parsed.Positional[0]
}
if (-not $busid) {
Write-Error 'Bus ID required. Use: PC-AI usb attach --busid <id>'
Write-Info "Run 'PC-AI usb list' to see available devices"
return
}
$distribution = $parsed.Values['distribution']
Write-Header 'Attaching USB Device'
Write-Info "Bus ID: $busid"
if ($distribution) {
Write-Info "Distribution: $distribution"
}
try {
$result = Mount-UsbToWSL -BusId $busid -Distribution $distribution
if ($result.Success) {
Write-Success 'Device attached successfully'
} else {
Write-Error "Failed to attach device: $($result.Error)"
}
} catch {
Write-Error "Failed to attach USB device: $_"
}
}
'detach' {
if (-not (Require-Administrator 'USB detach')) { return }
$busid = $parsed.Values['busid']
if (-not $busid -and $parsed.Positional) {
$busid = $parsed.Positional[0]
}
if (-not $busid) {
Write-Error 'Bus ID required. Use: PC-AI usb detach --busid <id>'
return
}
Write-Header 'Detaching USB Device'
Write-Info "Bus ID: $busid"
try {
$result = Dismount-UsbFromWSL -BusId $busid -Unbind:$unbind
if ($result.Success) {
Write-Success 'Device detached successfully'
if ($unbind) {
Write-Info 'Device unbound from usbipd'
}
} else {
Write-Error "Failed to detach device: $($result.Error)"
}
} catch {
Write-Error "Failed to detach USB device: $_"
}
}
'status' {
Write-Header 'USB/WSL Passthrough Status'
try {
$status = Get-UsbWSLStatus
Write-SubHeader 'usbipd Status'
$color = if ($status.UsbIpdInstalled) { 'Green' } else { 'Red' }
Write-Bullet "usbipd-win Installed: $($status.UsbIpdInstalled)" -Color $color
if ($status.AttachedDevices) {
Write-SubHeader 'Attached to WSL'
$status.AttachedDevices | ForEach-Object {
Write-Bullet "$($_.BusId): $($_.Description)" -Color Green
}
}
if ($status.BoundDevices) {
Write-SubHeader 'Bound (Ready to Attach)'
$status.BoundDevices | ForEach-Object {
Write-Bullet "$($_.BusId): $($_.Description)" -Color Yellow
}
}
} catch {
Write-Error "Failed to get USB status: $_"
}
}
'bind' {
if (-not (Require-Administrator 'USB bind')) { return }