-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathonboarding.py
More file actions
1569 lines (1378 loc) · 61.4 KB
/
onboarding.py
File metadata and controls
1569 lines (1378 loc) · 61.4 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
"""
AION Onboarding — First-run Setup Wizard.
Automatically called on first start.
"""
import os
import sys
import json
import re
# UTF-8 + ANSI/VT100 on Windows
if sys.platform == "win32":
os.system("chcp 65001 >nul 2>&1")
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
try:
import ctypes
ctypes.windll.kernel32.SetConsoleMode(
ctypes.windll.kernel32.GetStdHandle(-11), 0x0007)
except Exception:
pass
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from pathlib import Path
BOT_DIR = Path(__file__).parent
# ── ANSI Colors ───────────────────────────────────────────────────────────────
_TTY = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
def _c(code: str, text: str) -> str:
return f"\033[{code}m{text}\033[0m" if _TTY else text
C_CYAN = "96"
C_BOLD = "1"
C_GREEN = "92"
C_YELLOW = "93"
C_RED = "91"
C_DIM = "90"
C_WHITE = "97"
C_LOGO = "96;1"
# ── Helpers ───────────────────────────────────────────────────────────────────
def ok(msg: str) -> None:
print(f" {_c(C_GREEN, '[OK]')} {msg}")
def warn(msg: str) -> None:
print(f" {_c(C_YELLOW, '[!]')} {msg}")
def err(msg: str) -> None:
print(f" {_c(C_RED, '[X]')} {msg}")
def info(msg: str) -> None:
print(f" {_c(C_DIM, '...')} {msg}")
def ask(prompt: str, default: str = "") -> str:
hint = f" [{_c(C_DIM, default)}]" if default else ""
try:
val = input(f" {_c(C_CYAN, prompt)}{hint}: ").strip()
except (EOFError, KeyboardInterrupt):
raise
return val if val else default
def ask_hidden(prompt: str) -> str:
print(f" {_c(C_DIM, '(input is visible — normal for a setup wizard)')}")
return ask(prompt)
def _select(items: list, default: int = 0) -> int:
"""Interactive arrow-key selector. Returns selected index.
Use ↑/↓ to navigate, Enter to confirm.
Falls back to numbered input when stdout is not a TTY."""
n = len(items)
idx = max(0, min(default, n - 1))
def _render(sel: int) -> None:
for i, item in enumerate(items):
if i == sel:
print(f" {_c('92;1', '>')} {_c('97;1', item)}")
else:
print(f" {_c(C_DIM, item)}")
sys.stdout.flush()
def _erase(count: int) -> None:
sys.stdout.write(f"\x1b[{count}A\x1b[J")
sys.stdout.flush()
if not _TTY:
# Non-interactive fallback
for i, item in enumerate(items, 1):
marker = _c(C_GREEN, "*") if i - 1 == default else " "
print(f" {marker} {_c(C_WHITE, str(i))} {item}")
print()
while True:
val = ask(f"Choice (1-{n})", str(default + 1))
if val.isdigit() and 1 <= int(val) <= n:
return int(val) - 1
warn(f"Enter a number between 1 and {n}.")
print(f" {_c(C_DIM, 'Arrow keys ↑↓ · Enter to select')}")
_render(idx)
try:
if sys.platform == "win32":
import msvcrt
while True:
key = msvcrt.getch()
if key in (b'\r', b'\n'):
break
if key in (b'\x00', b'\xe0'):
k2 = msvcrt.getch()
if k2 == b'H': # Up
idx = (idx - 1) % n
elif k2 == b'P': # Down
idx = (idx + 1) % n
elif key == b'\x1b':
raise KeyboardInterrupt
_erase(n)
_render(idx)
else:
import tty, termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
while True:
ch = sys.stdin.read(1)
if ch in ('\r', '\n'):
break
if ch == '\x1b':
seq = sys.stdin.read(2)
if seq == '[A':
idx = (idx - 1) % n
elif seq == '[B':
idx = (idx + 1) % n
elif ch == '\x03':
raise KeyboardInterrupt
_erase(n)
_render(idx)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
except Exception:
pass # keep last idx
_erase(n)
print(f" {_c(C_GREEN, '>')} {_c('97;1', items[idx])}")
return idx
def _checkboxes(items: list, defaults: "list[int] | None" = None,
title: str = "") -> "list[int]":
"""Multi-select checkbox list.
Space = toggle · ↑↓ = navigate · Enter = confirm
Returns list of selected indices. Falls back to numbered input when not a TTY."""
n = len(items)
checked = set(defaults or [])
idx = 0
def _render(cur: int) -> None:
if title:
print(f" {_c(C_DIM, title)}")
for i, item in enumerate(items):
box = _c(C_GREEN, "[x]") if i in checked else _c(C_DIM, "[ ]")
cursor = _c("92;1", ">") if i == cur else " "
label = _c("97;1", item) if i == cur else _c(C_DIM, item)
print(f" {cursor} {box} {label}")
print(f" {_c(C_DIM, 'Space = toggle · Enter = confirm')}")
sys.stdout.flush()
def _erase(count: int) -> None:
lines = count + (1 if title else 0) + 1 # items + title + hint
sys.stdout.write(f"\x1b[{lines}A\x1b[J")
sys.stdout.flush()
if not _TTY:
for i, item in enumerate(items, 1):
marker = _c(C_GREEN, "[x]") if (i - 1) in checked else "[ ]"
print(f" {marker} {_c(C_WHITE, str(i))} {item}")
print()
raw = ask(f"Select (comma-separated, e.g. 1,3 or Enter = none)", "")
result = set()
for part in raw.split(","):
part = part.strip()
if part.isdigit() and 1 <= int(part) <= n:
result.add(int(part) - 1)
return sorted(result)
print(f" {_c(C_DIM, 'Arrow keys ↑↓ · Space = toggle · Enter = confirm')}")
_render(idx)
try:
if sys.platform == "win32":
import msvcrt
while True:
key = msvcrt.getch()
if key in (b'\r', b'\n'):
break
if key in (b'\x00', b'\xe0'):
k2 = msvcrt.getch()
if k2 == b'H':
idx = (idx - 1) % n
elif k2 == b'P':
idx = (idx + 1) % n
elif key == b' ':
if idx in checked:
checked.discard(idx)
else:
checked.add(idx)
elif key == b'\x1b':
raise KeyboardInterrupt
_erase(n)
_render(idx)
else:
import tty, termios
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
while True:
ch = sys.stdin.read(1)
if ch in ('\r', '\n'):
break
if ch == '\x1b':
seq = sys.stdin.read(2)
if seq == '[A':
idx = (idx - 1) % n
elif seq == '[B':
idx = (idx + 1) % n
elif ch == ' ':
if idx in checked:
checked.discard(idx)
else:
checked.add(idx)
elif ch == '\x03':
raise KeyboardInterrupt
_erase(n)
_render(idx)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
except Exception:
pass
_erase(n)
# Print final state
for i, item in enumerate(items):
box = _c(C_GREEN, "[x]") if i in checked else _c(C_DIM, "[ ]")
print(f" {box} {_c(C_DIM, item)}")
return sorted(checked)
def section(title: str, step: str) -> None:
print()
print(f" {_c(C_LOGO, '====================================================')} ")
print(f" {_c(C_BOLD, step)} {_c(C_WHITE, title)}")
print(f" {_c(C_LOGO, '====================================================')} ")
print()
# ── Provider & Model Registry ─────────────────────────────────────────────────
PROVIDERS = {
"gemini": {
"label": "Google Gemini",
"note": "Free tier available · fast · recommended",
"key_env": "GEMINI_API_KEY",
"key_url": "https://aistudio.google.com/app/apikey",
"key_fmt": "AIza",
"key_hint": "Format: AIza...",
"models": [
("gemini-2.5-pro", "Best quality · deep reasoning · slow"),
("gemini-2.5-flash", "Fast & affordable (recommended)"),
("gemini-2.5-flash-lite", "Ultra-fast · minimal cost"),
("gemini-2.0-flash", "Stable & reliable"),
],
"default_model": "gemini-2.5-flash",
},
"openai": {
"label": "OpenAI",
"note": "GPT-4.1, o3, o4-mini ...",
"key_env": "OPENAI_API_KEY",
"key_url": "https://platform.openai.com/api-keys",
"key_fmt": "sk-",
"key_hint": "Format: sk-...",
"models": [
("gpt-4.1", "OpenAI flagship · best quality"),
("gpt-4.1-mini", "Faster GPT-4.1 · affordable"),
("gpt-4o", "Multimodal · images & audio"),
("o3", "Deep reasoning · slow & expensive"),
("o4-mini", "Fast reasoning · affordable (recommended)"),
("gpt-4o-mini", "Ultra-fast · minimal cost"),
],
"default_model": "o4-mini",
},
"deepseek": {
"label": "DeepSeek",
"note": "Very fast · very cheap · strong reasoning",
"key_env": "DEEPSEEK_API_KEY",
"key_url": "https://platform.deepseek.com",
"key_fmt": "sk-",
"key_hint": "Format: sk-...",
"models": [
("deepseek-chat", "DeepSeek V3 · best for general tasks"),
("deepseek-reasoner", "DeepSeek R1 · math / code / reasoning"),
],
"default_model": "deepseek-chat",
},
"anthropic": {
"label": "Anthropic (Claude)",
"note": "Claude Sonnet/Opus/Haiku · strong coding",
"key_env": "ANTHROPIC_API_KEY",
"key_url": "https://console.anthropic.com/settings/keys",
"key_fmt": "sk-ant-",
"key_hint": "Format: sk-ant-...",
"models": [
("claude-opus-4-6", "Most capable · slow · expensive"),
("claude-sonnet-4-6", "Best balance · fast (recommended)"),
("claude-haiku-4-5-20251001", "Fastest · cheapest"),
("claude-3-5-sonnet-20241022","Claude 3.5 Sonnet (stable)"),
],
"default_model": "claude-sonnet-4-6",
},
"grok": {
"label": "xAI Grok",
"note": "Grok 3 · real-time knowledge",
"key_env": "XAI_API_KEY",
"key_url": "https://console.x.ai",
"key_fmt": "xai-",
"key_hint": "Format: xai-...",
"models": [
("grok-3", "Grok 3 flagship"),
("grok-3-mini", "Grok 3 Mini · fast & cheap"),
("grok-2", "Grok 2 (previous gen)"),
],
"default_model": "grok-3",
},
"ollama": {
"label": "Ollama (local)",
"note": "100% offline · no API key · any model",
"key_env": None,
"key_url": "https://ollama.com/download",
"key_fmt": None,
"key_hint": "No API key needed",
"models": [
("ollama/llama3.2", "Meta Llama 3.2 · 3B · fast"),
("ollama/llama3.1:8b", "Meta Llama 3.1 · 8B · good quality"),
("ollama/qwen2.5", "Alibaba Qwen 2.5 · strong multilingual"),
("ollama/deepseek-r1:8b", "DeepSeek R1 distilled · reasoning"),
("ollama/mistral", "Mistral 7B"),
("ollama/phi4", "Microsoft Phi-4"),
("ollama/gemma3", "Google Gemma 3"),
("ollama/codellama", "Meta Code Llama · coding"),
],
"default_model": "ollama/llama3.2",
},
}
# ── Banner ────────────────────────────────────────────────────────────────────
def banner() -> None:
print()
print(_c(C_LOGO, " ===================================================="))
print(_c(C_LOGO, " = ="))
print(_c(C_LOGO, " = AION -- First Start: Setup ="))
print(_c(C_LOGO, " = ="))
print(_c(C_LOGO, " ===================================================="))
print()
print(f" {_c(C_WHITE, 'Welcome! This wizard sets up AION once.')}")
print(f" {_c(C_DIM, 'Settings can be changed later in .env, config.json, or the encrypted Vault.')}")
print()
# ── Step 1: Primary Provider ──────────────────────────────────────────────────
def step1_provider() -> str:
section("Choose your primary AI provider", "Step 1/9:")
print(f" {_c(C_DIM, 'This will be the default model. You can add more providers in step 2.')}")
print()
provider_list = list(PROVIDERS.keys())
items = []
for pid in provider_list:
p = PROVIDERS[pid]
key_note = " (no key needed)" if not p["key_env"] else ""
items.append(f"{p['label']:<22} {p['note']}{key_note}")
idx = _select(items, default=0)
ok(f"Provider: {PROVIDERS[provider_list[idx]]['label']}")
return provider_list[idx]
# ── Step 2: Primary API Key ───────────────────────────────────────────────────
def _ask_api_key(provider_id: str) -> str:
p = PROVIDERS[provider_id]
if not p["key_env"]:
# Ollama: no key needed
info(f"Ollama uses local models — no API key required.")
info(f"Install from: {p['key_url']}")
info(f"Then run: ollama pull llama3.2")
return "ollama"
print(f" {_c(C_DIM, 'Create key at:')}")
print(f" {_c(C_CYAN, p['key_url'])}")
print(f" {_c(C_DIM, p['key_hint'])}")
print()
while True:
api_key = ask_hidden(f"API key for {p['label']}")
if not api_key:
warn("API key cannot be empty.")
continue
if p["key_fmt"] and not api_key.startswith(p["key_fmt"]):
warn(f"Key does not start with '{p['key_fmt']}' — are you sure?")
confirm = ask("Use anyway? (y/n)", "y")
if confirm.lower() == "n":
continue
return api_key
def step2_apikey(provider: str) -> str:
section(f"API key for {PROVIDERS[provider]['label']}", "Step 2/9:")
return _ask_api_key(provider)
# ── Step 3: Model ─────────────────────────────────────────────────────────────
def step3_model(provider: str) -> str:
section("Choose a model", "Step 3/9:")
p = PROVIDERS[provider]
model_list = p["models"]
default_model = p["default_model"]
print(f" {_c(C_DIM, 'Available models for')} {_c(C_CYAN, p['label'])}:")
print()
default_idx = next(
(i for i, (n, _) in enumerate(model_list) if n == default_model), 0
)
items = [f"{name:<40} {desc}" for name, desc in model_list]
idx = _select(items, default=default_idx)
chosen = model_list[idx][0]
ok(f"Model: {chosen}")
return chosen
# ── Step 4: Additional Providers ─────────────────────────────────────────────
def step4_additional_providers(primary: str) -> dict:
section("Additional providers (optional)", "Step 4/9:")
print(f" {_c(C_DIM, 'Add more providers so AION can switch models on demand.')}")
print(f" {_c(C_DIM, 'Each provider is active when its key is in .env or the encrypted Vault.')}")
print()
extra_keys: dict = {}
remaining = [pid for pid in PROVIDERS if pid != primary]
items = []
for pid in remaining:
p = PROVIDERS[pid]
note = "(no key needed)" if not p["key_env"] else p["note"]
items.append(f"{p['label']} — {note}")
print(f" {_c(C_DIM, 'Select with Space, confirm with Enter:')}")
print()
selected_idx = _checkboxes(items)
selected_pids = [remaining[i] for i in selected_idx]
print()
for pid in selected_pids:
p = PROVIDERS[pid]
if not p["key_env"]:
info(f"Install: {p['key_url']}")
info("Then run: ollama pull llama3.2")
ok(f"{p['label']} enabled (no key needed)")
else:
print()
key = _ask_api_key(pid)
if key:
extra_keys[p["key_env"]] = key
ok(f"{p['label']} key saved.")
print()
if not selected_pids:
info("No additional providers selected.")
return extra_keys
# ── Step 5: Messaging Channels ────────────────────────────────────────────────
def step5_channels() -> dict:
section("Messaging channels (optional)", "Step 5/9:")
print(f" {_c(C_DIM, 'Connect AION to messaging platforms — each is a separate plugin.')}")
print(f" {_c(C_DIM, 'All channels are optional. You can add them later via .env or the Vault.')}")
print()
result: dict = {}
channel_items = [
"Telegram — text, images, voice messages (bidirectional bot)",
"Discord — @Mentions and DMs, slash command /ask",
"Slack — @Mentions and DMs via Socket Mode",
]
print(f" {_c(C_DIM, 'Select with Space, confirm with Enter:')}")
print()
selected = _checkboxes(channel_items)
print()
# ── Telegram ────────────────────────────────────────────────────────────
if 0 in selected:
print(f" {_c(C_CYAN, 'Telegram setup:')}")
print(f" {_c(C_DIM, '1. Create a bot via @BotFather on Telegram → copy token')}")
print(f" {_c(C_DIM, '2. Get Chat ID: open https://api.telegram.org/bot<TOKEN>/getUpdates')}")
print()
token = ask("Bot token (e.g. 123456:ABC-...)")
chat_id = ask("Chat ID (e.g. 123456789)")
if token and chat_id:
result["TELEGRAM_BOT_TOKEN"] = token
result["TELEGRAM_CHAT_ID"] = chat_id
ok("Telegram configured.")
else:
warn("Token or Chat ID missing — Telegram skipped.")
print()
# ── Discord ─────────────────────────────────────────────────────────────
if 1 in selected:
print(f" {_c(C_CYAN, 'Discord setup:')}")
print(f" {_c(C_DIM, '1. discord.com/developers/applications → New App → Bot')}")
print(f" {_c(C_DIM, '2. Copy Bot Token')}")
_msg = '3. Enable "Message Content Intent" under Bot \u2192 Privileged Gateway Intents'
print(f" {_c(C_DIM, _msg)}")
print()
dc_token = ask("Discord Bot Token")
if dc_token:
result["DISCORD_BOT_TOKEN"] = dc_token
ok("Discord configured.")
else:
warn("No token entered — Discord skipped.")
print()
# ── Slack ────────────────────────────────────────────────────────────────
if 2 in selected:
print(f" {_c(C_CYAN, 'Slack setup:')}")
print(f" {_c(C_DIM, '1. api.slack.com/apps → New App → From scratch')}")
print(f" {_c(C_DIM, '2. Enable Socket Mode → generate App-Level Token (scope: connections:write)')}")
print(f" {_c(C_DIM, '3. OAuth & Permissions → Bot scopes: app_mentions:read, chat:write, im:history, im:read, im:write')}")
print(f" {_c(C_DIM, '4. Install app → copy Bot User OAuth Token')}")
print()
sl_bot_token = ask("Slack Bot Token (xoxb-...)")
sl_app_token = ask("Slack App Token (xapp-...)")
if sl_bot_token and sl_app_token:
result["SLACK_BOT_TOKEN"] = sl_bot_token
result["SLACK_APP_TOKEN"] = sl_app_token
ok("Slack configured.")
else:
warn("Token(s) missing — Slack skipped.")
print()
if not selected:
info("No channels selected — you can add them later via .env or the Vault.")
print()
return result
# ── Step 5b: MCP Servers ──────────────────────────────────────────────────────
MCP_SERVERS = [
{
"id": "filesystem",
"label": "Filesystem — read/write local folders",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"needs_vault": False,
"arg_prompt": "Path to expose (e.g. C:/Users/Paul/Documents)",
"arg_key": None,
},
{
"id": "github",
"label": "GitHub — repos, issues, PRs, code search",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"needs_vault": True,
"vault_key": "mcp_github",
"vault_env": "GITHUB_PERSONAL_ACCESS_TOKEN",
"key_hint": "Personal Access Token — github.com/settings/tokens",
},
{
"id": "postgres",
"label": "PostgreSQL — query your database",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"needs_vault": True,
"vault_key": "mcp_postgres",
"vault_env": "POSTGRES_URL",
"key_hint": "Connection string, e.g. postgresql://user:pass@localhost/db",
},
{
"id": "notion",
"label": "Notion — pages, databases, search",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-notion"],
"needs_vault": True,
"vault_key": "mcp_notion",
"vault_env": "NOTION_API_TOKEN",
"key_hint": "Integration token — notion.so/my-integrations",
},
]
def step5b_mcp() -> dict:
"""Returns mcp_servers dict to write to mcp_servers.json."""
section("MCP Integrations (optional)", "Step 5b/9:")
print(f" {_c(C_DIM, 'MCP servers give AION instant access to external services.')}")
print(f" {_c(C_DIM, 'Requires: npm/npx installed · pip install mcp')}")
print()
items = [s["label"] for s in MCP_SERVERS]
selected = _checkboxes(items)
print()
if not selected:
info("No MCP servers selected — add them later via mcp_servers.json.")
print()
return {}
servers: dict = {}
for i in selected:
srv = MCP_SERVERS[i]
sid = srv["id"]
if srv["id"] == "filesystem":
folder = ask("Path to expose", str(Path.home()))
servers[sid] = {
"command": srv["command"],
"args": srv["args"] + [folder],
}
ok(f"Filesystem configured ({folder})")
elif srv.get("needs_vault"):
print()
print(f" {_c(C_CYAN, srv['id'].capitalize() + ' setup:')}")
print(f" {_c(C_DIM, srv['key_hint'])}")
token = ask(f"{srv['vault_env']}")
if token:
# Store in vault
_write_vault(srv["vault_key"], token)
servers[sid] = {
"command": srv["command"],
"args": srv["args"],
"vault_env": {srv["vault_env"]: srv["vault_key"]},
}
ok(f"{sid} configured (token stored in vault)")
else:
warn(f"{sid} skipped — no token entered")
print()
return servers
def _write_vault(key: str, value: str) -> None:
"""Writes a value to the credentials vault during onboarding."""
try:
import re as _re
from cryptography.fernet import Fernet
vault_dir = BOT_DIR / "credentials"
key_file = vault_dir / ".vault.key"
vault_dir.mkdir(parents=True, exist_ok=True)
if key_file.exists():
fernet_key = key_file.read_bytes().strip()
else:
fernet_key = Fernet.generate_key()
key_file.write_bytes(fernet_key)
try:
key_file.chmod(0o600)
except Exception:
pass
fernet = Fernet(fernet_key)
name = _re.sub(r"[^\w\-]", "_", key.lower().strip())
name = _re.sub(r"_+", "_", name).strip("_")
enc_path = vault_dir / f"{name}.md.enc"
enc_path.write_bytes(fernet.encrypt(value.encode("utf-8")))
except Exception as e:
warn(f"Vault write failed: {e}")
# ── Step 5c: Hub Plugins ──────────────────────────────────────────────────────
_HUB_MANIFEST_URL = (
"https://raw.githubusercontent.com/xynstr/aion-hub-plugins/main/manifest.json"
)
# Curated plugin list shown during onboarding (name → label shown to user)
_HUB_ONBOARDING_PLUGINS = [
("desktop", "Desktop Automation — mouse, keyboard, screenshots"),
("playwright_browser", "Browser Automation — headless Chromium via Playwright"),
("multi_agent", "Multi-Agent — run parallel sub-agents"),
("audio_pipeline", "Audio Pipeline — voice input/output (TTS + transcription)"),
("docx_tool", "DOCX Creator — create Word documents"),
("image_search", "Image Search — find images on the web"),
]
# Messaging plugins auto-selected when the corresponding channel was configured
_CHANNEL_PLUGINS = {
"TELEGRAM_BOT_TOKEN": ("telegram_bot", "Telegram Bot"),
"DISCORD_BOT_TOKEN": ("discord_bot", "Discord Bot"),
"SLACK_BOT_TOKEN": ("slack_bot", "Slack Bot"),
}
async def _hub_install_offline(name: str, manifest: dict) -> bool:
"""Download + extract a hub plugin without hot-reload (AION not running yet)."""
import hashlib, zipfile, shutil, subprocess, sys, tempfile
from pathlib import Path
try:
import httpx
except ImportError:
warn("httpx not installed — cannot download plugins during setup.")
return False
info = manifest.get(name)
if not info:
warn(f"Plugin '{name}' not found in manifest.")
return False
url = info.get("download_url")
expected = info.get("sha256")
if not url:
warn(f"No download_url for '{name}'.")
return False
try:
async with httpx.AsyncClient(timeout=60, follow_redirects=True) as c:
r = await c.get(url)
r.raise_for_status()
zip_bytes = r.content
except Exception as e:
warn(f"Download failed for '{name}': {e}")
return False
if expected:
actual = hashlib.sha256(zip_bytes).hexdigest()
if actual != expected:
warn(f"SHA256 mismatch for '{name}' — skipping.")
return False
plugins_dir = Path(__file__).parent / "plugins"
plugin_dir = plugins_dir / name
try:
with tempfile.TemporaryDirectory() as tmp:
from pathlib import Path as _P
tmp_zip = _P(tmp) / f"{name}.zip"
tmp_zip.write_bytes(zip_bytes)
with zipfile.ZipFile(tmp_zip) as zf:
names = zf.namelist()
prefix = name + "/"
if all(n == prefix or n.startswith(prefix) for n in names):
zf.extractall(tmp)
extracted = _P(tmp) / name
else:
extracted = _P(tmp) / name
extracted.mkdir()
zf.extractall(extracted)
if plugin_dir.exists():
shutil.rmtree(plugin_dir)
shutil.copytree(extracted, plugin_dir)
(plugin_dir / "version.txt").write_text(info.get("version", "?"), encoding="utf-8")
except Exception as e:
warn(f"Extract failed for '{name}': {e}")
return False
# Install dependencies (optional — don't fail if this breaks)
deps = info.get("dependencies", [])
req_f = plugin_dir / "requirements.txt"
pip_cmd = None
if req_f.exists():
pip_cmd = [sys.executable, "-m", "pip", "install", "-r", str(req_f), "-q"]
elif deps:
pip_cmd = [sys.executable, "-m", "pip", "install", "-q"] + deps
if pip_cmd:
try:
subprocess.run(pip_cmd, timeout=120, check=False)
except Exception:
pass
return True
def step5c_hub_plugins(channels: dict) -> None:
"""Offer curated hub plugins during onboarding. Auto-select messaging plugins."""
import asyncio
section("Optional plugins from the Hub", "Step 5c/9:")
print(f" {_c(C_DIM, 'AION ships with core tools only. Additional plugins can be installed')}")
print(f" {_c(C_DIM, 'from the Plugin Hub — also available later in the Web UI under Plugins → Hub.')}")
print()
# Fetch manifest once (needed for downloads)
manifest: dict = asyncio.run(_fetch_manifest_sync())
if not manifest:
info("Hub not reachable — skipping. You can install plugins later via the Web UI.")
print()
return
# Build ordered list: channel plugins (auto-pre-selected) then curated plugins
ordered: list[tuple[str, str]] = [] # (plugin_name, display_label)
auto_indices: list[int] = []
for ch_key, (pname, label) in _CHANNEL_PLUGINS.items():
if channels.get(ch_key):
auto_indices.append(len(ordered))
ordered.append((pname, f"{label} {_c(C_GREEN, '(auto — channel configured)')}"))
for pname, label in _HUB_ONBOARDING_PLUGINS:
ordered.append((pname, label))
items = [label for _, label in ordered]
print(f" {_c(C_DIM, 'Select with Space, confirm with Enter:')}")
print()
selected_indices = _checkboxes(items, defaults=auto_indices)
print()
to_install = [ordered[i][0] for i in selected_indices]
if not to_install:
info("No hub plugins selected — you can install them later via Plugins → Hub.")
print()
return
print(f" Installing {len(to_install)} plugin(s)…")
print()
for pname in to_install:
print(f" ⟳ {pname} … ", end="", flush=True)
success = asyncio.run(_hub_install_offline(pname, manifest))
print(_c(C_GREEN, "ok") if success else _c(C_YELLOW, "skipped"))
print()
ok("Plugins installed — they will be active on first AION start.")
print()
async def _fetch_manifest_sync() -> dict:
try:
import httpx
async with httpx.AsyncClient(timeout=8) as c:
r = await c.get(_HUB_MANIFEST_URL)
r.raise_for_status()
return r.json()
except Exception:
return {}
# ── Step 6: Profile ───────────────────────────────────────────────────────────
def step6_profile() -> dict:
section("Your profile", "Step 6/9:")
print(f" {_c(C_DIM, 'Helps AION adapt to you from day one.')}")
print()
name = ask("Your name", "")
print()
print(f" {_c(C_DIM, 'Address:')}")
anrede = ["informal", "formal"][_select(["informal (you)", "formal (Sir/Ma'am)"], default=0)]
print()
print(f" {_c(C_DIM, 'Primary language:')}")
lang = ["German", "English", "mixed"][_select(["German", "English", "mixed"], default=0)]
print()
_use_hint = 'Primary use (comma-separated, e.g. "1,3"):'
print(f" {_c(C_DIM, _use_hint)}")
print(f" {_c(C_WHITE, '1')} Coding")
print(f" {_c(C_WHITE, '2')} Research")
print(f" {_c(C_WHITE, '3')} Productivity")
print(f" {_c(C_WHITE, '4')} Creative writing")
print(f" {_c(C_WHITE, '5')} General")
use_map = {"1": "Coding", "2": "Research", "3": "Productivity",
"4": "Creative writing", "5": "General"}
use_input = ask("Selection (e.g. 1,3)", "5")
uses = [use_map[p.strip()] for p in use_input.split(",") if p.strip() in use_map] or ["General"]
print()
print(f" {_c(C_DIM, 'Response style:')}")
style = ["Short & concise", "Normal", "Detailed"][_select(
["Short & concise", "Normal", "Detailed"], default=1
)]
print()
extra = ask("Anything AION should know from the start? (optional, Enter = skip)", "")
return {"name": name, "anrede": anrede, "lang": lang,
"uses": uses, "style": style, "extra": extra}
# ── Step 7: Permissions ───────────────────────────────────────────────────────
_PERM_PRESETS = {
"conservative": {
"shell_exec": "ask", "install_package": "ask", "file_write": "ask",
"file_delete": "ask", "self_modify": "ask", "create_plugin": "ask",
"restart": "ask", "web_search": "allow", "web_fetch": "allow",
"telegram_auto": "ask", "memory_write": "allow", "schedule": "ask",
},
"balanced": {
"shell_exec": "ask", "install_package": "ask", "file_write": "allow",
"file_delete": "ask", "self_modify": "ask", "create_plugin": "ask",
"restart": "ask", "web_search": "allow", "web_fetch": "allow",
"telegram_auto": "allow", "memory_write": "allow", "schedule": "ask",
},
"autonomous": {
"shell_exec": "allow", "install_package": "allow", "file_write": "allow",
"file_delete": "allow", "self_modify": "allow", "create_plugin": "allow",
"restart": "allow", "web_search": "allow", "web_fetch": "allow",
"telegram_auto": "allow", "memory_write": "allow", "schedule": "allow",
},
}
_PERM_LABELS = {
"shell_exec": "Shell commands",
"install_package": "Install packages (pip)",
"file_write": "Write / modify files",
"file_delete": "Delete files",
"self_modify": "Modify own code",
"create_plugin": "Create plugins",
"restart": "Restart AION",
"web_search": "Web search",
"web_fetch": "Fetch URLs",
"telegram_auto": "Send Telegram messages autonomously",
"memory_write": "Write to memory",
"schedule": "Create scheduled tasks",
}
def step7_permissions() -> dict:
section("Permissions — what AION may do autonomously", "Step 7/9:")
print(f" {_c(C_DIM, 'Controls what AION does without asking you first.')}")
print()
preset_name = ["conservative", "balanced", "autonomous"][_select([
"Conservative — asks before anything that touches the system",
"Balanced — search/read/write free, shell/install needs OK (recommended)",
"Autonomous — AION decides everything on its own",
], default=1)]
perms = dict(_PERM_PRESETS[preset_name])
ok(f"Preset '{preset_name}' selected.")
print()
customize = ask("Customize individual permissions? (y/n)", "n")
if customize.lower() == "y":
print()
for key, label in _PERM_LABELS.items():
current = perms[key]
current_display = _c(C_GREEN, "allow") if current == "allow" else \
_c(C_YELLOW, "ask") if current == "ask" else \
_c(C_RED, "deny")
val = ask(f" {label:<42} [{current_display}] (allow/ask/deny)", current).lower()
if val in ("allow", "ask", "deny"):
perms[key] = val
print()
perms["preset"] = preset_name
return perms
# ── Step 8: Advanced Settings ─────────────────────────────────────────────────
def _find_claude_bin() -> "str | None":
"""Sucht die claude CLI — delegiert an config_store.find_claude_bin()."""
from config_store import find_claude_bin
return find_claude_bin()
def _claude_cli_logged_in(claude_bin: str) -> bool:
"""Prüft ob claude CLI angemeldet ist (schneller Test-Aufruf)."""
import subprocess as _sp
try:
r = _sp.run(
[claude_bin, "--print", "--model", "claude-haiku-4-5-20251001", "ping"],
capture_output=True, text=True, timeout=15,
encoding="utf-8", errors="replace",
)
return r.returncode == 0
except Exception:
return False
def step8_advanced(primary_model: str = "") -> dict:
section("Advanced settings", "Step 8/9:")
print(f" {_c(C_DIM, 'Fine-tune AION behavior. All settings can be changed later.')}")
print()
result: dict = {}
# Port
port = ask("Web UI port", "7000")
if port.isdigit() and 1 <= int(port) <= 65535:
result["port"] = port
else:
warn(f"Ungültiger Port '{port}' — verwende Standard 7000.")
result["port"] = "7000"
if result["port"] != "7000":
ok(f"Port set to {result['port']}.")
else: