-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_wizard.py
More file actions
2151 lines (1925 loc) · 96.1 KB
/
Copy pathsetup_wizard.py
File metadata and controls
2151 lines (1925 loc) · 96.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 python3
"""
ShinAgent Setup Wizard — standalone Flask app.
Runs BEFORE the main requirements.txt is installed, so this file imports
nothing from the ShinAgent codebase itself and only depends on flask,
requests, and pyyaml (installed by setup.sh before this runs). psutil is
soft-imported where used (RAM detection) since it's a HUD-only dependency,
not part of the main requirements.txt, and may genuinely not be present at
wizard-run-time. Safe to run multiple times — re-detects current state and
lets you review/change it rather than assuming a blank slate.
===========================================================================
AUDIT OF THE PREVIOUS WIZARD (this file, before this rewrite)
===========================================================================
Findings from a full read of the prior version before rewriting it:
1. Steps that existed (6, not 8): Welcome/System Check, LLM Backend,
Voice, Google Services (optional), Sim Racing/Flight (optional),
Review & Finish. No dedicated Elite Dangerous step (folded nowhere —
ED wasn't mentioned at all) and no ShinAgent HUD step.
2. Missing entirely: Elite Dangerous / Ship Computer setup (no ED
toggle, no INARA key field, no ed_bridge.py instructions, no
companion-panel URL) and ShinAgent HUD setup (no pywebview/HUD
dependency check, no launch command, no retro gaming mention). The
Vernacular Generator and Pop-Up Video are Settings-panel features, not
first-run setup concerns, so their absence here is correct, not a gap.
3. API key fields: contrary to what might be assumed, GEMINI_API_KEY and
ZAI_API_KEY (GLM) were both ALREADY present in ENV_KEYS and already had
full backend cards in Step 2, including a genuinely good multi-step
Gemini guide with free-tier details and a model selector. Grok and
GLM key fields existed but had no live TEST endpoint (the `noTest`
flag) — not a bug, since testing an untested-tier key risks
surprising the user with a real billed call.
4. The Gemini step-by-step guide: present and reasonably thorough
(3 steps, free-tier numbers, "no credit card" reassurance). Kept and
extended in this rewrite rather than replaced.
5. config.yaml handling (`_update_config`): wrote llm.backend,
llm.gemini.model, voice.input_device/output_device/deepgram_tts.model/
wake_word.enabled, agent.name/call_name/active_profile, face.style,
and integrations.forza_telemetry/ac_telemetry/msfs_telemetry.enabled.
Missing: integrations.ed_telemetry.enabled, ed.inara_enabled — Elite
Dangerous had no config-writing path at all, matching finding #2.
6. Directory creation (`_ensure_directories`): created logs,
logs/conversations, photos/{captures,incoming,processed}, memory/db,
credentials, wake_words, cache/ufc. Missing cache/ed (used by
integrations/ed_inara.py and ed_edsm.py) and cache/popups (used by
integrations/popup_video.py for Pop-Up Video sessions) — both features
self-create their cache dir on first write regardless, so this wasn't
a functional bug, just an incomplete "everything's ready on first run"
guarantee.
Separately (not a wizard bug, but discovered while checking this):
integrations/ed_inara.py and ed_edsm.py both hardcoded
`CACHE_DIR = Path.home() / "imq2" / "cache" / "ed"` instead of the
repo-relative pattern every other cache dir in this codebase uses
(ufc_data.py, popup_video.py both use `Path(__file__).resolve()
.parent.parent / "cache" / ...`) — meaning ED's disk cache silently
pointed at the wrong directory on any machine where the repo isn't
cloned to exactly `~/imq2` (this dev machine included). Fixed in both
files as part of this task, since it directly determines where this
wizard's directory creation needs to point.
7. requirements.txt install: worked correctly (SSE-streamed `pip install
-r requirements.txt`, kept in this rewrite basically unchanged). No
equivalent existed for installing missing *system* packages
(portaudio/ffmpeg/chromium/tmux) — the old Step 1 only warned about
them with no in-wizard fix, despite Step 1's own checklist showing
them as WARN. Added in this rewrite.
8. Completion screen: already correctly referenced
`bash scripts/q2_start.sh` / `q2_stop.sh` / `q2_status.sh` and the web
app URL — NOT bare `python main.py` as might be assumed for an
early-written wizard. Missing from the quick-reference card: the
`tmux attach -t q2` monitor command, the Settings URL, and (new) the
HUD launch command — all added in this rewrite.
9. Other things found while reading: `/setup/api/cameras` was a defined
Flask route with real v4l2-ctl detection logic that the JS never
called anywhere — dead code. No step in the new spec asks for a
camera-selection UI either, so this route is kept for API parity
(webcam vision analysis is a real, separate ShinAgent feature) but
remains intentionally unused by this wizard's own UI, same as before
— noted here explicitly rather than left as an unexplained dead route.
===========================================================================
"""
import importlib
import importlib.util
import json
import os
import platform
import re
import shutil
import socket
import subprocess
import sys
import threading
import time
from pathlib import Path
from flask import Flask, Response, jsonify, request
try:
import yaml
except ImportError:
yaml = None
try:
import requests
except ImportError:
requests = None
BASE_DIR = Path(__file__).resolve().parent
ENV_PATH = BASE_DIR / ".env"
CONFIG_PATH = BASE_DIR / "config" / "config.yaml"
REQUIREMENTS_PATH = BASE_DIR / "requirements.txt"
ENV_KEYS = [
"ANTHROPIC_API_KEY", "OPENAI_API_KEY", "XAI_API_KEY", "ZAI_API_KEY", "GEMINI_API_KEY",
"DEEPGRAM_API_KEY", "PORCUPINE_ACCESS_KEY", "INARA_API_KEY", "TAVILY_API_KEY",
]
REQUIRED_DIRS = (
"logs", "logs/conversations",
"photos/captures", "photos/incoming", "photos/processed",
"credentials", "wake_words",
"cache", "cache/ufc", "cache/ed", "cache/popups",
"memory/db",
)
SYSTEM_PACKAGES = ["portaudio19-dev", "ffmpeg", "chromium-browser", "tmux"]
app = Flask(__name__)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _can_import(name: str) -> bool:
try:
importlib.import_module(name)
return True
except Exception:
return False
def _is_windows() -> bool:
return sys.platform == "win32"
def _is_linux() -> bool:
return sys.platform.startswith("linux")
def _is_pi() -> bool:
return _get_pi_model() is not None
def _get_ram_gb():
"""psutil if available (soft dependency, not in the main
requirements.txt — it's a HUD-only package that may not be installed
yet), else /proc/meminfo on Linux, else None."""
try:
import psutil
return round(psutil.virtual_memory().total / (1024 ** 3), 1)
except Exception:
pass
try:
with open("/proc/meminfo") as f:
for line in f:
if line.startswith("MemTotal:"):
kb = int(line.split()[1])
return round(kb / (1024 ** 2), 1)
except Exception:
pass
return None
def _get_pi_model():
try:
with open("/proc/cpuinfo") as f:
for line in f:
if line.lower().startswith("model"):
return line.split(":", 1)[1].strip()
except Exception:
pass
return None
def _get_disk_free_gb():
try:
return round(shutil.disk_usage(str(BASE_DIR)).free / (1024 ** 3), 1)
except Exception:
return None
def _which_chromium():
return shutil.which("chromium-browser") or shutil.which("chromium") or shutil.which("chromium.exe")
def _which_browser():
"""Chromium first (Linux kiosk display default), then Chrome/Edge --
chromium-browser is rarely installed via a package manager on Windows,
so Chrome or Edge (both ship with every Windows 10/11 install) is the
realistic kiosk-display browser there."""
found = _which_chromium()
if found:
return found
if not _is_windows():
return None
for exe in ("chrome.exe", "msedge.exe"):
path = shutil.which(exe)
if path:
return path
for var in ("PROGRAMFILES", "PROGRAMFILES(X86)"):
base = os.environ.get(var)
if not base:
continue
for rel in ("Google/Chrome/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe"):
candidate = Path(base) / rel
if candidate.exists():
return str(candidate)
return None
def _get_platform_name() -> str:
if _is_windows():
return f"Windows {platform.release()}"
pi_model = _get_pi_model()
if pi_model:
return pi_model
if _is_linux():
try:
info = platform.freedesktop_os_release()
name = info.get("PRETTY_NAME") or info.get("NAME")
if name:
return name
except Exception:
pass
return f"Linux {platform.release()}"
return platform.system() or "Unknown"
def _get_local_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception:
return "localhost"
def _read_env_existing_keys() -> set:
existing = set()
if ENV_PATH.exists():
for line in ENV_PATH.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if stripped and not stripped.startswith("#") and "=" in stripped:
existing.add(stripped.split("=", 1)[0].strip())
return existing
def _write_env(api_keys: dict):
"""Merge-only: append keys that don't already exist in .env, never
touch/overwrite a key that's already present (even if its value is
blank) — the wizard is safe to re-run without clobbering manual edits."""
existing_keys = _read_env_existing_keys()
new_lines = []
for key in ENV_KEYS:
val = (api_keys.get(key) or "").strip()
if val and key not in existing_keys:
new_lines.append(f"{key}={val}")
if not new_lines:
return
prefix = ""
if ENV_PATH.exists():
existing_text = ENV_PATH.read_text(encoding="utf-8")
if existing_text and not existing_text.endswith("\n"):
prefix = "\n"
else:
new_lines.insert(0, "# Auto-generated by ShinAgent setup wizard")
with open(ENV_PATH, "a", encoding="utf-8") as f:
f.write(prefix + "\n".join(new_lines) + "\n")
def _update_config(data: dict):
if yaml is None:
return
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
cfg = {}
if CONFIG_PATH.exists():
cfg = yaml.safe_load(CONFIG_PATH.read_text(encoding="utf-8")) or {}
voice = cfg.setdefault("voice", {})
if data.get("input_device"):
voice["input_device"] = data["input_device"]
if data.get("output_device"):
voice["output_device"] = data["output_device"]
if data.get("tts_voice"):
voice.setdefault("deepgram_tts", {})["model"] = data["tts_voice"]
if data.get("wake_word_enabled") is not None:
voice.setdefault("wake_word", {})["enabled"] = bool(data["wake_word_enabled"])
llm = cfg.setdefault("llm", {})
if data.get("llm_backend"):
llm["backend"] = data["llm_backend"]
if data.get("gemini_model"):
llm.setdefault("gemini", {})["model"] = data["gemini_model"]
agent = cfg.setdefault("agent", {})
agent["name"] = data.get("agent_name") or "ShinAgent"
agent.setdefault("call_name", agent["name"])
agent.setdefault("active_profile", "profiles/default.yaml")
face = cfg.setdefault("face", {})
face["style"] = 1
integrations = cfg.setdefault("integrations", {})
if data.get("forza_enabled") is not None:
integrations.setdefault("forza_telemetry", {})["enabled"] = bool(data["forza_enabled"])
if data.get("ac_enabled") is not None:
integrations.setdefault("ac_telemetry", {})["enabled"] = bool(data["ac_enabled"])
if data.get("msfs_enabled") is not None:
integrations.setdefault("msfs_telemetry", {})["enabled"] = bool(data["msfs_enabled"])
if data.get("ed_enabled") is not None:
integrations.setdefault("ed_telemetry", {})["enabled"] = bool(data["ed_enabled"])
if data.get("ed_enabled") is not None or data.get("inara_enabled") is not None:
ed = cfg.setdefault("ed", {})
if data.get("inara_enabled") is not None:
ed["inara_enabled"] = bool(data["inara_enabled"])
CONFIG_PATH.write_text(
yaml.dump(cfg, default_flow_style=False, allow_unicode=True), encoding="utf-8"
)
def _ensure_directories():
for d in REQUIRED_DIRS:
(BASE_DIR / d).mkdir(parents=True, exist_ok=True)
def _write_personality_state():
"""config/personality_state.yaml doesn't exist until Q2's own
config/loader.py first runs and saves it — writing a sane default here
means the very first launch (before any dial edit) has a real file to
read rather than relying on load_personality_state()'s "not found"
fallback path, matching what a normal running instance would produce."""
if yaml is None:
return
path = BASE_DIR / "config" / "personality_state.yaml"
if path.exists():
return
import datetime
state = {
"active_profile": "profiles/default.yaml",
"dial_overrides": {},
"probability_narration": False,
"wellness_checkins": "off",
"saved_at": datetime.datetime.now().isoformat(),
}
path.write_text(yaml.dump(state, default_flow_style=False, allow_unicode=True), encoding="utf-8")
# ---------------------------------------------------------------------------
# Routes — pages
# ---------------------------------------------------------------------------
@app.route("/setup")
def setup_page():
return Response(WIZARD_HTML, mimetype="text/html")
@app.route("/")
def index_redirect():
return setup_page()
# ---------------------------------------------------------------------------
# Routes — API
# ---------------------------------------------------------------------------
@app.route("/setup/api/check")
def api_check():
wake_dir = BASE_DIR / "wake_words"
checks = {
"python_version": platform.python_version(),
"python_ok": sys.version_info >= (3, 11),
"is_64bit": sys.maxsize > 2**32,
"venv_active": sys.prefix != sys.base_prefix,
"pip_available": _can_import("pip") or importlib.util.find_spec("pip") is not None,
"portaudio": _can_import("sounddevice") or _can_import("pyaudio"),
"ffmpeg": shutil.which("ffmpeg") is not None,
"browser": _which_browser() is not None,
"tmux": shutil.which("tmux") is not None,
"requirements_installed": _can_import("flask") and _can_import("chromadb") and _can_import("anthropic"),
"env_exists": ENV_PATH.exists(),
"config_exists": CONFIG_PATH.exists(),
"google_creds": (BASE_DIR / "credentials" / "credentials.json").exists(),
"wake_word_file": bool(list(wake_dir.glob("*.ppn"))) if wake_dir.exists() else False,
"disk_free_gb": _get_disk_free_gb(),
"ram_gb": _get_ram_gb(),
"pi_model": _get_pi_model(),
"platform": platform.system(),
"platform_release": platform.release(),
"is_windows": _is_windows(),
}
return jsonify(checks)
@app.route("/setup/api/platform")
def api_platform():
return jsonify({
"is_windows": _is_windows(),
"is_linux": _is_linux(),
"is_pi": _is_pi(),
"platform_name": _get_platform_name(),
"python_version": platform.python_version(),
"hostname": platform.node(),
})
@app.route("/setup/api/install", methods=["POST"])
def api_install():
def generate():
if not REQUIREMENTS_PATH.exists():
yield "data: ERROR: requirements.txt not found\n\n"
return
try:
proc = subprocess.Popen(
[sys.executable, "-m", "pip", "install", "-r", str(REQUIREMENTS_PATH)],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
)
except Exception as e:
yield f"data: ERROR: {e}\n\n"
return
for line in proc.stdout:
yield f"data: {line.rstrip()}\n\n"
proc.wait()
yield "data: DONE\n\n" if proc.returncode == 0 else f"data: ERROR (pip exited {proc.returncode})\n\n"
return Response(generate(), mimetype="text/event-stream")
@app.route("/setup/api/install_system", methods=["POST"])
def api_install_system():
"""Streams `sudo apt-get install -y <missing system packages>` on
Linux/Debian. On Windows there's no apt-get equivalent for
ffmpeg/chromium/tmux, but PyAudio is the one of the four that's
actually pip-installable there, so this streams a real
`pip install pyaudio` instead of just printing instructions -- falling
back to the pre-built-wheel note if the source build fails (common on
Windows without a C compiler)."""
def generate():
if _is_windows():
yield "data: Installing PyAudio via pip (no apt-get on Windows)...\n\n"
proc = None
try:
proc = subprocess.Popen(
[sys.executable, "-m", "pip", "install", "pyaudio"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
)
for line in proc.stdout:
yield f"data: {line.rstrip()}\n\n"
proc.wait()
except Exception as e:
yield f"data: ERROR: {e}\n\n"
if proc is None or proc.returncode != 0:
yield "data: PyAudio failed to install from source.\n\n"
yield "data: Download a pre-built wheel instead:\n\n"
yield "data: https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio\n\n"
yield "data: Then run: pip install PyAudio-0.2.14-cpXX-cpXX-win_amd64.whl\n\n"
yield "data: DONE\n\n"
return
if shutil.which("apt-get") is None:
yield "data: No apt-get available on this platform -- install these manually:\n\n"
yield f"data: {' '.join(SYSTEM_PACKAGES)}\n\n"
yield "data: DONE\n\n"
return
try:
proc = subprocess.Popen(
["sudo", "apt-get", "install", "-y"] + SYSTEM_PACKAGES,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
)
except Exception as e:
yield f"data: ERROR: {e}\n\n"
return
for line in proc.stdout:
yield f"data: {line.rstrip()}\n\n"
proc.wait()
yield "data: DONE\n\n" if proc.returncode == 0 else f"data: ERROR (apt-get exited {proc.returncode})\n\n"
return Response(generate(), mimetype="text/event-stream")
@app.route("/setup/api/audio")
def api_audio():
input_devices, output_devices = [], []
try:
import sounddevice as sd
for idx, d in enumerate(sd.query_devices()):
rate = int(d.get("default_samplerate") or 48000)
if d.get("max_input_channels", 0) > 0:
input_devices.append({
"index": idx, "name": d.get("name", "?"),
"channels": d.get("max_input_channels", 1),
"sample_rates": [rate],
})
if d.get("max_output_channels", 0) > 0:
output_devices.append({
"index": idx, "name": d.get("name", "?"),
"channels": d.get("max_output_channels", 2),
})
return jsonify({"input_devices": input_devices, "output_devices": output_devices})
except Exception:
if _is_windows():
return jsonify({
"input_devices": [], "output_devices": [],
"error": "sounddevice not installed. Run: pip install sounddevice",
})
# Fallback: parse `arecord -l` for input devices only (no portable
# equivalent for output enumeration without sounddevice/pyaudio).
try:
out = subprocess.run(["arecord", "-l"], capture_output=True, text=True, timeout=5).stdout
for m in re.finditer(r"card (\d+): ([^\[]+)\[([^\]]*)\], device (\d+): ([^\[]+)\[([^\]]*)\]", out):
input_devices.append({
"index": int(m.group(1)), "name": (m.group(3) or m.group(2)).strip(),
"channels": 1, "sample_rates": [48000],
})
except Exception:
pass
return jsonify({"input_devices": input_devices, "output_devices": output_devices})
@app.route("/setup/api/cameras")
def api_cameras():
"""Not called by this wizard's own UI (no step asks for camera
selection) -- kept for API parity since webcam vision analysis is a
real, separate ShinAgent feature. See the audit note at the top of
this file."""
cameras = []
try:
out = subprocess.run(
["v4l2-ctl", "--list-devices"], capture_output=True, text=True, timeout=5
).stdout
current_name = None
for line in out.splitlines():
if line and not line.startswith((" ", "\t")):
current_name = line.split("(")[0].strip()
elif line.strip().startswith("/dev/video"):
cameras.append({"name": current_name or "Unknown", "path": line.strip()})
except Exception:
pass
return jsonify({"cameras": cameras})
@app.route("/setup/api/test", methods=["POST"])
def api_test():
data = request.get_json(silent=True) or {}
backend = data.get("backend", "")
key = (data.get("key") or "").strip()
if not key:
return jsonify({backend: "invalid", "message": "No key provided"})
if requests is None:
return jsonify({backend: "not_tested", "message": "requests not installed"})
# Gemini gets its own branch with richer status-code handling (below) --
# it's ShinAgent's recommended free default, so a wrong/expired/rate
# -limited key should say exactly which of those it is rather than a
# flat ok/invalid, since that's the backend a first-time user is most
# likely testing.
if backend == "gemini":
try:
r = requests.post(
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
headers={
"Authorization": f"Bearer {key}",
"Content-Type": "application/json",
},
json={
"model": "gemini-2.5-flash",
"messages": [{"role": "user", "content": "Hi"}],
"max_tokens": 5,
},
timeout=5,
)
except Exception as e:
return jsonify({"gemini": "error", "error": str(e)})
if r.status_code == 200:
return jsonify({"gemini": "ok", "model": "gemini-2.5-flash"})
if r.status_code in (401, 403):
return jsonify({"gemini": "invalid", "error": "Key rejected"})
if r.status_code == 429:
return jsonify({"gemini": "ok", "note": "Rate limited but key is valid"})
return jsonify({"gemini": "error", "error": f"HTTP {r.status_code}"})
try:
if backend == "anthropic":
r = requests.post(
"https://api.anthropic.com/v1/messages",
headers={
"x-api-key": key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
json={
"model": "claude-haiku-4-5-20251001",
"max_tokens": 1,
"messages": [{"role": "user", "content": "hi"}],
},
timeout=10,
)
ok = r.status_code == 200
elif backend == "deepgram":
r = requests.get(
"https://api.deepgram.com/v1/projects",
headers={"Authorization": f"Token {key}"}, timeout=10,
)
ok = r.status_code == 200
elif backend == "openai":
r = requests.get(
"https://api.openai.com/v1/models",
headers={"Authorization": f"Bearer {key}"}, timeout=10,
)
ok = r.status_code == 200
else:
return jsonify({backend: "not_tested"})
return jsonify({backend: "ok" if ok else "invalid"})
except Exception as e:
return jsonify({backend: "invalid", "message": str(e)})
@app.route("/setup/api/test/mic", methods=["POST"])
def api_test_mic():
data = request.get_json(silent=True) or {}
device_index = data.get("device_index")
try:
import sounddevice as sd
fs = 16000
duration_s = 2
rec = sd.rec(int(duration_s * fs), samplerate=fs, channels=1, dtype="int16", device=device_index)
sd.wait()
sd.play(rec, fs, device=data.get("output_index"))
sd.wait()
return jsonify({"ok": True})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/setup/api/tts_preview", methods=["POST"])
def api_tts_preview():
"""Not in the task's own Flask-routes list, but required by Step 3's
[PREVIEW] button (sends sample text to Deepgram TTS, plays back in
browser) -- a genuinely necessary route that list omitted."""
data = request.get_json(silent=True) or {}
key = (data.get("key") or "").strip()
voice = data.get("voice") or "aura-2-zeus-en"
if not key:
return jsonify({"ok": False, "error": "No Deepgram key provided"}), 400
if requests is None:
return jsonify({"ok": False, "error": "requests not installed"}), 500
try:
r = requests.post(
f"https://api.deepgram.com/v1/speak?model={voice}",
headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
json={"text": "ShinAgent is ready."},
timeout=15,
)
if r.status_code != 200:
return jsonify({"ok": False, "error": f"HTTP {r.status_code}"}), 400
return Response(r.content, mimetype="audio/mpeg")
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/setup/api/detect_controller")
def api_detect_controller():
"""
8BitDo Zero 2 gamepad-mode detection for the Voice step's Controller
subsection. Self-contained (this wizard imports nothing from the main
ShinAgent codebase, per the module docstring) rather than importing
voice/controller.py's ControllerManager -- duplicates its minimal
name-matching logic instead. Linux/Pi only, same as the real thing.
"""
if _is_windows():
return jsonify({"found": False, "platform": "windows"})
try:
import evdev
for path in evdev.list_devices():
try:
dev = evdev.InputDevice(path)
name = dev.name
dev.close()
if "8bitdo" in name.lower() and "zero" in name.lower():
return jsonify({"found": True, "path": path, "name": name})
except Exception:
continue
return jsonify({"found": False})
except ImportError:
return jsonify({"found": False, "error": "evdev not installed"})
@app.route("/setup/api/check_ppn", methods=["POST"])
def api_check_ppn():
d = BASE_DIR / "wake_words"
files = list(d.glob("*.ppn")) if d.exists() else []
return jsonify({"found": bool(files), "files": [f.name for f in files]})
@app.route("/setup/api/check_creds")
def api_check_creds():
return jsonify({"found": (BASE_DIR / "credentials" / "credentials.json").exists()})
@app.route("/setup/api/google_auth", methods=["POST"])
def api_google_auth():
script = BASE_DIR / "credentials" / "setup_gmail_oauth.py"
if not script.exists():
return jsonify({"ok": False, "error": "credentials/setup_gmail_oauth.py not found"}), 404
try:
# Fire-and-forget: this opens a browser tab for the OAuth consent
# screen and blocks on user interaction there, so the wizard can't
# (and shouldn't) wait on it synchronously -- /setup/api/google_status
# is polled from the browser instead.
subprocess.Popen([sys.executable, str(script)], cwd=str(BASE_DIR))
return jsonify({"ok": True, "message": "Google auth flow started — check for a new browser tab."})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/setup/api/google_status")
def api_google_status():
"""Polled by the browser after google_auth starts the OAuth flow --
credentials/setup_gmail_oauth.py writes gmail_token.json on success,
so its existence is the completion signal."""
token_path = BASE_DIR / "credentials" / "gmail_token.json"
return jsonify({"authorized": token_path.exists()})
@app.route("/setup/api/check_ollama", methods=["POST"])
def api_check_ollama():
if requests is None:
return jsonify({"running": False})
try:
r = requests.get("http://localhost:11434/api/tags", timeout=3)
return jsonify({"running": r.status_code == 200})
except Exception:
return jsonify({"running": False})
@app.route("/setup/api/check_hud", methods=["POST"])
def api_check_hud():
packages = {
"pywebview": _can_import("webview"),
"flask": _can_import("flask"),
"flask_cors": _can_import("flask_cors"),
"requests": _can_import("requests"),
"psutil": _can_import("psutil"),
"vgamepad": _can_import("vgamepad"),
}
return jsonify({
"packages": packages,
"hud_ready": packages["pywebview"] and packages["flask"] and packages["flask_cors"] and packages["psutil"],
"retro_ready": packages["vgamepad"],
})
@app.route("/setup/api/save", methods=["POST"])
def api_save():
data = request.get_json(silent=True) or {}
try:
_write_env(data.get("api_keys", {}) or {})
_update_config(data)
_ensure_directories()
_write_personality_state()
summary = ["Wrote .env", "Updated config.yaml", "Created required directories", "Wrote personality_state.yaml"]
return jsonify({"ok": True, "restart_required": False, "summary": summary})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/setup/api/launch", methods=["POST"])
def api_launch():
if _is_windows():
# No tmux/bash on Windows -- launch in its own console window instead.
# --text (not --face) is the safer default: the kiosk face pulls in
# extra display deps that aren't guaranteed to be installed yet.
try:
subprocess.Popen(
[sys.executable, "main.py", "--text"], cwd=str(BASE_DIR),
creationflags=subprocess.CREATE_NEW_CONSOLE,
)
return jsonify({"ok": True, "output": "Launched ShinAgent in a new console window."})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
script = BASE_DIR / "scripts" / "q2_start.sh"
if not script.exists():
return jsonify({"ok": False, "error": "scripts/q2_start.sh not found"}), 404
try:
result = subprocess.run(
["bash", str(script)], cwd=str(BASE_DIR),
capture_output=True, text=True, timeout=20,
)
return jsonify({"ok": result.returncode == 0, "output": result.stdout + result.stderr})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/setup/api/launch_hud", methods=["POST"])
def api_launch_hud():
"""Only offered when the wizard itself is running on Windows -- if the
server is Linux/Pi, the HUD runs on a separate Windows gaming PC that
this process has no way to reach."""
if not _is_windows():
return jsonify({"ok": False, "error": "HUD auto-launch is only available when ShinAgent itself is on Windows -- run hud/hud.py on your Windows gaming PC instead."}), 400
script = BASE_DIR / "hud" / "hud.py"
if not script.exists():
return jsonify({"ok": False, "error": "hud/hud.py not found"}), 404
try:
subprocess.Popen(
[sys.executable, str(script), "--q2", "localhost"], cwd=str(BASE_DIR),
creationflags=subprocess.CREATE_NEW_CONSOLE,
)
return jsonify({"ok": True, "message": "HUD launched in a new window."})
except Exception as e:
return jsonify({"ok": False, "error": str(e)}), 500
@app.route("/setup/api/server_ip")
def api_server_ip():
return jsonify({"ip": _get_local_ip()})
@app.route("/setup/api/shutdown", methods=["POST"])
def api_shutdown():
def _delayed_exit():
time.sleep(2)
os._exit(0)
threading.Thread(target=_delayed_exit, daemon=True).start()
return jsonify({"ok": True})
# ---------------------------------------------------------------------------
# Wizard HTML — single-page app, all CSS/JS inline
# ---------------------------------------------------------------------------
WIZARD_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ShinAgent Setup</title>
<style>
:root {
--bg: #00080a;
--surface: #021210;
--surface2:#0a1f1a;
--border: rgba(0, 220, 120, 0.15);
--text: #c8f0dc;
--dim: #4a8a6a;
--accent: #ff3c3c;
--accent2: #00c8ff;
--accent3: #00dc78;
--warning: #ffb400;
--danger: #ff3c3c;
}
* { box-sizing: border-box; }
html, body {
margin: 0; padding: 0; background: var(--bg); color: var(--text);
font-family: 'Courier New', monospace;
min-height: 100%;
}
body::before {
content: ""; position: fixed; inset: 0; pointer-events: none; z-index: 999;
background: repeating-linear-gradient(0deg, rgba(0,0,0,0.15) 0px, rgba(0,0,0,0.15) 1px, transparent 1px, transparent 3px);
opacity: 0.35;
}
h1, h2, h3 { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
#app { display: flex; min-height: 100vh; }
/* -- Sidebar -- */
#sidebar {
width: 240px; flex-shrink: 0;
background: var(--surface);
border-right: 1px solid var(--border);
padding: 20px 0;
position: sticky; top: 0; height: 100vh; overflow-y: auto;
}
#sidebar .logo { text-align: center; margin-bottom: 24px; padding: 0 16px; }
#sidebar .logo .title { font-size: 1.3rem; font-weight: 800; letter-spacing: 0.08em; color: var(--accent); text-shadow: 0 0 14px rgba(255,60,60,0.5); }
#sidebar .logo .sub { font-size: 0.68rem; color: var(--dim); margin-top: 4px; }
.step-item {
display: flex; align-items: center; gap: 10px;
padding: 10px 16px; cursor: pointer; font-size: 0.82rem;
border-left: 3px solid transparent;
color: var(--dim);
}
.step-item:hover { background: rgba(0,220,120,0.04); }
.step-item.active { color: var(--text); border-left-color: var(--accent2); background: rgba(0,200,255,0.06); }
.step-item.done { color: var(--accent3); }
.step-item.disabled { cursor: not-allowed; opacity: 0.4; }
.step-num {
width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0;
display: flex; align-items: center; justify-content: center;
font-size: 0.72rem; font-weight: 700;
border: 1px solid var(--border); color: var(--dim);
}
.step-item.active .step-num { border-color: var(--accent2); color: var(--accent2); }
.step-item.done .step-num { border-color: var(--accent3); background: var(--accent3); color: #000; }
.step-item.skip .step-num { border-color: var(--warning); color: var(--warning); }
.step-title-sm { flex: 1; }
.step-icon { font-size: 0.9rem; }
/* -- Main content -- */
#main { flex: 1; position: relative; z-index: 1; min-width: 0; }
.wrap { max-width: 720px; margin: 0 auto; padding: 24px 20px 80px; }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 24px; margin-bottom: 16px; }
.step-title { font-size: 1.4rem; margin: 0 0 6px; color: var(--text); }
.step-desc { color: var(--dim); margin: 0 0 20px; line-height: 1.5; font-size: 0.92rem; }
.checklist { display: flex; flex-direction: column; gap: 8px; margin: 16px 0; }
.check-row { display: flex; align-items: center; gap: 10px; font-size: 0.88rem; flex-wrap: wrap; }
.badge { display: inline-flex; align-items: center; justify-content: center; min-width: 52px; padding: 2px 8px; border-radius: 4px; font-size: 0.72rem; font-weight: 700; letter-spacing: 0.05em; }
.badge-ok { background: rgba(0,220,120,0.15); color: var(--accent3); border: 1px solid var(--accent3); }
.badge-warn { background: rgba(255,180,0,0.12); color: var(--warning); border: 1px solid var(--warning); }
.badge-err { background: rgba(255,60,60,0.12); color: var(--accent); border: 1px solid var(--accent); }
.badge-info { background: rgba(0,200,255,0.1); color: var(--accent2); border: 1px solid var(--accent2); }
.badge-none { background: var(--surface2); color: var(--dim); border: 1px solid var(--border); }
.fix-cmd { margin: 4px 0 0 62px; }
.row { margin-bottom: 16px; }
.row label.field-label { display: block; font-size: 0.82rem; color: var(--dim); margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.05em; }
input[type=text], input[type=password], select, textarea {
width: 100%; background: var(--surface2); border: 1px solid var(--border); color: var(--text);
padding: 10px 12px; border-radius: 6px; font-family: inherit; font-size: 0.92rem;
}
input:focus, select:focus { outline: none; border-color: var(--accent2); }
.input-with-btn { display: flex; gap: 8px; }
.input-with-btn input { flex: 1; }
.key-wrap { position: relative; }
.key-wrap input { padding-right: 40px; }
.eye-toggle { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; color: var(--dim); font-size: 0.8rem; user-select: none; }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 10px 18px; border-radius: 6px; border: none; font-family: inherit; font-size: 0.88rem; font-weight: 700; cursor: pointer; letter-spacing: 0.03em; }
.btn-primary { background: var(--accent); color: #000; }
.btn-primary:hover { background: #ff5c5c; }
.btn-ghost { background: transparent; color: var(--accent3); border: 1px solid var(--accent3); }
.btn-ghost:hover { background: rgba(0,220,120,0.08); }
.btn-cyan { background: transparent; color: var(--accent2); border: 1px solid var(--accent2); }
.btn-cyan:hover { background: rgba(0,200,255,0.08); }
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-sm { padding: 6px 12px; font-size: 0.78rem; }
.btn-full { width: 100%; }
.backend-option { border: 1px solid var(--border); border-radius: 8px; padding: 14px 16px; margin-bottom: 10px; cursor: pointer; transition: border-color 0.15s; }
.backend-option.selected { border-color: var(--accent2); background: rgba(0,200,255,0.05); }
.backend-option .bh { display: flex; align-items: center; gap: 10px; font-weight: 700; }
.backend-option .bh .tag { font-size: 0.68rem; color: var(--accent); border: 1px solid var(--accent); border-radius: 3px; padding: 1px 6px; }
.backend-option .bd { color: var(--dim); font-size: 0.84rem; margin: 6px 0 10px; }
.backend-option .bkey { display: none; }
.backend-option.selected .bkey { display: flex; gap: 8px; }
.gemini-guide { border: 1px solid rgba(0,220,120,0.2); background: rgba(0,20,10,0.5); border-radius: 8px; padding: 14px 16px; margin: 4px 0 12px; }
.gemini-guide .gg-title { display: flex; align-items: center; justify-content: space-between; font-size: 0.76rem; letter-spacing: 0.06em; color: var(--accent3); font-weight: 700; margin-bottom: 10px; }
.gemini-guide .gg-step { margin-bottom: 12px; font-size: 0.84rem; color: var(--dim); line-height: 1.6; }
.gemini-guide .gg-step b { color: var(--text); display: block; margin-bottom: 4px; }
.gemini-guide .gg-step ul { margin: 4px 0 0 18px; padding: 0; }
.gemini-guide .gg-freetier { font-size: 0.8rem; color: var(--dim); border-top: 1px solid rgba(0,220,120,0.15); padding-top: 10px; margin-top: 4px; line-height: 1.6; }
.gemini-model-row { margin-top: 12px; }
.card-toggle { display: flex; align-items: center; justify-content: space-between; border: 1px solid var(--border); border-radius: 8px; padding: 14px 16px; margin-bottom: 12px; }
.card-toggle .ct-body { flex: 1; }
.card-toggle .ct-title { font-weight: 700; margin-bottom: 4px; }
.card-toggle .ct-desc { color: var(--dim); font-size: 0.82rem; line-height: 1.5; }
.card-toggle-extra { border: 1px solid var(--border); border-top: none; border-radius: 0 0 8px 8px; margin: -12px 0 12px; padding: 14px 16px; background: rgba(0,0,0,0.15); }
.toggle { position: relative; width: 46px; height: 26px; flex-shrink: 0; }
.toggle input { opacity: 0; width: 0; height: 0; position: absolute; }
.toggle-track { position: absolute; inset: 0; background: var(--surface2); border: 1px solid var(--border); border-radius: 999px; transition: 0.15s; }
.toggle input:checked ~ .toggle-track { background: var(--accent3); border-color: var(--accent3); }
.toggle-thumb { position: absolute; top: 2px; left: 2px; width: 20px; height: 20px; border-radius: 50%; background: #fff; transition: 0.15s; }
.toggle input:checked ~ .toggle-thumb { transform: translateX(20px); }
.term-log { background: #00080a; border: 1px solid rgba(0,220,120,0.2); font: 12px 'Courier New', monospace; color: var(--accent3); padding: 12px; overflow-y: auto; height: 200px; white-space: pre-wrap; border-radius: 6px; }