-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGemmaCLI.ps1
More file actions
1389 lines (1189 loc) · 65.3 KB
/
GemmaCLI.ps1
File metadata and controls
1389 lines (1189 loc) · 65.3 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
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
# =========================================================================================
# PRE-FLIGHT & AUTO-UNBLOCKER (Fix for GitHub / Internet Downloads)
# =========================================================================================
$script:scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
try {
# 1. Elevate the current session's policy so we can actually load our libraries.
# This ONLY affects this specific window/process, not your global system settings.
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force -ErrorAction SilentlyContinue
# 2. Recursively unblock all project files (Removes "Mark of the Web")
Get-ChildItem -Path $script:scriptDir -Recurse -Include *.ps1,*.js,*.json -ErrorAction SilentlyContinue | Unblock-File -ErrorAction SilentlyContinue
} catch {
Write-Host "`n [!] Security Warning: Windows is blocking this script's libraries." -ForegroundColor Yellow
Write-Host " [!] Please run this command in a NEW PowerShell window to fix permanently:" -ForegroundColor Gray
Write-Host " Unblock-File -Path '$PSCommandPath'`n" -ForegroundColor Cyan
}
# Disable Expect100Continue handshake to prevent 417 errors and reduce latency
[System.Net.ServicePointManager]::Expect100Continue = $false
# Ensure UTF-8 output for emoji and Unicode rendering
# ====================== UNICODE CHARS ======================
$TL = [char]0x256D; $TR = [char]0x256E; $BL = [char]0x2570; $BR = [char]0x256F
$H = [char]0x2500; $V = [char]0x2502; $ARR = [char]0x2192; $CHK = [char]0x2713
$CRS = [char]0x2717; $DOT = [char]0x25CF; $BUL = [char]0x2022; $BLK = [char]0x2588
$LBK = [char]0x2591; $WRN = [char]0x26A0
# =========================================================================================
# SCRIPT INITIALIZATION
# =========================================================================================
# 1. Define Script Directory
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
# ====================== LOAD SETTINGS ======================
$settingsPath = Join-Path $scriptDir "config/settings.json"
$script:Settings = @{}
if (Test-Path $settingsPath) {
try {
$rawSettings = Get-Content $settingsPath | ConvertFrom-Json
if ($rawSettings) {
foreach ($prop in $rawSettings.PSObject.Properties) {
$script:Settings[$prop.Name] = $prop.Value
}
# Apply hidden network settings
if ($null -ne $script:Settings.disable_expect_100) {
[System.Net.ServicePointManager]::Expect100Continue = (-not $script:Settings.disable_expect_100)
}
}
} catch { }
}
# ====================== CORE REGISTRY & CONSTANTS ======================
# Dynamically load from settings, or fallback to safety if missing
$script:MODEL_REGISTRY = if ($script:Settings.model_registry) {
$script:Settings.model_registry
} else {
[ordered]@{
"gemma-ultra" = @{ id = "gemma-3-27b-it"; label = "Gemma Ultra (27B)"; desc = "Highest reasoning & logic" }
}
}
# Default to Ultra unless specified in settings
$script:MODEL_HANDLE = if ($script:Settings.current_model_handle) { $script:Settings.current_model_handle } else { "gemma-ultra" }
# Resolve handle to ID for API calls
$script:MODEL = $script:MODEL_REGISTRY.$($script:MODEL_HANDLE).id
$script:BASE_URI_BASE = "https://generativelanguage.googleapis.com/v1beta/models"
# Tool limits mapped to model IDs (for legacy compatibility) or Handles
$script:TOOL_LIMITS = @{
"gemma-4-31b-it" = 12
"gemma-4-26b-a4b-it" = 12
"gemma-3-27b-it" = 12
"gemma-3-12b-it" = 8
"gemma-3-4b-it" = 2
"gemma-3n-e4b-it" = 2
"gemma-3n-e2b-it" = 2
"gemma-3-1b-it" = 0
}
# 2. Source All Library Modules
. (Join-Path $scriptDir "lib/ToolLoader.ps1")
. (Join-Path $scriptDir "lib/Api.ps1")
. (Join-Path $scriptDir "lib/UI.ps1")
. (Join-Path $scriptDir "lib/History.ps1")
# ====================== DEBUG =======================
$script:debugMode = $false
# 4. Load API Key (Requires UI functions for Draw-Box)
# ====================== SECURE API KEY STORAGE ======================
$script:configDir = Join-Path $env:APPDATA "GemmaCLI"
function Initialize-TTS {
if (-not $global:GemmaTTS) {
try {
Add-Type -AssemblyName System.Speech
$global:GemmaTTS = New-Object System.Speech.Synthesis.SpeechSynthesizer
# Default to a female voice if available
$global:GemmaTTS.SelectVoiceByHints([System.Speech.Synthesis.VoiceGender]::Female)
} catch {
Write-Host " [!] Could not initialize Windows TTS." -ForegroundColor Red
return $false
}
}
return $true
}
function Format-TextForSpeech {
param([string]$text)
if ([string]::IsNullOrWhiteSpace($text)) { return "" }
# Strip thoughts, channels, and code blocks
$clean = $text -replace '(?s)<thought>.*?</thought>', ''
$clean = $clean -replace '(?s)<\|channel>thought.*?<channel\|>', ''
$clean = $clean -replace '(?s)<code_block>.*?</code_block>', ' [Code block omitted] '
$clean = $clean -replace '(?s)```.*?```', ' [Code block omitted] '
# Strip markdown markers
$clean = $clean -replace '\*\*', ''
$clean = $clean -replace '\*', ''
return $clean.Trim()
}
function Save-ApiKey {
param([string]$apiKey)
Save-StoredKey -apiKey $apiKey -keyName "gemmacli"
Draw-Box @("$CHK API key saved securely (Windows user-only encryption)") -Color Green
}
# ====================== LOAD API KEY ======================
$API_KEY = $env:GEMMA_API_KEY
if (-not $API_KEY) { $API_KEY = Get-StoredKey -keyName "gemmacli" }
if (-not $API_KEY) {
Write-Host "`n=== First-time setup (Gemma API) ===" -ForegroundColor Cyan
Write-Host "Get your free Gemma API key here:" -ForegroundColor Yellow
Write-Host "https://aistudio.google.com/app/apikey`n" -ForegroundColor Gray
do {
$secureInput = Read-Host "Enter your Gemma API key" -AsSecureString
$plainKey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureInput))
$confirmInput = Read-Host "Confirm key (paste again)" -AsSecureString
$confirm = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($confirmInput))
if ($plainKey -ne $confirm) { Write-Host "$CRS Keys do not match. Try again." -ForegroundColor Red }
elseif ([string]::IsNullOrWhiteSpace($plainKey)) { Write-Host "$CRS API key cannot be empty." -ForegroundColor Red }
} while ($plainKey -ne $confirm -or [string]::IsNullOrWhiteSpace($plainKey))
Save-ApiKey $plainKey
$API_KEY = $plainKey
} else {
Write-Host "$CHK Gemma API key loaded successfully" -ForegroundColor DarkGray
}
$script:API_KEY = $API_KEY
# ====================== API ORCHESTRATION (lib/Api.ps1) ======================
# 5. Load Intelligence File
# ====================== LOAD INTELLIGENCE ======================
$configPath = Join-Path $scriptDir "instructions.json"
$script:intelligence = try {
if (Test-Path $configPath) {
$json = Get-Content $configPath -Raw | ConvertFrom-Json
if ($null -eq $json.system_prompt) { throw "Invalid JSON structure" }
$json
} else { throw "File not found" }
} catch {
[PSCustomObject]@{
system_prompt = "You are Gemma, a helpful assistant."
guardrails = @{ max_output_tokens = 8192; temperature = 0.7; top_p = 0.95 }
}
}
# 6. Define Remaining Script Variables
# ====================== GUARDRAILS & STATUS ======================
$script:GUARDRAILS = @{
maxOutputTokens = if ($script:intelligence.guardrails.max_output_tokens) { [int]$script:intelligence.guardrails.max_output_tokens } else { 8192 };
temperature = if ($script:intelligence.guardrails.temperature) { [float]$script:intelligence.guardrails.temperature } else { 0.7 };
topP = if ($script:intelligence.guardrails.top_p) { [float]$script:intelligence.guardrails.top_p } else { 0.95 }
}
# $CONTEXT_WINDOW = 128000
$script:lastStatus = @{ prompt = 0; candidate = 0; total = 0; finish = "" }
$script:lastApiCall = (Get-Date).AddSeconds(-10) # main loop Gemma calls
$script:lastApiCall_Gemini = (Get-Date).AddSeconds(-10) # dual-agent Gemini calls
$script:apiCallLog_Gemma = [System.Collections.Generic.List[datetime]]::new() # Gemma RPM tracker
$script:apiCallLog_Gemini = [System.Collections.Generic.List[datetime]]::new() # Gemini RPM tracker (separate quota)
# ====================== SYSTEM PROMPT (lib/Api.ps1) ======================
# ====================== RATE LIMITING ======================
# ====================== API ORCHESTRATION (lib/Api.ps1) ======================
# ====================== DUAL-AGENT (lib/Api.ps1) ======================
function Initialize-ToolKeys {
foreach ($tool in @($script:TOOLS.Values)) {
if ($tool.RequiresKey) {
$existing = Get-StoredKey -keyName $tool.Name
if (-not $existing) {
Write-Host "`n=== Tool Setup: $($tool.Name) ===" -ForegroundColor Cyan
Write-Host "This tool requires an API key. Get it here:" -ForegroundColor Yellow
Write-Host "$($tool.KeyUrl)`n" -ForegroundColor Gray
Write-Host "(Press Escape to cancel and disable this tool)`n" -ForegroundColor DarkGray
$cancelled = $false
$plainKey = ""
do {
$secureInput = Read-SecureStringWithCancel -Prompt "Enter API key for $($tool.Name)"
if ($null -eq $secureInput) { $cancelled = $true; break }
$plainKey = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureInput))
$confirm = Read-HostWithCancel -Prompt "Confirm API key (paste again)"
if ($null -eq $confirm) { $cancelled = $true; break }
if ($plainKey -ne $confirm) {
Write-Host "$CRS Keys do not match. Try again." -ForegroundColor Red
$plainKey = ""
}
elseif ([string]::IsNullOrWhiteSpace($plainKey)) {
Write-Host "$CRS API key cannot be empty." -ForegroundColor Red
}
} while ($plainKey -ne $confirm -or [string]::IsNullOrWhiteSpace($plainKey))
if ($cancelled) {
Write-Host "`nSetup cancelled. Disabling tool '$($tool.Name)'..." -ForegroundColor Yellow
if (Test-Path "tools\$($tool.Name).ps1") {
Move-Item -Path "tools\$($tool.Name).ps1" -Destination "more_tools/" -Force
$script:TOOLS.Remove($tool.Name)
}
} else {
Save-StoredKey -apiKey $plainKey -keyName $tool.Name
Draw-Box @("$CHK API key for '$($tool.Name)' saved securely.") -Color Green
}
}
}
}
}
function Update-SystemPrompt {
param([bool]$resetHistory = $false)
$toolBlock = Get-ToolInstructions -ScriptRoot $scriptDir -Model $script:MODEL -ToolLimits $script:TOOL_LIMITS
$prompt = Get-SystemPrompt
$prompt = $prompt -replace "%%AVAILABLE_TOOLS%%", $toolBlock
# Initialize keys for any newly loaded/refreshed tools
Initialize-ToolKeys
# Onboarding Injection
$onboarding = ""
if ($script:TOOLS.ContainsKey("tutorial")) {
$onboarding = "ONBOARDING: The 'tutorial' tool is active. You MUST call it immediately to receive your mission instructions for this session."
}
$prompt = $prompt -replace "%%ONBOARDING_NOTICE%%", $onboarding
# Latent Awareness Injection
$latent = ""
if ($script:INACTIVE_COUNT -gt 0) {
$latent = "SYSTEM NOTICE: There are currently $($script:INACTIVE_COUNT) inactive tools in your repository. If you encounter a request that requires a capability you do not currently possess, suggest that the user check '/settings' or '/tools disabled' to enable more capabilities."
}
$prompt = $prompt -replace "%%LATENT_AWARENESS_NOTICE%%", $latent
$prompt = "[SYSTEM]: Current date and time: $(Get-Date -Format 'dddd, MMMM dd yyyy HH:mm')`n`n" + $prompt
$script:systemPrompt = $prompt
if ($resetHistory -or $null -eq $script:history -or $script:history.Count -eq 0) {
$script:history = @(
@{ role = "user"; parts = @(@{ text = $script:systemPrompt }) },
@{ role = "model"; parts = @(@{ text = "Acknowledged. Gemma CLI [SYSTEM] protocols active. Standing by for instructions." }) }
)
} else {
# Update index 0 (system instructions) without wiping conversation turns
$script:history[0].parts[0].text = $script:systemPrompt
}
}
# Initial build
Update-SystemPrompt
# ====================== LOAD MEMORY ======================
$appDataGemma = Join-Path $env:APPDATA "GemmaCLI"
$memoryFile = Join-Path $appDataGemma "memory.json"
$script:historyFile = Join-Path $appDataGemma "last_session.json"
# ====================== LOAD CUSTOM COMMANDS ======================
$customCommandsPath = Join-Path $scriptDir "config/custom_commands.json"
$script:customCommands = @{}
if (Test-Path $customCommandsPath) {
$jsonObject = Get-Content -Path $customCommandsPath | ConvertFrom-Json
$hashtable = @{}
if ($jsonObject) {
foreach ($property in $jsonObject.PSObject.Properties) {
$hashtable[$property.Name] = $property.Value
}
}
$script:customCommands = $hashtable
}
# ====================== COLOR SCHEMES ======================
$script:DefaultColors = @{
input_highlight = "DarkMagenta"
input_text = "Gray"
gemma_response = "Green"
ui_boxes = "Cyan"
system_status = "Cyan"
user_label = "Gray"
custom_command = "Magenta"
}
$script:AlternativeColors = @{
input_highlight = "DarkBlue"
input_text = "White"
gemma_response = "Yellow"
ui_boxes = "Cyan"
system_status = "Cyan"
user_label = "White"
custom_command = "Cyan"
}
$scheme = if ($script:Settings.color_scheme) { $script:Settings.color_scheme } else { "default" }
if ($scheme -eq "alternative") {
$script:Colors = $script:AlternativeColors
} else {
$script:Colors = $script:DefaultColors
}
# ====================== CONTEXT MODE INIT ======================
$contextMode = if ($script:Settings.context_mode) { $script:Settings.context_mode } else { "standard" }
if ($contextMode -eq "large") {
$script:CONTEXT_LIMIT = 128000
$script:TRIM_THRESHOLD = 60000
} else {
$script:CONTEXT_LIMIT = 15000
$script:TRIM_THRESHOLD = 11000
}
# ====================== SPLASH ======================
$startupDelay = if ($script:Settings.startup_delay) { [int]$script:Settings.startup_delay } else { 0 }
if ($startupDelay -gt 0) { Start-Sleep -Seconds $startupDelay }
Clear-Host
Write-Host ""
Write-Host " .oooooo. oooooooooooo ooo ooooo ooo ooooo .o. " -ForegroundColor Magenta
Write-Host " d8P' 'Y8b '888' '8 '88. .888' '88. .888' .888. " -ForegroundColor Magenta
Write-Host "888 888 888b d'888 888b d'888 .8'888. " -ForegroundColor Magenta
Write-Host "888 888oooo8 8 Y88. .P 888 8 Y88. .P 888 .8' '888. " -ForegroundColor Magenta
Write-Host "888 ooooo 888 ' 8 '888' 888 8 '888' 888 .88ooo8888. " -ForegroundColor Magenta
Write-Host "'88. .88' 888 o 8 Y 888 8 Y 888 .8' '888. " -ForegroundColor Magenta
Write-Host " 'Y8bood8P' o888ooooood8 o8o o888o o8o o888o o88o o8888o" -ForegroundColor Magenta
Write-Host ""
$helpLines = @(
"/help $ARR Show all commands",
"/clear $ARR Reset conversation",
"/speak [m/f] $ARR Toggle Text-to-Speech (TTS) output",
"/listen $ARR Enable Speech-to-Text (STT) input",
"/recall $ARR Load memories from previous sessions",
"/resume $ARR Resume last conversation session",
"/multiline $ARR Multiline mode - end with /end",
"/refresh $ARR Hot-reload tools and system prompt",
"/model [id] $ARR Switch model / pass id directly",
"/tools [all] $ARR Show enabled/disabled/all tools",
"/settings $ARR Manage system settings",
"/customCommand $ARR List/Create your custom commands",
"/bigBrother [q] $ARR Dual model pipeline, Gemini > Gemma > Gemini",
"/littleSister [q] $ARR Dual model pipeline, Gemma > Gemini > Gemma",
"/debug $ARR Toggle debug output",
"/trim $ARR Force manual context trim",
"/resetkey $ARR Delete saved key & re-prompt",
"/exit $ARR Quit"
)
Draw-Box $helpLines -Title "Gemma CLI v0.8.1 $BUL (C) 2026 SpdrByte Labs $BUL AGPL-3.0 License" -Width 80 -Color $script:Colors.ui_boxes
Write-Host ""
# ====================== MAIN LOOP ======================
while ($true) {
# Dark Purple Entire Row Highlight for Input
$esc = [char]27
# Map friendly color names to ANSI if needed, but for now we'll stick to basic colors or keep the purple logic
# The requirement was "don't reuse same colors", so let's use the scheme's highlight
$bgRGB = if ($scheme -eq "alternative") { "0;0;100" } else { "40;0;40" }
$highlightColor = "$esc[48;2;$($bgRGB)m"
$reset = "$esc[0m"
# Write the row start and header
Write-Host "$highlightColor$($esc)[K You" -NoNewline -ForegroundColor $script:Colors.user_label
# 1. Print bar AFTER user prompt line always.
$startX = [Console]::CursorLeft
$startY = [Console]::CursorTop
# Ensure there is a line below for the bar if we are at the bottom
if ($startY -ge ([Console]::BufferHeight - 1)) {
[Console]::WriteLine()
$startY--
[Console]::SetCursorPosition($startX, $startY)
}
$barRow = $startY + 1
[Console]::SetCursorPosition(0, $barRow)
$text = Get-StatusBarText
$w = [Console]::WindowWidth
$paddedText = if ($text.Length -gt ($w - 1)) { $text.Substring(0, $w - 1) } else { $text.PadRight($w - 1) }
Write-Host $paddedText -ForegroundColor $script:Colors.system_status -BackgroundColor DarkBlue -NoNewline
# Return cursor to prompt position for user to type
[Console]::SetCursorPosition($startX, $startY)
# Start polling tracker — moves bar down if user input wraps to new line
Start-BarTracker -InitialBarRow $barRow -HighlightANSI $highlightColor
# Use the ANSI code as a prefix for Read-Host to keep the background purple while typing
$userInput = Read-Host "$highlightColor"
$endY = [Console]::CursorTop
Write-Host -NoNewline $reset # Reset immediately after enter
# Stop tracker, get final bar row, erase it
Stop-BarTracker
$finalBarRow = $script:barRow
if ($finalBarRow -lt [Console]::BufferHeight) {
[Console]::SetCursorPosition(0, $finalBarRow)
Write-Host (" " * ($w - 1)) -NoNewline
[Console]::SetCursorPosition(0, $endY)
}
if ($userInput -eq "exit" -or $userInput -eq "/exit") { break }
if ($userInput -eq "/multiline") {
$pastelines =@()
Write-Host "Multiline mode - [end with /end on its own line]" -ForegroundColor DarkGray
while ($true) {
$pasteline = Read-Host
if ($pasteline -eq "/end") { break }
$pastelines += $pasteline
}
$userInput = $pastelines -join "`n"
}
if ($userInput -eq "/clear") {
$script:history = @($script:history[0])
Draw-Box @("$CHK Conversation cleared.") -Color Yellow
continue
}
if ($userInput -match '^/speak\s*(.*)$') {
$arg = $matches[1].Trim().ToLower()
if ($arg -eq "male" -or $arg -eq "m" -or $arg -eq "female" -or $arg -eq "f") {
$script:ttsEnabled = $true
$voiceName = if ($arg -eq "male" -or $arg -eq "m") { "Microsoft David Desktop" } else { "Microsoft Zira Desktop" }
$label = if ($arg -eq "male" -or $arg -eq "m") { "David (Male)" } else { "Zira (Female)" }
if (Initialize-TTS) {
try {
$global:GemmaTTS.SelectVoice($voiceName)
Draw-Box @("$CHK Text-to-Speech ON (Voice: $label)") -Color Magenta
} catch {
Write-Host " [!] Voice '$voiceName' not found." -ForegroundColor Red
}
}
continue
}
# Original toggle logic
$script:ttsEnabled = -not $script:ttsEnabled
$state = if ($script:ttsEnabled) { "ON" } else { "OFF" }
Draw-Box @("$CHK Text-to-Speech $state") -Color Magenta
# Initialize if turning on
if ($script:ttsEnabled) { Initialize-TTS | Out-Null }
continue
}
if ($userInput -eq "/debug") {
$script:debugMode = -not $script:debugMode
$state = if ($script:debugMode) { "ON" } else { "OFF" }
Draw-Box @("$CHK Debug mode $state") -Color Yellow
continue
}
if ($userInput -eq "/trim") {
$script:history = Invoke-SmartTrim -hist $script:history -tokenBudget $script:TRIM_THRESHOLD
Draw-Box @("$CHK Manual context trim completed.") -Color Magenta
continue
}
if ($userInput -eq "/refresh") {
Update-SystemPrompt
Draw-Box @("$CHK Tools and system prompt reloaded.", " Current enabled tools: $($script:TOOLS.Count)") -Color Green
continue
}
if ($userInput -eq "/help") {
Draw-Box $helpLines -Title "Gemma CLI $BUL Help" -Width 80 -Color $script:Colors.ui_boxes
continue
}
if ($userInput -eq "/listen") {
try {
Add-Type -AssemblyName System.Speech
$recognizer = New-Object System.Speech.Recognition.SpeechRecognitionEngine
$recognizer.SetInputToDefaultAudioDevice()
$recognizer.LoadGrammar((New-Object System.Speech.Recognition.DictationGrammar))
# Give the user more time to think and speak
$recognizer.InitialSilenceTimeout = [TimeSpan]::FromSeconds(10)
$recognizer.EndSilenceTimeout = [TimeSpan]::FromSeconds(3)
Write-Host "`n [LISTENING...] " -NoNewline -ForegroundColor Yellow
$sttResult = $recognizer.Recognize([TimeSpan]::FromSeconds(60))
if ($sttResult) {
$rawText = $sttResult.Text
$confidence = [Math]::Round($sttResult.Confidence, 2)
if ($script:debugMode) {
Write-Host " [STT Confidence: $confidence] " -NoNewline -ForegroundColor Yellow
}
Write-Host $rawText -ForegroundColor Green
# Tag the input so Gemma knows to be lenient with transcription errors
$userInput = "[VOICE STT (Confidence: $confidence)]: $rawText"
} else {
Write-Host "No speech detected." -ForegroundColor Red
continue
}
} catch {
Write-Host " [!] STT Error: $($_.Exception.Message)" -ForegroundColor Red
continue
} finally {
if ($recognizer) { $recognizer.Dispose() }
}
}
if ($userInput -eq "/recall") {
if (-not (Test-Path $memoryFile)) {
Draw-Box @("$CRS No memory file found. Ask Gemma to remember something first.") -Color Yellow
continue
}
try {
$raw = Get-Content $memoryFile -Raw -Encoding UTF8
$memories = $raw | ConvertFrom-Json
if (-not $memories -or $memories.Count -eq 0) {
Draw-Box @("$CRS Memory file is empty.") -Color Yellow
continue
}
$lines = @()
$lines += "RECALLED MEMORIES ($($memories.Count) entries):"
$lines += ""
$grouped = $memories | Group-Object -Property category | Sort-Object Name
foreach ($group in $grouped) {
$lines += "[$($group.Name.ToUpper())]"
foreach ($m in $group.Group) {
$lines += " $($m.date) $($m.fact)"
}
$lines += ""
}
$script:history += @{
role = "user"
parts = @(@{ text = "MEMORY CONTEXT - facts you have learned about me in previous sessions:`n`n$($lines -join "`n")`n`nAcknowledge this context briefly and use it going forward." })
}
$boxLines = @("$CHK Loaded $($memories.Count) memories into context", "")
foreach ($group in $grouped) {
$boxLines += " $($group.Name.ToUpper()) ($($group.Group.Count))"
foreach ($m in $group.Group) {
$preview = if ($m.fact.Length -gt 55) { $m.fact.Substring(0, 55) + "..." } else { $m.fact }
$boxLines += " $($m.date.Substring(0,10)) $preview"
}
}
Draw-Box $boxLines -Title "/recall $BUL Memory Loaded" -Width 80 -Color Magenta
} catch {
Draw-Box @("$CRS Failed to load memory: $($_.Exception.Message)") -Color Red
}
continue
}
if ($userInput -eq "/resume") {
if (-not (Test-Path $script:historyFile)) {
Draw-Box @("$CRS No previous session history found.") -Color Yellow
continue
}
try {
$raw = Get-Content $script:historyFile -Raw -Encoding UTF8
$savedHistory = $raw | ConvertFrom-Json
# Reconstruct history into proper format (hashtables)
$script:history = @()
foreach ($turn in $savedHistory) {
$turnHash = @{ role = $turn.role; parts = @() }
foreach ($part in $turn.parts) {
$partHash = @{}
if ($part.text) { $partHash["text"] = $part.text }
if ($part.inline_data) {
$partHash["inline_data"] = @{
mime_type = $part.inline_data.mime_type
data = $part.inline_data.data
}
}
$turnHash.parts += $partHash
}
$script:history += $turnHash
}
Draw-Box @("$CHK Resumed last session history ($($script:history.Count) turns).") -Color Green
} catch {
Draw-Box @("$CRS Failed to resume session: $($_.Exception.Message)") -Color Red
}
continue
}
if ($userInput -match '^/tools\s*(.*)$') {
$sub = $matches[1].Trim().ToLower()
$mode = "enabled"
if ($sub -eq "all") { $mode = "all" }
elseif ($sub -eq "disabled") { $mode = "disabled" }
$title = switch ($mode) {
"all" { "All Repository Tools (Enabled & Disabled)" }
"disabled" { "Disabled Tools (more_tools/)" }
default { "Active Tools (Enabled)" }
}
$toolLines = Get-ToolsSummary -ScriptRoot $scriptDir -Mode $mode
$wikiPath = Join-Path $scriptDir "TOOLS.html"
$toolLines += ""
$toolLines += " $BUL Tool Docs: $(Convert-ToHyperlink -Text $wikiPath)"
Draw-Box $toolLines -Title $title -Width 90 -Color Green
continue
}
if ($userInput -eq "/resetkey") {
if (Remove-StoredKey -keyName "gemmacli") {
Draw-Box @("$CHK Saved API key deleted. Restart the script to set a new one.") -Color Cyan
} else {
Draw-Box @("$CRS No saved API key found to delete.") -Color Yellow
}
break
}
if ($userInput -eq "/settings") {
$settingsChoice = Show-ArrowMenu -Options @("Colors", "Tools", "Smart Trim", "Context Mode", "Start Delay", "Exit") -Title "Settings"
switch ($settingsChoice) {
0 {
$schemeOptions = @("Default Scheme", "Alternative Scheme")
$schemeIdx = if ($scheme -eq "alternative") { 1 } else { 0 }
$choice = Show-ArrowMenu -Options $schemeOptions -Title "Color Settings" -Default $schemeIdx
if ($choice -ge 0) {
$newScheme = if ($choice -eq 1) { "alternative" } else { "default" }
$script:Settings.color_scheme = $newScheme
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
Draw-Box @("Color scheme updated to '$newScheme'. Restart the script to apply changes.") -Color Yellow
}
}
1 {
$enabledTools = @(Get-ChildItem -Path "tools" -Filter "*.ps1" | ForEach-Object { @{ Name = $_.BaseName; Status = "Enabled" } })
$disabledTools = @(Get-ChildItem -Path "more_tools" -Filter "*.ps1" | ForEach-Object { @{ Name = $_.BaseName; Status = "Disabled" } })
$allTools = $enabledTools + $disabledTools
$pageSize = 12
$pageIdx = 0
while ($true) {
$startIdx = $pageIdx * $pageSize
$endIdx = [math]::Min($startIdx + $pageSize - 1, $allTools.Count - 1)
$currentPageTools = $allTools[$startIdx..$endIdx]
$toolOptions = $currentPageTools | ForEach-Object {
$meta = $script:TOOL_CACHE[$_.Name]
$inds = @()
if ($meta.Interactive) { $indicators += "⚠ " }
if ($meta.RequiresKey) { $indicators += "🔑" }
$indStr = if ($inds.Count -gt 0) { " " + ($inds -join " ") } else { "" }
"$($meta.Icon) $($_.Name)$indStr ($($_.Status))"
}
$hasPrev = $pageIdx -gt 0
$hasNext = ($startIdx + $pageSize) -lt $allTools.Count
if ($hasPrev) { $toolOptions += "< Previous Page" }
if ($hasNext) { $toolOptions += "> Next Page" }
$toolOptions += "[ Exit ]"
$totalPages = [math]::Ceiling($allTools.Count / $pageSize)
$titleStr = "Tool Management $BUL Page $($pageIdx + 1) of $totalPages"
$toolChoice = Show-ArrowMenu -Options $toolOptions -Title $titleStr
if ($toolChoice -lt 0) { break } # Esc pressed
$selectedStr = $toolOptions[$toolChoice]
if ($selectedStr -eq "[ Exit ]") { break }
elseif ($selectedStr -eq "< Previous Page") { $pageIdx--; continue }
elseif ($selectedStr -eq "> Next Page") { $pageIdx++; continue }
# They selected an actual tool
$selectedTool = $currentPageTools[$toolChoice]
$enabledCount = @($allTools | Where-Object { $_.Status -eq "Enabled" }).Count
$limit = $script:TOOL_LIMITS[$script:MODEL]
if ($selectedTool.Status -eq "Disabled" -and $enabledCount -ge $limit) {
Draw-Box @("Model '$($script:MODEL)' only supports $limit active tools. Please disable a tool before enabling another.") -Color Red
} else {
if ($selectedTool.Status -eq "Enabled") {
Move-Item -Path "tools\$($selectedTool.Name).ps1" -Destination "more_tools/"
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
Update-SystemPrompt
Draw-Box @("Tool '$($selectedTool.Name)' disabled.") -Color Yellow
} else {
Move-Item -Path "more_tools\$($selectedTool.Name).ps1" -Destination "tools/"
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
Update-SystemPrompt
# Check if tool is still active (it might have been disabled during key setup)
if ($script:TOOLS.ContainsKey($selectedTool.Name)) {
Draw-Box @("Tool '$($selectedTool.Name)' enabled.") -Color Yellow
} else {
Draw-Box @("Tool '$($selectedTool.Name)' disabled (Setup cancelled).") -Color Yellow
}
}
}
break # Exit the loop after toggling
}
}
2 {
$currentEnabled = if ($null -ne $script:Settings.smart_trim) { [bool]$script:Settings.smart_trim } else { $false }
$currentStrength = if ($script:Settings.smart_trim_strength) { [int]$script:Settings.smart_trim_strength } else { 5 }
$trimState = if ($currentEnabled) { "Enabled" } else { "Disabled" }
$trimChoice = Show-ArrowMenu -Options @("Toggle Smart Trim ($trimState)", "Set Strength ($currentStrength)") -Title "Smart Trim Settings"
if ($trimChoice -eq 0) {
$script:Settings.smart_trim = -not $currentEnabled
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
$newState = if ($script:Settings.smart_trim) { "Enabled" } else { "Disabled" }
Draw-Box @("$CHK Smart Trim $newState") -Color Magenta
}
elseif ($trimChoice -eq 1) {
$strengthOptions = @(
"1 - Conservative (keep most, minimal token savings)",
"2 - Conservative+",
"3 - Balanced-",
"4 - Balanced",
"5 - Balanced+ (recommended)",
"6 - Aggressive-",
"7 - Aggressive",
"8 - Aggressive+",
"9 - Maximum-",
"10 - Maximum (keep least, most token savings)"
)
$strengthIdx = [math]::Max(0, $currentStrength - 1)
$strengthChoice = Show-ArrowMenu -Options $strengthOptions -Title "Smart Trim Strength" -Default $strengthIdx
if ($strengthChoice -ge 0) {
$script:Settings.smart_trim_strength = $strengthChoice + 1
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
Draw-Box @("$CHK Smart Trim strength set to $($script:Settings.smart_trim_strength)") -Color Magenta
}
}
}
3 {
$currentMode = if ($script:Settings.context_mode) { $script:Settings.context_mode } else { "standard" }
$defaultIdx = if ($currentMode -eq "large") { 1 } else { 0 }
$modeChoice = Show-ArrowMenu -Options @("Standard (15k - Google API)", "Large (128k - Enterprise/Paid)") -Title "Select Context Mode" -Default $defaultIdx
if ($modeChoice -ge 0) {
$script:Settings.context_mode = if ($modeChoice -eq 1) { "large" } else { "standard" }
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
Draw-Box @("Context mode set to '$($script:Settings.context_mode)'. Restart GemmaCLI to apply.") -Color Magenta
}
}
4 {
$currentDelay = if ($script:Settings.startup_delay) { [int]$script:Settings.startup_delay } else { 0 }
$delayOptions = @("0s - No delay", "1s", "2s", "3s", "5s")
$delayValues = @(0, 1, 2, 3, 5)
$currentIdx = [math]::Max(0, $delayValues.IndexOf($currentDelay))
$delayChoice = Show-ArrowMenu -Options $delayOptions -Title "Startup Delay $BUL current: $($currentDelay)s" -Default $currentIdx
if ($delayChoice -ge 0) {
$script:Settings.startup_delay = $delayValues[$delayChoice]
$script:Settings | ConvertTo-Json | Set-Content -Path $settingsPath
Draw-Box @("$CHK Startup delay set to $($delayValues[$delayChoice])s") -Color Magenta
}
}
}
continue
}
if ($userInput -eq "/customCommand") {
$lines = @(
"HOW TO CREATE A CUSTOM COMMAND:",
"Use the syntax: /customCommand /yourAlias Your detailed prompt here",
"Example: /customCommand /poem write a short poem about coding",
"",
"Once created, you can just type /yourAlias to execute that prompt.",
""
)
if ($script:customCommands.Count -gt 0) {
$lines += "YOUR CUSTOM COMMANDS:"
foreach ($key in $script:customCommands.Keys) {
$lines += "$($key.PadRight(18)) $ARR $($script:customCommands[$key])"
}
} else {
$lines += "You haven't created any custom commands yet."
}
Draw-Box $lines -Title "Custom Commands Management" -Width 80 -Color $script:Colors.custom_command
continue
}
if ($userInput -match '^/customCommand\s+(\/\w+)\s+(.*)') {
$alias = $matches[1]
$prompt = $matches[2]
$script:customCommands[$alias] = $prompt
$script:customCommands | ConvertTo-Json | Set-Content -Path $customCommandsPath
Draw-Box @("Custom command '$alias' has been saved and is ready to use.") -Color Green
continue
}
# ---- /model command ----
if ($userInput -match '^/model\s*(.*)$') {
$modelArg = $matches[1].Trim()
# Strictly allowed handles for the Chat Model Picker
$gemmaHandles = @("gemma-4-pro", "gemma-4-fast", "gemma-ultra", "gemma-heavy", "gemma-medium", "gemma-small", "gemma-nano-pro", "gemma-nano-lite")
$availableGemma = @()
foreach ($handle in $gemmaHandles) {
$p = $script:MODEL_REGISTRY.PSObject.Properties[$handle]
if ($p -and $p.Value.id) { $availableGemma += $p }
}
if ([string]::IsNullOrWhiteSpace($modelArg)) {
# UI shows Checkmark (if current), ID, and Description in aligned columns
$menuLabels = $availableGemma | ForEach-Object {
$e = $_.Value
$isCurrent = ($_.Name -eq $script:MODEL_HANDLE)
$prefix = if ($isCurrent) { "$CHK " } else { " " }
"$prefix $($e.id.PadRight(25)) $ARR $($e.desc)"
}
$currentIdx = 0
for ($i = 0; $i -lt $availableGemma.Count; $i++) {
if ($availableGemma[$i].Name -eq $script:MODEL_HANDLE) { $currentIdx = $i; break }
}
$choice = Show-ArrowMenu -Options $menuLabels -Title "Select Gemma Model $BUL $WRN Warning: Changing model clears context" -Width 110 -Default $currentIdx
if ($choice -ge 0) {
$selected = $availableGemma[$choice]
$script:MODEL_HANDLE = $selected.Name
$script:MODEL = $selected.Value.id
$script:Settings.current_model_handle = $script:MODEL_HANDLE
$script:Settings | ConvertTo-Json | Set-Content $settingsPath
# Check tool limits and disable excess tools
$limit = if ($script:TOOL_LIMITS[$script:MODEL] -ne $null) { $script:TOOL_LIMITS[$script:MODEL] } else { 0 }
$enabledTools = Get-ChildItem -Path "tools" -Filter "*.ps1" | Sort-Object Name
if ($enabledTools.Count -gt $limit) {
$toDisable = $enabledTools.Count - $limit
$disabledNames = @()
for ($i = 0; $i -lt $toDisable; $i++) {
$tool = $enabledTools[$enabledTools.Count - 1 - $i]
Move-Item -Path $tool.FullName -Destination "more_tools/" -Force
$disabledNames += $tool.BaseName
}
Draw-Box @("$WRN Tool limit for '$($script:MODEL)' is $limit.", " Disabled excess tools: $($disabledNames -join ', ')") -Color Yellow
}
Update-SystemPrompt -resetHistory $true
Draw-Box @("$CHK Model switched to: $script:MODEL", "$WRN Conversation context has been cleared.") -Color Magenta
} else {
Write-Host " Model selection cancelled." -ForegroundColor DarkGray
}
} else {
# Direct switch: check if input matches a Gemma ID or Handle
$found = $availableGemma | Where-Object { $_.Name -eq $modelArg -or $_.Value.id -eq $modelArg }
if ($found) {
$script:MODEL_HANDLE = $found.Name
$script:MODEL = $found.Value.id
$script:Settings.current_model_handle = $script:MODEL_HANDLE
$script:Settings | ConvertTo-Json | Set-Content $settingsPath
Update-SystemPrompt
Draw-Box @("$CHK Model switched to: $script:MODEL") -Color Magenta
} else {
Write-Host " [!] Unknown or restricted Gemma model '$modelArg'." -ForegroundColor Red
}
}
continue
}
# ---- /bigBrother command ----
if ($userInput -match '^/bigBrother\s+(.+)$') {
$query = $matches[1].Trim()
Invoke-DualAgent -query $query -mode "bigBrother"
continue
}
if ($userInput -eq "/bigBrother") {
Draw-Box @("$CRS Usage: /bigBrother <your question>") -Color Yellow
continue
}
# ---- /littleSister command ----
if ($userInput -match '^/littleSister\s+(.+)$') {
$query = $matches[1].Trim()
Invoke-DualAgent -query $query -mode "littleSister"
continue
}
if ($userInput -eq "/littleSister") {
Draw-Box @("$CRS Usage: /littleSister <your question>") -Color Yellow
continue
}
if ($script:customCommands.ContainsKey($userInput)) {
$userInput = $script:customCommands.$userInput
Draw-Box @("Executing custom command: $userInput") -Color $script:Colors.custom_command
}
if ([string]::IsNullOrWhiteSpace($userInput)) {
# Move up one line and clear it to remove the dangling "You:" prompt
Write-Host "$esc[1A$esc[K" -NoNewline
continue
}
$script:history += @{ role = "user"; parts = @(@{ text = $userInput }) }
$currentUri = Get-ApiUri
$toolTurns = 0
$defaultMax = if ($script:MODEL -in @("gemma-4-31b-it","gemma-4-26b-a4b-it","gemma-3-27b-it","gemma-3-12b-it")) { 8 } else { 4 }
$maxToolTurns = if ($script:Settings.max_tool_turns) { [int]$script:Settings.max_tool_turns } else { $defaultMax }
while ($true) {
# RPM check — enforces free-tier request-per-minute ceiling before every call
Invoke-RpmCheck -backend "gemma"
# Minimum 2-second gap between calls (secondary guard, covers sub-RPM burst)
if ($script:lastApiCall) {
$elapsed = ((Get-Date) - $script:lastApiCall).TotalMilliseconds
if ($elapsed -lt 2000) { Start-Sleep -Milliseconds (2000 - $elapsed) }
}
$script:lastApiCall = Get-Date
# Trim history if approaching context window limit
$script:history = Invoke-SmartTrim -hist $script:history -tokenBudget $script:TRIM_THRESHOLD -currentQuery $userInput
# Start spinner ONLY for the API call to avoid interfering with tool logic
Start-Spinner -Label "Gemma is thinking (Esc to cancel)"
$resp = Invoke-GemmaApiWithRetry -uri $currentUri -historyRef ([ref]$script:history) -gConfig $script:GUARDRAILS
Stop-Spinner
if ($resp.cancelled) {
Write-Host " [Operation cancelled by user]" -ForegroundColor Yellow
break
}
if (-not $resp) {
Write-Host ""
Draw-Box @("$CRS No response from API. Check your connection or API key.") -Color Red
break
}
if ($resp.apiError) {
$errMsg = $resp.apiError
Write-Host ""
Draw-Box @("$CRS API Error:", " $errMsg") -Color Red
break
}
if (-not $resp.candidates) {
$reason = if ($resp.promptFeedback.blockReason) { $resp.promptFeedback.blockReason } else { "Unknown reason" }
Write-Host ""
Draw-Box @("$CRS Response blocked: $reason") -Color Red
break
}
# Update metadata for next status bar draw