-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbyteask.ps1
More file actions
1832 lines (1761 loc) · 88.1 KB
/
Copy pathbyteask.ps1
File metadata and controls
1832 lines (1761 loc) · 88.1 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
#!/usr/bin/env pwsh
# byteask.ps1 - ByteAsk AI coding agent CLI (native Windows launcher).
#
# PowerShell port of the POSIX `byteask` wrapper: same auth flow (magic-link, mode-C
# token in config.toml), same hourly re-prompting update check, same interactive
# onboarding, and the same /login|/logout launch loop (the TUI drops a marker; we
# re-auth here and relaunch, since the engine can't hot-swap the startup-loaded token).
#
# Behavior parity with byteask/cli/byteask is intentional - keep them in sync.
$VERSION = '0.1.11'
$DEFAULT_GATEWAY = 'https://code.byteask.ai'
$CODEX_HOME = if ($env:BYTEASK_HOME) { $env:BYTEASK_HOME } else { Join-Path $HOME '.byteask' }
$env:CODEX_HOME = $CODEX_HOME
$env:CODEX_BRAND = if ($env:BYTEASK_BRAND) { $env:BYTEASK_BRAND } else { 'ByteAsk' }
$env:BYTEASK_CLIENT_VERSION = $VERSION # engine displays THIS, not its crate version
$SELF_DIR = $PSScriptRoot
$ENGINE = Join-Path $SELF_DIR 'byteask-engine.exe'
$UPDATE_STATE = Join-Path $CODEX_HOME 'update-check'
$AUTH_REQ = Join-Path $CODEX_HOME '.byteask-auth-request'
function Write-Err([string]$m) { [Console]::Error.WriteLine($m) } # stderr, non-throwing
function Resolve-Gateway {
if ($env:BYTEASK_GATEWAY) { return $env:BYTEASK_GATEWAY }
$f = Join-Path $CODEX_HOME 'gateway'
if (Test-Path $f) { return ((Get-Content -Raw $f).Trim()) }
return $DEFAULT_GATEWAY
}
# True only when both stdin and stdout are a real console (mirrors `[ -t 0 ] && [ -t 1 ]`).
function Test-Interactive {
return (-not [Console]::IsInputRedirected) -and (-not [Console]::IsOutputRedirected)
}
# $true iff A > B, numeric dot-separated, tolerant of junk (matches version_gt).
function Test-VersionGt([string]$a, [string]$b) {
if ($a -eq $b) { return $false }
$pa = $a -split '\.'; $pb = $b -split '\.'
$n = [Math]::Max($pa.Count, $pb.Count)
for ($i = 0; $i -lt $n; $i++) {
$ia = 0; $ib = 0
if ($i -lt $pa.Count) { [void][int]::TryParse($pa[$i], [ref]$ia) }
if ($i -lt $pb.Count) { [void][int]::TryParse($pb[$i], [ref]$ib) }
if ($ia -gt $ib) { return $true }
if ($ia -lt $ib) { return $false }
}
return $false
}
# Rewrite config.toml without the token line; clear auth.json. Returns 0 (ok / not
# signed in) or 1 (token present but not removable). Writes messages to host/stderr.
# Full logout across ALL auth stores (managed token, BYOK keys+JWT, subscription auth.json)
# + stop the sidecar + reset to a managed UNSIGNED config. Mirrors the sh do_logout.
function Invoke-Logout {
$wasSigned = Test-SignedIn
# 1. stop the BYOK sidecar (holds keys + JWT in memory)
$pidf = Join-Path $CODEX_HOME 'byok-sidecar.pid'
if (Test-Path $pidf) { try { Stop-Process -Id ([int](Get-Content $pidf)) -ErrorAction SilentlyContinue } catch {}; Remove-Item -Force -ErrorAction SilentlyContinue $pidf }
# 2. clear every credential store
Remove-Item -Force -ErrorAction SilentlyContinue $BYOK_CFG
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $CODEX_HOME 'auth.json')
# 3. reset to managed + UNSIGNED
$model = Get-CfgLine '^model = "(.*)"$'
if (-not $model) { $model = if ($env:BYTEASK_MODEL) { $env:BYTEASK_MODEL } else { 'gpt-5.4' } }
$gw = (Resolve-Gateway).TrimEnd('/')
Write-ManagedConfig $model (Get-CfgLine '^(model_catalog_json = .*)$') $gw ''
# 4. report on actual post-state
if (Test-SignedIn) { Write-Err "Couldn't fully log out - check permissions on $CODEX_HOME"; return 1 }
if ($wasSigned) { Write-Host "Logged out of ByteAsk. Run 'byteask' to sign back in." }
else { Write-Host "You're not signed in to ByteAsk." }
return 0
}
# Magic-link sign-in; writes gateway + config.toml with the mode-C token. Exits 1 on
# failure (like the sh wrapper). $Email/$Ref empty = prompt / discover.
# ===================== BYOK (bring your own key) - Windows parity ===========
# Mirrors the sh wrapper's byok commands. Keys + the managed JWT live in
# ~/.byteask/byok-config.json (0600 best-effort); a local python "sidecar" reads it
# and the engine points at it, routing per model (own-key -> provider direct; no key
# -> managed gateway). Requires python. KEEP THIS FILE PURE ASCII (PS 5.1 codepage).
$BYOK_PORT = if ($env:BYOK_SIDECAR_PORT) { $env:BYOK_SIDECAR_PORT } else { '8799' }
$BYOK_CFG = Join-Path $CODEX_HOME 'byok-config.json'
$BYOK_SIDECAR = Join-Path $CODEX_HOME 'byok_sidecar.py'
$BYOK_MODELS = Join-Path $CODEX_HOME 'byteask_models.py' # shared self-hosted-models helper
function Get-ModelsPython {
foreach ($p in @('python3','python')) { if (Get-Command $p -ErrorAction SilentlyContinue) { return $p } }
return $null
}
function Test-ModelsReady {
if (-not (Test-Path $BYOK_MODELS)) { Write-Err "byteask: self-hosted models need the helper; run 'byteask --update'."; return $false }
if (-not (Get-ModelsPython)) { Write-Err "byteask: self-hosted models need python3 (not found on PATH)."; return $false }
return $true
}
function Invoke-ModelsPy([string[]]$PyArgs) {
$py = Get-ModelsPython; if (-not $py) { return @() }
try { return @(& $py $BYOK_MODELS @PyArgs 2>$null) } catch { return @() }
}
function Read-HiddenLine([string]$prompt) {
$sec = Read-Host -AsSecureString $prompt
return [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec))
}
# Re-merge the registry's self/* endpoints into the catalog (idempotent + atomic; never
# drops a base model). At launch + after add/remove so /model tracks the registry and a
# --update that re-fetched a base catalog can't permanently drop custom rows.
function Invoke-ModelsMerge {
if (-not (Test-Path $BYOK_MODELS)) { return }
$py = Get-ModelsPython; if (-not $py) { return }
$cat = Join-Path $CODEX_HOME 'models-catalog.json'
if (-not (Test-Path $cat)) { return }
try { & $py $BYOK_MODELS merge-catalog $BYOK_CFG $cat 2>$null | Out-Null } catch {}
}
function Test-HasSelfEndpoints {
if (-not (Test-Path $BYOK_CFG)) { return $false }
return (Select-String -Path $BYOK_CFG -Pattern '"endpoints"' -Quiet)
}
function Get-PyExe {
foreach ($p in @('python3','python','py')) {
$c = Get-Command $p -ErrorAction SilentlyContinue
if ($c) { return $c.Source }
}
return $null
}
# Run an inline Python snippet by writing it to a temp .py file and executing THAT,
# never via `python -c <code>`. Windows PowerShell 5.1 does not escape embedded
# double-quotes or newlines when it builds the command line for a native command, so
# a multi-line -c snippet with "quoted" dict keys reaches python.exe truncated ->
# SyntaxError: '(' was never closed (Windows 11, 2026-07-16). Routing the code through
# a temp file sidesteps ALL command-line quoting of the code; only simple args (file
# paths, provider names) are passed, which 5.1 quotes correctly. sys.argv matches the
# -c form: argv[0] is the script, argv[1..] are $ExtraArgs. Returns $null on no-python
# or any failure (callers fall back to a default). Mirrors the sh wrapper's `python3 -`.
function Invoke-Py([string]$Code, [string[]]$ExtraArgs) {
$py = Get-PyExe
if (-not $py) { return $null }
$tmp = Join-Path ([IO.Path]::GetTempPath()) ('byteask-py-' + [Guid]::NewGuid().ToString('N') + '.py')
try {
[IO.File]::WriteAllText($tmp, $Code, (New-Object Text.UTF8Encoding $false)) # no BOM
if ($ExtraArgs) { return (& $py $tmp @ExtraArgs 2>$null) }
return (& $py $tmp 2>$null)
} catch {
return $null
} finally {
Remove-Item -Force -ErrorAction SilentlyContinue $tmp
}
}
# JSON ops via python (BYOK requires python anyway - no jq/PS-JSON edge cases).
$BYOK_MERGE_PY = @'
import json,sys,os
path=sys.argv[1]
try: cfg=json.load(open(path))
except Exception: cfg={}
if not isinstance(cfg,dict): cfg={}
cfg.setdefault("keys",{})
for pair in sys.argv[2:]:
k,_,v=pair.partition("=")
if k.startswith("keys."):
prov=k[5:]
if v: cfg["keys"][prov]=v
else: cfg["keys"].pop(prov,None)
else:
if v: cfg[k]=v
else: cfg.pop(k,None)
os.makedirs(os.path.dirname(path),exist_ok=True)
open(path,"w").write(json.dumps(cfg))
try: os.chmod(path,0o600)
except Exception: pass
'@
$BYOK_FIELD_PY = 'import json,sys' + "`n" + 'try: print(json.load(open(sys.argv[1])).get(sys.argv[2]) or "")' + "`n" + 'except Exception: print("")'
$BYOK_COUNT_PY = 'import json,sys' + "`n" + 'try: print(len((json.load(open(sys.argv[1])).get("keys") or {})))' + "`n" + 'except Exception: print(0)'
function Invoke-ByokMerge([string[]]$pairs) {
[void](Invoke-Py $BYOK_MERGE_PY (@($BYOK_CFG) + $pairs))
}
function Get-ByokField([string]$name) {
if (-not (Test-Path $BYOK_CFG)) { return '' }
$v = Invoke-Py $BYOK_FIELD_PY @($BYOK_CFG, $name)
if ($null -eq $v) { return '' }
return $v
}
function Get-ByokKeyCount {
if (-not (Test-Path $BYOK_CFG)) { return 0 }
$c = Invoke-Py $BYOK_COUNT_PY @($BYOK_CFG)
if (-not $c) { return 0 }
return [int]$c
}
# Per-provider menu verb: "change" if that key is set, else "add" (openai anthropic gemini).
function Get-ByokKeyVerbs {
if (-not (Test-Path $BYOK_CFG)) { return @('add','add','add') }
$snippet = 'import json,sys' + "`n" + 'try: keys=json.load(open(sys.argv[1])).get("keys") or {}' + "`n" + 'except Exception: keys={}' + "`n" + 'print(" ".join("change" if keys.get(p) else "add" for p in ("openai","anthropic","gemini")))'
$out = Invoke-Py $snippet @($BYOK_CFG)
if (-not $out) { return @('add','add','add') }
$parts = ($out.Trim() -split '\s+')
if ($parts.Count -lt 3) { return @('add','add','add') }
return $parts
}
function Get-CfgLine([string]$pattern) {
$cfg = Join-Path $CODEX_HOME 'config.toml'
if (-not (Test-Path $cfg)) { return '' }
$m = Select-String -Path $cfg -Pattern $pattern | Select-Object -First 1
if ($m) { return $m.Matches[0].Groups[1].Value } else { return '' }
}
function Get-CurrentJwt {
$j = Get-ByokField 'jwt'
if ($j) { return $j }
return (Get-CfgLine '^experimental_bearer_token = "(.*)"$')
}
# Emails that have signed in on this machine (persists across logout). Used to
# skip the referral prompt for a returning user - referrals only credit a NEW signup.
function Test-EmailKnown([string]$Email) {
$ke = Join-Path $CODEX_HOME '.known-emails'
if (-not (Test-Path $ke)) { return $false }
$want = $Email.Trim().ToLowerInvariant()
foreach ($line in (Get-Content $ke -ErrorAction SilentlyContinue)) {
if ($line.Trim().ToLowerInvariant() -eq $want) { return $true }
}
return $false
}
function Add-KnownEmail([string]$Email) {
if (Test-EmailKnown $Email) { return }
$ke = Join-Path $CODEX_HOME '.known-emails'
try { Add-Content -Path $ke -Value $Email -ErrorAction SilentlyContinue } catch { }
}
# Authoritative "has this email signed in before?" via the gateway (works across
# machines, unlike the local cache). Returns 'yes' | 'no' | '' (couldn't tell).
# Fail-open: any error / older gateway without the route -> '' (caller uses local).
function Get-ServerEmailExists([string]$Email) {
$gw = (Resolve-Gateway).TrimEnd('/')
if (-not $gw) { return '' }
try {
$enc = [uri]::EscapeDataString($Email) # encodes '+' -> %2B, '@' -> %40
$r = Invoke-RestMethod -Uri "$gw/auth/account-exists?email=$enc" -TimeoutSec 3 -ErrorAction Stop
if ($null -ne $r.exists) { if ($r.exists) { return 'yes' } else { return 'no' } }
} catch { }
return ''
}
# True (=> SKIP the referral prompt) when the email is a returning user. Server first,
# local .known-emails fallback when the gateway can't be reached.
function Test-EmailReturning([string]$Email) {
switch (Get-ServerEmailExists $Email) {
'yes' { return $true }
'no' { return $false }
default { return (Test-EmailKnown $Email) }
}
}
# One gateway probe per sign-in attempt. From a single /auth/account-exists call it
# returns @{ Block = <reason the address is refused, or ''>; Exists = 'yes'|'no'|'' }.
# Fail-open: any error leaves both empty -> allow, with /auth/start the authoritative gate.
function Get-EmailProbe([string]$Email) {
$out = @{ Block = ''; Exists = '' }
$gw = (Resolve-Gateway).TrimEnd('/')
if (-not $gw) { return $out }
try {
$enc = [uri]::EscapeDataString($Email)
$r = Invoke-RestMethod -Uri "$gw/auth/account-exists?email=$enc" -TimeoutSec 3 -ErrorAction Stop
if ($r.blocked) { $out.Block = [string]$r.error; return $out }
if ($null -ne $r.exists) { $out.Exists = if ($r.exists) { 'yes' } else { 'no' } }
} catch { }
return $out
}
# True => this email is a NEW signup (show the referral prompt). Uses the probe's Exists,
# local .known-emails fallback when the server was silent.
function Test-EmailNew([string]$Email, [string]$Exists) {
switch ($Exists) {
'yes' { return $false }
'no' { return $true }
default { return (-not (Test-EmailKnown $Email)) }
}
}
function Write-ManagedConfig([string]$model, [string]$catalog, [string]$gateway, [string]$token) {
# Empty $token => UNSIGNED (no experimental_bearer_token line) so the launch check onboards.
$tokenLine = if ($token) { "experimental_bearer_token = `"$token`"" } else { "" }
$cfg = @"
model = "$model"
model_provider = "byteask"
web_search = "live"
$catalog
[model_providers.byteask]
name = "ByteAsk"
base_url = "$gateway/byteask/v1"
wire_api = "responses"
requires_openai_auth = false
$tokenLine
[model_providers.byteask.http_headers]
x-openai-actor-authorization = "byteask"
"@
$cfg = Add-TersePref $cfg
Set-Content -Path (Join-Path $CODEX_HOME 'config.toml') -Value $cfg
}
function Write-ByokConfig([string]$model, [string]$catalog, [string]$token) {
$cfg = @"
model = "$model"
model_provider = "byok-local"
web_search = "live"
$catalog
[model_providers.byok-local]
name = "ByteAsk (your key)"
base_url = "http://127.0.0.1:$BYOK_PORT/byteask/v1"
wire_api = "responses"
requires_openai_auth = false
supports_websockets = false
[model_providers.byok-local.http_headers]
X-BYOK-Token = "$token"
x-openai-actor-authorization = "byteask"
"@
$cfg = Add-TersePref $cfg
Set-Content -Path (Join-Path $CODEX_HOME 'config.toml') -Value $cfg
}
# Terse mode: gateway-injected output-style floor (default-on lite). The level
# rides an x-byteask-terse header the gateway reads to append a style block to
# `instructions`. Persisted in CODEX_HOME/terse so it survives re-login. Parity
# with the sh wrapper's do_terse. Pure ASCII (PS 5.1 codepage rule).
function Add-TersePref([string]$cfg) {
# Re-emit the saved terse level when (re)writing config, so a re-login keeps it.
$pref = Join-Path $CODEX_HOME 'terse'
if (Test-Path $pref) {
$lvl = (Get-Content -Raw $pref -ErrorAction SilentlyContinue)
if ($lvl) { $lvl = $lvl.Trim() }
if ($lvl) { $cfg = $cfg + "`nx-byteask-terse = `"$lvl`"" }
}
return $cfg
}
function Get-TerseLevelNow {
$cfg = Join-Path $CODEX_HOME 'config.toml'
if (-not (Test-Path $cfg)) { return '' }
$m = Select-String -Path $cfg -Pattern '^x-byteask-terse = "(.*)"$' | Select-Object -First 1
if ($m) { return $m.Matches[0].Groups[1].Value }
return ''
}
function Set-TerseConfig([string]$level) {
$cfg = Join-Path $CODEX_HOME 'config.toml'
if (-not (Test-Path $cfg)) { return }
$out = New-Object System.Collections.Generic.List[string]
$inHdrs = $false
foreach ($ln in (Get-Content -Path $cfg)) {
$s = $ln.Trim()
if ($s.StartsWith('[') -and $s.EndsWith(']')) {
$inHdrs = $s.EndsWith('.http_headers]')
$out.Add($ln)
if ($inHdrs) { $out.Add("x-byteask-terse = `"$level`"") }
continue
}
if ($inHdrs -and $s.ToLower().StartsWith('x-byteask-terse')) { continue }
$out.Add($ln)
}
Set-Content -Path $cfg -Value $out
}
function Invoke-Terse([string[]]$rest) {
$arg = if ($rest.Count -ge 1) { "$($rest[0])" } else { 'status' }
switch -Regex ($arg) {
'^(status)?$' {
$tl = Get-TerseLevelNow; if (-not $tl) { $tl = 'lite (default)' }
Write-Host "Terse mode: $tl"
Write-Host " concise replies, code/commands/errors kept exact. Change:"
Write-Host " byteask terse off | lite | full | ultra"
return 0
}
'^(off|lite|full|ultra)$' { }
'^(-h|--help)$' { Write-Host "usage: byteask terse [status|off|lite|full|ultra]"; return 0 }
default { Write-Err "byteask terse: unknown level '$arg' (use off|lite|full|ultra|status)"; return 2 }
}
if (-not (Test-Path $CODEX_HOME)) { New-Item -ItemType Directory -Force -Path $CODEX_HOME | Out-Null }
Set-Content -Path (Join-Path $CODEX_HOME 'terse') -Value $arg -NoNewline
Set-TerseConfig $arg
switch ($arg) {
'off' { Write-Host "Terse mode OFF - replies use the model's normal style." }
'lite' { Write-Host "Terse mode LITE (default) - concise; skips filler, keeps all code/technical detail exact." }
'full' { Write-Host "Terse mode FULL - tight, fragment-style replies; code/commands/errors kept verbatim." }
'ultra' { Write-Host "Terse mode ULTRA - maximum terseness; code/commands/errors kept verbatim." }
}
Write-Host " Takes effect on your next 'byteask' launch."
return 0
}
function Test-SidecarHealth {
try { $null = Invoke-WebRequest -UseBasicParsing -TimeoutSec 2 "http://127.0.0.1:$BYOK_PORT/healthz"; return $true }
catch { return $false }
}
function Ensure-Sidecar {
if ($env:BYOK_SKIP_SIDECAR) { return $true }
if (-not (Test-Path $BYOK_SIDECAR)) { Write-Err "byteask: BYOK sidecar not installed; run 'byteask --update'."; return $false }
$pidf = Join-Path $CODEX_HOME 'byok-sidecar.pid'
if (Test-SidecarHealth) {
if ((Test-Path $pidf) -and ((Get-Item $pidf).LastWriteTime -gt (Get-Item $BYOK_SIDECAR).LastWriteTime)) { return $true }
try { Stop-Process -Id ([int](Get-Content $pidf -ErrorAction SilentlyContinue)) -ErrorAction SilentlyContinue } catch {}
Start-Sleep -Milliseconds 500
}
$py = Get-PyExe
if (-not $py) { Write-Err "byteask: BYOK needs python (not found on PATH)."; return $false }
$env:BYOK_SIDECAR_PORT = $BYOK_PORT
$p = Start-Process -FilePath $py -ArgumentList $BYOK_SIDECAR -WindowStyle Hidden -PassThru
Set-Content -Path $pidf -Value $p.Id -NoNewline
for ($i = 0; $i -lt 30; $i++) { if (Test-SidecarHealth) { return $true }; Start-Sleep -Milliseconds 100 }
Write-Err "byteask: BYOK sidecar didn't start."; return $false
}
function Test-ProviderKey([string]$prov, [string]$key) {
switch ($prov) {
'openai' { $u = 'https://api.openai.com/v1/models'; $h = @{ 'Authorization' = "Bearer $key" } }
'anthropic' { $u = 'https://api.anthropic.com/v1/models'; $h = @{ 'x-api-key' = $key; 'anthropic-version' = '2023-06-01' } }
'gemini' { $u = 'https://generativelanguage.googleapis.com/v1beta/models'; $h = @{ 'x-goog-api-key' = $key } }
default { return $true }
}
try { $null = Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Headers $h $u; return $true }
catch {
$code = 0; try { $code = [int]$_.Exception.Response.StatusCode } catch {}
if ($code -eq 401 -or $code -eq 403) { Write-Err " That $prov key was rejected by the provider (HTTP $code)."; return $false }
Write-Err " Couldn't verify the $prov key right now (HTTP $code) - saving it anyway."; return $true
}
}
function Invoke-ByokEnter {
$jwt = Get-CurrentJwt
$lt = Get-ByokField 'local_token'
if (-not $lt) { $lt = Invoke-Py 'import secrets;print(secrets.token_hex(24))' }
$gw = (Resolve-Gateway).TrimEnd('/')
Invoke-ByokMerge @("jwt=$jwt", "local_token=$lt", "gateway=$gw")
if (-not (Ensure-Sidecar)) { return $false }
Write-ByokConfig (Get-CfgLine '^model = "(.*)"$') (Get-CfgLine '^(model_catalog_json = .*)$') $lt
return $true
}
# Prompt (masked) + validate + store + activate ONE provider key. Returns $true/$false
# (no exit) so the source menu can loop. Reused by `byok set` (CLI) + the menu.
function Add-ByokKey([string]$prov) {
if (-not (Test-Path $BYOK_SIDECAR)) { Write-Err "byteask: BYOK needs the sidecar; run 'byteask --update' first."; return $false }
if (-not (Get-PyExe)) { Write-Err "byteask: BYOK needs python (not found)."; return $false }
$sec = Read-Host -AsSecureString "Paste your $prov API key (hidden, never shown)"
$key = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec))
if (-not $key) { Write-Err "No key entered."; return $false }
if (-not (Test-ProviderKey $prov $key)) { return $false }
Invoke-ByokMerge @("keys.$prov=$key")
if (-not (Invoke-ByokEnter)) { return $false }
Write-Host "Saved your $prov key."
return $true
}
# One-line per-provider state for the source menu + status.
function Get-ByokStatusLine {
$code = @'
import json,sys
try: keys=json.load(open(sys.argv[1])).get("keys") or {}
except Exception: keys={}
lbl={"openai":"OpenAI","anthropic":"Anthropic","gemini":"Gemini"}
print(" ".join("%s=%s"%(lbl[p],"your key" if keys.get(p) else "managed") for p in ("openai","anthropic","gemini")))
'@
$out = Invoke-Py $code @($BYOK_CFG)
if ($out) { return $out }
return "OpenAI=managed Anthropic=managed Gemini=managed"
}
# Signed in iff a JWT exists AND (best-effort) is not expired (exp claim, decoded read-only).
function Test-SignedIn {
$jwt = Get-CurrentJwt
if (-not $jwt) { return $false }
try {
$seg = $jwt.Split('.')[1].Replace('-','+').Replace('_','/')
switch ($seg.Length % 4) { 2 { $seg += '==' } 3 { $seg += '=' } }
$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($seg))
$exp = [regex]::Match($json, '"exp"\s*:\s*([0-9]+)').Groups[1].Value
if ($exp -and [long]$exp -lt [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()) { return $false }
} catch {}
return $true
}
# The MANAGED provider authenticates with experimental_bearer_token in config.toml - that
# line IS the credential the engine sends. Get-CurrentJwt reads byok-config.json FIRST, so a
# managed config whose token line is missing still reports "signed in" (and the settings
# screen shows the email) while every turn 401s with "Sign in to continue - type /login".
# True == that broken state.
function Test-ManagedMissingToken {
$cfg = Join-Path $CODEX_HOME 'config.toml'
if (-not (Test-Path $cfg)) { return $false }
$pm = Select-String -Path $cfg -Pattern '^model_provider = "(.*)"$' | Select-Object -First 1
if (-not $pm -or $pm.Matches[0].Groups[1].Value -ne 'byteask') { return $false }
return (-not (Select-String -Path $cfg -Pattern '^experimental_bearer_token = ' -Quiet))
}
# $true when the ACTIVE config needs a ByteAsk account; $false when fully self-served.
# Mirrors the sh _needs_byteask_signin: managed provider -> needs us; byok-local self/*
# or a cloud model with the user's own key -> direct, no account; byok-local auto or an
# un-keyed cloud model -> managed-forwards, needs us; other providers -> engine owns auth.
function Test-NeedsSignin {
$prov = Get-CfgLine '^model_provider = "(.*)"$'
if ($prov -eq 'byteask') { return $true }
if ($prov -ne 'byok-local') { return $false }
$model = Get-CfgLine '^model = "(.*)"$'
if ($model -like 'self/*') { return $false }
if (-not $model -or $model -eq 'auto') { return $true }
# Cloud model: no account IFF the user holds their own key for its provider. Reuse the
# served translator predicates (via a temp .py) so the provider map can't drift; any
# failure -> conservative "needs us" (never a silent launch that would 401 first turn).
$code = @'
import json, sys, os
model = os.environ.get("BYTEASK_MODEL", "")
sys.path.insert(0, sys.argv[2])
try:
import anthropic_translate, gemini_translate
if anthropic_translate.is_anthropic_model(model): prov = "anthropic"
elif gemini_translate.is_gemini_model(model): prov = "gemini"
else: prov = "openai"
keys = json.load(open(sys.argv[1])).get("keys") or {}
print("direct" if (keys.get(prov) or "").strip() else "managed")
except Exception:
print("managed")
'@
$env:BYTEASK_MODEL = $model
$out = Invoke-Py $code @($BYOK_CFG, $CODEX_HOME)
Remove-Item Env:\BYTEASK_MODEL -ErrorAction SilentlyContinue
if ($out -and ($out -join '').Trim() -eq 'direct') { return $false }
return $true
}
# Interactive iff a real console, or BYOK_ASSUME_TTY set (test seam).
function Test-MenuTty { if ($env:BYOK_ASSUME_TTY) { return $true }; return (Test-Interactive) }
function Invoke-ByokSet([string[]]$rest) {
$prov = $rest[0]
if (@('openai','anthropic','gemini') -notcontains $prov) {
Write-Err "usage: byteask byok set <openai|anthropic|gemini> [--subscription]"; exit 2 }
if ($prov -eq 'openai' -and (($rest -contains '--subscription') -or ($rest -contains '--sub'))) {
Invoke-ByokSubscription; return }
if (-not (Add-ByokKey $prov)) { exit 1 }
Write-Host "Keyed providers bill to your account; other models use ByteAsk managed (counts toward your usage)."
Write-Host "Relaunching..."
}
function Show-ByokStatus {
if ((Get-ByokKeyCount) -eq 0) { Write-Host "BYOK: off (all traffic is managed)."; return }
Write-Host "BYOK: on. Keyed providers (billed to you):"
$code = @'
import json,sys
try: keys=json.load(open(sys.argv[1])).get("keys") or {}
except Exception: keys={}
for p in ("openai","anthropic","gemini"): print(" - %s: %s"%(p,"your key" if keys.get(p) else "managed"))
'@
$lines = Invoke-Py $code @($BYOK_CFG)
if ($lines) { foreach ($ln in @($lines)) { Write-Host $ln } }
Write-Host " Un-keyed providers use ByteAsk managed (billed to you, counts toward your usage)."
if (Test-SidecarHealth) { Write-Host " sidecar: running on 127.0.0.1:$BYOK_PORT" } else { Write-Host " sidecar: not running (starts on next launch)" }
}
function Invoke-ByokRemove([string[]]$rest) {
$prov = $rest[0]
if (@('openai','anthropic','gemini') -notcontains $prov) { Write-Err "usage: byteask byok remove <openai|anthropic|gemini>"; exit 2 }
Invoke-ByokMerge @("keys.$prov=")
if ((Get-ByokKeyCount) -eq 0) { Invoke-ByokOff } else { [void](Invoke-ByokEnter); Write-Host "Removed your $prov key." }
}
function Invoke-ByokOff {
$jwt = Get-CurrentJwt; $gw = (Resolve-Gateway).TrimEnd('/')
$hadKeys = (Get-ByokKeyCount) -ne 0
$pidf = Join-Path $CODEX_HOME 'byok-sidecar.pid'
if (Test-Path $pidf) { try { Stop-Process -Id ([int](Get-Content $pidf)) -ErrorAction SilentlyContinue } catch {}; Remove-Item -Force -ErrorAction SilentlyContinue $pidf }
Invoke-ByokMerge @('keys.openai=','keys.anthropic=','keys.gemini=')
# A self/* model needs the sidecar; on managed it would fail every turn - reset
# to the default cloud model (mirrors Remove-Model's active-model handling).
$offModel = Get-CfgLine '^model = "(.*)"$'
if ((-not $offModel) -or $offModel.StartsWith('self/')) {
$offModel = if ($env:BYTEASK_MODEL) { $env:BYTEASK_MODEL } else { 'gpt-5.4' }
}
Write-ManagedConfig $offModel (Get-CfgLine '^(model_catalog_json = .*)$') $gw $jwt
if ($hadKeys) { Write-Host "Switched to ByteAsk managed (billed to ByteAsk, /usage as normal)." }
else { Write-Host "You're on ByteAsk managed (billed to ByteAsk, /usage as normal)." }
}
function Invoke-ByokSubscription {
Write-Host "Sign in with your ChatGPT subscription (Plus/Pro/Business)."
Write-Host "Note: OpenAI's own sign-in screen appears; Anthropic/Gemini keys don't mix into a subscription session."
& $ENGINE login; if ($LASTEXITCODE -ne 0) { Write-Err "ChatGPT sign-in failed."; exit 1 }
$cfg = @"
model = "$(Get-CfgLine '^model = "(.*)"$')"
model_provider = "openai"
web_search = "live"
$(Get-CfgLine '^(model_catalog_json = .*)$')
"@
Set-Content -Path (Join-Path $CODEX_HOME 'config.toml') -Value $cfg
Write-Host "ChatGPT subscription active (OpenAI-only session). 'byteask byok off' to return to managed."
}
function Invoke-Byok([string[]]$rest) {
$sub = if ($rest.Count -ge 1) { $rest[0] } else { '' }
$tail = @($rest | Select-Object -Skip 1)
switch ($sub) {
'set' { Invoke-ByokSet $tail }
'remove' { Invoke-ByokRemove $tail }
'rm' { Invoke-ByokRemove $tail }
'off' { Invoke-ByokOff }
{ $_ -eq 'status' -or $_ -eq '' } { Show-ByokStatus }
default { Write-Err "usage: byteask byok <set|status|remove|off> [provider]"; exit 2 }
}
}
# ===================== self-hosted / custom models (byteask models) =========
# Point ByteAsk at the user's OWN OpenAI-compatible server (vLLM/TGI/Ollama/LM Studio/
# DGX). Registry + routing + slim catalog row all via the shared python helper, so this
# stays a thin mirror of the sh wrapper. Pure ASCII (PS 5.1 codepage rule).
function Show-SelfHostedHowto {
Write-Host ""
Write-Host "Other providers & your own hosted model"
Write-Host " A cloud provider with your own key (OpenRouter, Groq, DeepSeek, ...):"
Write-Host " byteask models add or --provider openrouter --key sk-... (they bill you)"
Write-Host " Your OWN OpenAI-compatible server (vLLM/TGI/Ollama/LM Studio/DGX):"
Write-Host " byteask models add my-model --url http://your-host:8000 (never billed)"
Write-Host " See providers: byteask models providers"
Write-Host ""
}
function Show-ModelsHelp {
Write-Err "Use a cloud provider with YOUR key (OpenRouter/Groq/DeepSeek/... - the provider bills you):"
Write-Err " byteask models add <alias> --provider <id> [--key K] [--model ID]"
Write-Err " byteask models providers list the known providers"
Write-Err "Use your OWN hosted model (vLLM/TGI/Ollama/LM Studio/DGX - never billed by ByteAsk):"
Write-Err " byteask models add <alias> --url http://host:8000 [--model ID] [--key K] [--ollama]"
Write-Err " [--wire auto|responses|chat] [--ctx N] [--ca-bundle P] [--insecure]"
Write-Err " byteask models list [--check]"
Write-Err " byteask models test <alias>"
Write-Err " byteask models remove <alias>"
Write-Err "Then pick self/<alias> in /model."
}
# True (silently) when the shared helper is new enough for preset subcommands (D13).
function Test-PresetHelper {
$v = (Invoke-ModelsPy @('version'))
if (-not $v -or $v.Count -lt 1) { return $false }
$n = 0; if ([int]::TryParse("$($v[0])".Trim(), [ref]$n)) { return ($n -ge 2) }
return $false
}
function Require-PresetHelper {
if (Test-PresetHelper) { return $true }
Write-Err "byteask: provider presets need a newer helper - run 'byteask --update'."
return $false
}
# Resolve a preset id -> hashtable, or $null if unknown.
function Get-ProviderPreset([string]$id) {
$line = (Invoke-ModelsPy @('preset', $id))
if (-not $line -or $line.Count -lt 1) { return $null }
$parts = "$($line[0])".Split('|')
if ($parts.Count -lt 6) { return $null }
return @{ url = $parts[1]; wire = $parts[2]; needs = ($parts[3] -eq '1'); env = $parts[4]; kind = $parts[5] }
}
# Discover model ids; key rides BK_KEY (env, not argv - 3A). On failure maps the
# helper's HTTP status to a tailored hint (4A). Returns the id array (empty on fail).
function Invoke-Discover([string]$url, [string]$key, [string]$ca, [string]$insArg) {
$py = Get-ModelsPython
$errf = [System.IO.Path]::GetTempFileName()
$prev = $env:BK_KEY; $env:BK_KEY = $key
try { $out = @(& $py $BYOK_MODELS discover $url '' $ca $insArg 2>$errf) }
finally { if ($null -eq $prev) { Remove-Item Env:BK_KEY -ErrorAction SilentlyContinue } else { $env:BK_KEY = $prev } }
$rc = $LASTEXITCODE
$err = (Get-Content $errf -Raw -ErrorAction SilentlyContinue); Remove-Item $errf -ErrorAction SilentlyContinue
if ($rc -ne 0 -or -not $out -or $out.Count -eq 0) {
if ($err -match 'HTTP 401' -or $err -match 'HTTP 403') { Write-Err " the server rejected your key - check --key or your API key." }
elseif ($err -match 'HTTP 402') { Write-Err " your account needs credits before it can be used (402)." }
elseif ($err -match 'HTTP 404') { Write-Err " no /v1/models at $url - check the URL, or pass --model <id>." }
elseif ($err -match 'HTTP ') { Write-Err " couldn't list models - pass --model <id>." }
else { Write-Err " couldn't reach $url - check the URL / network." }
return @()
}
return $out
}
# Interactive picker (1B): shows up to 20 ids; a typed substring filters the fetched
# set in place; a number picks the shown slice; an exact id is accepted. Returns the id.
function Select-FromIds([string[]]$ids) {
$cur = @($ids)
while ($true) {
$shown = @($cur | Select-Object -First 20)
for ($k=0; $k -lt $shown.Count; $k++) { Write-Err " $($k+1)) $($shown[$k])" }
if ($cur.Count -gt 20) { Write-Err " ... $($cur.Count - 20) more - type a substring to filter, or the exact id" }
$in = Read-Host " pick a number, or type a substring/exact id [1]"
if (-not $in) { return $shown[0] }
if ($in -match '^[1-9][0-9]*$' -and [int]$in -le $shown.Count) { return $shown[[int]$in - 1] }
if ($cur -contains $in) { return $in }
$f = @($cur | Where-Object { $_ -like "*$in*" })
if ($f.Count -eq 0) { Write-Err " no id matches `"$in`"." } else { $cur = $f }
}
}
function Get-Providers {
if (-not (Test-ModelsReady)) { return }
if (-not (Require-PresetHelper)) { return }
Write-Host "Cloud providers - bring your own key (your key, the provider bills you):"
foreach ($ln in (Invoke-ModelsPy @('presets'))) {
$p = "$ln".Split('|'); if ($p.Count -ge 6 -and $p[5] -eq 'cloud') { Write-Host (" {0,-12} {1}" -f $p[0], $p[1]) }
}
Write-Host "Local servers - your compute, never billed:"
foreach ($ln in (Invoke-ModelsPy @('presets'))) {
$p = "$ln".Split('|'); if ($p.Count -ge 6 -and $p[5] -eq 'local') { Write-Host (" {0,-12} {1}" -f $p[0], $p[1]) }
}
Write-Host "Add one: byteask models add <alias> --provider <id> [--key K] [--model ID]"
}
# Returns $true on success, $false on any failure (so the settings screen + exit code can react).
function Add-Model([string[]]$rest) {
if (-not (Test-ModelsReady)) { return $false }
if ($rest.Count -lt 1) { Write-Err "usage: byteask models add <alias> --provider <id> | --url <endpoint>"; return $false }
$alias = $rest[0] -replace '^self/',''
if (-not $alias -or $alias.StartsWith('-')) { Write-Err "usage: byteask models add <alias> --provider <id> | --url <endpoint>"; return $false }
# Seed the key from BK_KEY so a caller can pass it out-of-argv (a command line is
# readable by other processes) - the same channel this function already uses to reach
# the helper. An explicit --key is parsed below and still wins.
$u=''; $mid=''; $key="$env:BK_KEY"; $wire='auto'; $wireSet=$false; $ctx=''; $tools='auto'; $disp=''; $ca=''; $ins=$false; $hdrs=@(); $ollama=$false; $provider=''; $providerId=''; $kind='self'
for ($i=1; $i -lt $rest.Count; $i++) {
switch -Regex ($rest[$i]) {
'^--provider$' { $provider = $rest[++$i] }
'^--url$' { $u = $rest[++$i] }
'^--model$' { $mid = $rest[++$i] }
'^--key$' { $key = $rest[++$i] }
'^--wire$' { $wire = $rest[++$i]; $wireSet = $true }
'^--ctx$' { $ctx = $rest[++$i] }
'^--tools$' { $tools = $rest[++$i] }
'^--name$' { $disp = $rest[++$i] }
'^--ca-bundle$' { $ca = $rest[++$i] }
'^--insecure$' { $ins = $true }
'^--header$' { $hdrs += $rest[++$i] }
'^--ollama$' { $ollama = $true }
default { Write-Err "byteask models add: unknown option $($rest[$i])"; return $false }
}
}
$py = Get-ModelsPython
$insArg = if ($ins) { '1' } else { '' }
# --ollama is an alias for --provider ollama on a preset-capable helper; else the
# historical localhost default (no version gate for existing ollama users).
if ($ollama -and -not $provider) {
if (Test-PresetHelper) { $provider = 'ollama' } elseif (-not $u) { $u = 'http://localhost:11434' }
}
# Resolve a provider preset -> fills URL + wire + key env + kind. --url / --wire win.
if ($provider) {
if (-not (Require-PresetHelper)) { return $false }
$preset = Get-ProviderPreset $provider
if (-not $preset) { Write-Err "byteask models add: unknown provider '$provider'. See: byteask models providers"; return $false }
$providerId = $provider; $kind = $preset.kind
if (-not $u) { $u = $preset.url }
if (-not $wireSet) { $wire = $preset.wire }
if ($preset.needs -and -not $key) {
if ($preset.env) { $key = [Environment]::GetEnvironmentVariable($preset.env) }
if (-not $key -and (Test-Interactive)) {
$key = Read-HiddenLine " $provider API key (input hidden; Enter to abort)"
}
if (-not $key) { Write-Err "byteask models add: $provider needs an API key - pass --key, or set `$$($preset.env)."; return $false }
}
}
if (-not $u) { Write-Err "byteask models add: pass --provider <id> or --url <endpoint>."; return $false }
if (-not $mid) {
Write-Err " probing $u for available models..."
$ids = @(Invoke-Discover $u $key $ca $insArg)
if (-not $ids -or $ids.Count -eq 0) { return $false }
if (Test-Interactive) {
$mid = Select-FromIds $ids
} elseif ($kind -eq 'cloud') {
Write-Err "byteask models add: $provider lists many models - pass --model <id>. For example:"
foreach ($ex in @($ids | Select-Object -First 3)) { Write-Err " $ex" }
return $false
} else { $mid = $ids[0] }
if (-not $mid) { Write-Err " no model selected."; return $false }
Write-Err " model: $mid"
}
if ($wire -eq 'auto') {
$prev = $env:BK_KEY; $env:BK_KEY = $key
try { $w = @(& $py $BYOK_MODELS probe-wire $u $mid '' $ca $insArg 2>$null) }
finally { if ($null -eq $prev) { Remove-Item Env:BK_KEY -ErrorAction SilentlyContinue } else { $env:BK_KEY = $prev } }
$wire = if ($w -and $w.Count -ge 1) { "$($w[0])".Trim() } else { 'chat' }
Write-Err " wire: $wire"
}
$ep = @{ base_url = $u; model_id = $mid; wire = $wire; tools = $tools }
if ($key) { $ep.api_key = $key }
if ($ctx) { $ep.context_window = [int]$ctx }
if ($disp) { $ep.display_name = $disp }
if ($ca) { $ep.ca_bundle = $ca }
if ($ins) { $ep.insecure = $true }
if ($providerId) { $ep.provider_id = $providerId }
if ($hdrs.Count -gt 0) {
$h = @{}
foreach ($x in $hdrs) { $p = $x -split '=', 2; if ($p.Count -eq 2) { $h[$p[0].Trim()] = $p[1].Trim() } }
if ($h.Count -gt 0) { $ep.headers = $h }
}
$json = ($ep | ConvertTo-Json -Compress -Depth 5)
$json | & $py $BYOK_MODELS add $BYOK_CFG $alias | Out-Null
if ($LASTEXITCODE -ne 0) { Write-Err " failed to save the endpoint."; return $false }
if (-not (Invoke-ByokEnter)) { Write-Err " (warning: couldn't start the local sidecar - run 'byteask' to retry)" }
Invoke-ModelsMerge
if ($kind -eq 'cloud') {
Write-Host "Added self/$alias ($mid via $provider). Runs on $provider's cloud under YOUR key - they bill you; agent loops consume credits."
} else {
Write-Host "Added self/$alias ($mid, wire=$wire). Your compute - never billed by ByteAsk."
}
Write-Host "Pick it in /model, or run: byteask --model self/$alias"
if (Test-Interactive) {
$ans = Read-Host " Run a quick test now (one request on your key)? [Y/n]"
if ($ans -match '^[Nn]') { Write-Err " Skipped. Test later: byteask models test $alias" }
else { Test-Model @($alias) | Out-Null }
} else {
Write-Host "Test it end-to-end: byteask models test $alias"
}
return $true
}
function Get-Models([string[]]$rest) {
if (-not (Test-ModelsReady)) { return }
$py = Get-ModelsPython
& $py $BYOK_MODELS list $BYOK_CFG
if (($rest.Count -ge 1) -and ($rest[0] -eq '--check')) {
Write-Host " checking reachability..."
$json = (& $py $BYOK_MODELS list $BYOK_CFG --json 2>$null)
try { $eps = ("$json" | ConvertFrom-Json) } catch { $eps = $null }
if ($eps) {
foreach ($al in $eps.PSObject.Properties.Name) {
$ux = (& $py $BYOK_MODELS get $BYOK_CFG $al base_url 2>$null)
$kx = (& $py $BYOK_MODELS get $BYOK_CFG $al api_key 2>$null)
$prev = $env:BK_KEY; $env:BK_KEY = "$kx"
try { (& $py $BYOK_MODELS discover "$ux" 2>$null) | Out-Null }
finally { if ($null -eq $prev) { Remove-Item Env:BK_KEY -ErrorAction SilentlyContinue } else { $env:BK_KEY = $prev } }
if ($LASTEXITCODE -eq 0) { Write-Host " self/$($al): reachable" } else { Write-Host " self/$($al): UNREACHABLE" }
}
}
}
}
function Test-Model([string[]]$rest) {
if (-not (Test-ModelsReady)) { return }
if ($rest.Count -lt 1) { Write-Err "usage: byteask models test <alias>"; return }
$a = $rest[0] -replace '^self/',''
$py = Get-ModelsPython
& $py $BYOK_MODELS test $BYOK_CFG $a
}
function Remove-Model([string[]]$rest) {
if (-not (Test-ModelsReady)) { return }
if ($rest.Count -lt 1) { Write-Err "usage: byteask models remove <alias>"; return }
$a = $rest[0] -replace '^self/',''
$py = Get-ModelsPython
$res = (& $py $BYOK_MODELS remove $BYOK_CFG $a 2>$null)
$cur = Get-CfgLine '^model = "(.*)"$'
if ($cur -eq "self/$a") {
$def = if ($env:BYTEASK_MODEL) { $env:BYTEASK_MODEL } else { 'gpt-5.4' }
$cfgp = Join-Path $CODEX_HOME 'config.toml'
(Get-Content $cfgp) -replace "^model = ""self/$a""$", "model = ""$def""" | Set-Content $cfgp
Write-Host " (was your active model; switched to $def)"
}
Invoke-ModelsMerge
if ("$res".Trim() -eq 'removed') { Write-Host "Removed self/$a." } else { Write-Host "No self-hosted model 'self/$a'." }
}
# Returns an exit code (0 ok, non-zero on failure) so the top-level dispatch can
# propagate it instead of always exiting 0 (a scriptable failure signal).
function Invoke-Models([string[]]$rest) {
$sub = if ($rest.Count -ge 1) { $rest[0] } else { '' }
$tail = @($rest | Select-Object -Skip 1)
switch ($sub) {
'add' { if (Add-Model $tail) { return 0 } else { return 1 } }
'providers' { Get-Providers; return 0 }
'list' { Get-Models $tail; return 0 }
'ls' { Get-Models $tail; return 0 }
'test' { Test-Model $tail; return 0 }
'remove' { Remove-Model $tail; return 0 }
'rm' { Remove-Model $tail; return 0 }
{ $_ -eq '' -or $_ -eq 'help' -or $_ -eq '--help' -or $_ -eq '-h' } { Show-ModelsHelp; return 0 }
default { Write-Err "usage: byteask models <add|providers|list|test|remove>"; return 2 }
}
}
# Looping per-provider manage view. Keys mix (OpenAI + Anthropic + Gemini can all be
# set); un-keyed providers use ByteAsk managed. No-op when non-interactive. Keys are
# typed at a masked prompt, never shown.
# Signed-in email = the "sub" claim of the JWT (base64url middle segment), decoded via
# .NET (no python dep). Empty on any failure.
function Get-CurrentEmail {
$jwt = Get-CurrentJwt
if (-not $jwt) { return '' }
try {
$seg = $jwt.Split('.')[1].Replace('-','+').Replace('_','/')
switch ($seg.Length % 4) { 2 { $seg += '==' } 3 { $seg += '=' } }
$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($seg))
return ([regex]::Match($json, '"sub"\s*:\s*"([^"]*)"').Groups[1].Value)
} catch { return '' }
}
# Arrow-navigable single-select. Returns the chosen 1-based index (0 = cancel). Up/Down
# move; Enter/Space select; 1-9 jump-select; q/Esc cancel. Falls back to a numbered prompt
# when input is redirected (pipes / tests).
function Select-Menu([string[]]$Options, [int]$Start = 1) {
$n = $Options.Count
if ($env:BYOK_ASSUME_TTY -or [Console]::IsInputRedirected) {
for ($k = 0; $k -lt $n; $k++) { [Console]::Error.WriteLine(" $($k+1)) $($Options[$k])") }
$s = Read-Host '> '
if ($s -match '^[1-9][0-9]*$' -and [int]$s -ge 1 -and [int]$s -le $n) { return [int]$s }
return 0
}
$i = [Math]::Max(0, [Math]::Min($n - 1, $Start - 1)) # initial cursor (1-based $Start, clamped)
try { $top = [Console]::CursorTop } catch { $top = 0 }
while ($true) {
try { [Console]::SetCursorPosition(0, $top) } catch {}
for ($k = 0; $k -lt $n; $k++) {
$line = $(if ($k -eq $i) { '> ' } else { ' ' }) + $Options[$k]
$pad = [Math]::Max(0, [Console]::WindowWidth - 1 - $line.Length)
if ($k -eq $i) { Write-Host ($line + (' ' * $pad)) -ForegroundColor Cyan }
else { Write-Host ($line + (' ' * $pad)) }
}
$key = [Console]::ReadKey($true)
switch ($key.Key) {
'UpArrow' { $i = ($i - 1 + $n) % $n }
'DownArrow' { $i = ($i + 1) % $n }
'Enter' { return ($i + 1) }
'Spacebar' { return ($i + 1) }
'Escape' { return 0 }
default {
$c = [string]$key.KeyChar
if ($c -eq 'q' -or $c -eq 'Q') { return 0 }
if ($c -match '^[1-9]$' -and [int]$c -le $n) { return [int]$c }
}
}
}
}
# ==================== persistent settings screen (PS port) ==================
# Same anchored in-place region as the sh wrapper (docs/menu-redesign-plan.md):
# header, breadcrumb, menu, status line, footer repainted over themselves each
# frame. All console I/O flows through the $script:ScrIO ADAPTER (D6#8) so the
# state machine + geometry run under a MOCK console in automated tests; only
# the final visual pass needs a real Windows console. KEEP THIS FILE PURE ASCII.
$script:ScrIO = @{
GetSize = { ,@([Console]::WindowHeight, [Console]::WindowWidth) }
CursorTop = { [Console]::CursorTop }
SetPos = { param($r) [Console]::SetCursorPosition(0, [Math]::Max(0, $r)) }
WriteRow = { param($text, $color, $noNL)
if ($color) { Write-Host $text -ForegroundColor $color -NoNewline:$noNL }
else { Write-Host $text -NoNewline:$noNL } }
ReadKey = { [Console]::ReadKey($true) }
KeyAvail = { [Console]::KeyAvailable }
CtrlC = { param($on) try { [Console]::TreatControlCAsInput = $on } catch {} }
ReadSecret= { $s = Read-Host -AsSecureString ' '
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($s)) }
ReadLine = { Read-Host ' ' }
}
function Set-ScrIOMock([hashtable]$Mock) { $script:ScrIO = $Mock } # test seam (T27)
function Get-ScrGlyphs {
# Unicode glyphs only where fonts are dependable (Windows Terminal); legacy
# conhost raster fonts get ASCII. Emitted via [char] - the FILE stays ASCII.
if ($env:WT_SESSION -or $env:TERM_PROGRAM) {
return @{ ok=[string][char]0x2713; x=[string][char]0x2717; dot=[string][char]0x00B7
bc=[string][char]0x203A; ud=([string][char]0x2191 + [string][char]0x2193) }
}
return @{ ok='OK'; x='x'; dot='-'; bc='>'; ud='Up/Down' }
}
function Test-ScrOk {
if ($env:BYTEASK_PLAIN_MENU) { return $false }
if ([Console]::IsInputRedirected -or [Console]::IsOutputRedirected) { return $false }
if ($env:BYOK_ASSUME_TTY) { return $false } # test harnesses pipe the numbered path
try {
$sz = & $script:ScrIO.GetSize
if ($sz[0] -lt 16 -or $sz[1] -lt 40) { return $false }
[void](& $script:ScrIO.CursorTop)
return $true
} catch { return $false } # ISE / hosts without a real console buffer
}
function Get-ScrData {
$v = Get-ByokKeyVerbs
$script:ScrD = @{
Email = Get-CurrentEmail
VOA = $v[0]; VAN = $v[1]; VGE = $v[2]
NKeys = Get-ByokKeyCount
Keyed = @()
NSelf = 0; SelfRows = @()
Signed = (Test-SignedIn)
}
if (-not $script:ScrD.Email) { $script:ScrD.Email = 'not signed in' }
if ($v[0] -eq 'change') { $script:ScrD.Keyed += 'openai' }
if ($v[1] -eq 'change') { $script:ScrD.Keyed += 'anthropic' }
if ($v[2] -eq 'change') { $script:ScrD.Keyed += 'gemini' }
if ((Test-Path $BYOK_MODELS) -and (Get-ModelsPython) -and (Test-Path $BYOK_CFG)) {
$rows = @(Invoke-ModelsPy @('list', $BYOK_CFG))
foreach ($r in $rows) { if ("$r" -match 'self/') { $script:ScrD.SelfRows += "$r"; $script:ScrD.NSelf++ } }
}
$g = $script:ScrG
$pk = @{ $true='yours'; $false='managed' }
$script:ScrD.KLine = "Keys: OpenAI " + $pk[($v[0] -eq 'change')] + " $($g.dot) Anthropic " +
$pk[($v[1] -eq 'change')] + " $($g.dot) Gemini " + $pk[($v[2] -eq 'change')]
}
function Get-ScrProvName([string]$p) {
switch ($p) { 'openai' {'OpenAI'} 'anthropic' {'Anthropic'} 'gemini' {'Gemini'} default {$p} }
}
function Enter-ScrKeys {
$script:ScrState = 'keys'; Get-ScrData
$o = @()
$o += ,@('openai', ("OpenAI " + $script:ScrD.VOA + " your key"))
$o += ,@('anthropic', ("Anthropic " + $script:ScrD.VAN + " your key"))
$o += ,@('gemini', ("Gemini " + $script:ScrD.VGE + " your key"))
if ($script:ScrD.NKeys -gt 0) { $o += ,@('remove', 'Remove a key') }
$o += ,@('selfhost', ("Your own hosted model $($script:ScrG.dot) vLLM, TGI, Ollama, LM Studio, DGX, or any OpenAI-compatible server"))
$o += ,@('managed', ("Use ByteAsk managed $($script:ScrG.dot) 16 models incl. GPT, Claude & Gemini, 20% off API pricing"))