forked from MozgAI/MavKa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·2632 lines (2337 loc) · 110 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·2632 lines (2337 loc) · 110 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
#!/bin/bash
# MavKa 🍃 — Your personal AI assistant in Telegram
# One script. 5 minutes. Pennies a month.
#
# Recommended: bash <(curl -sL https://raw.githubusercontent.com/MozgAI/mavka/main/install.sh)
# Or local: bash install.sh
#
# DO NOT pipe via `curl ... | bash` — this script is interactive (read prompts) and stdin
# piping breaks the prompts. Use process substitution `bash <(curl ...)` instead.
#
# Supports: macOS (Apple Silicon & Intel), Linux (x86_64, ARM)
# Requires: internet connection
set -e
# Helpful Ctrl+C / unexpected-exit message: tell the user the install is partial
# and re-running converges to a good state.
on_interrupt() {
echo ""
echo ""
echo " ⚠ Установка прервана / Installation interrupted."
echo " Просто запусти ту же команду заново — установщик идемпотентен:"
echo " Just run the same command again — the installer is idempotent:"
echo ""
echo " bash <(curl -sL https://raw.githubusercontent.com/MozgAI/mavka/main/install.sh)"
echo ""
exit 130
}
trap on_interrupt INT TERM
# ─── Colors ───────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
PURPLE='\033[0;35m'
WHITE='\033[1;37m'
GREY='\033[0;37m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
# ─── Helpers ──────────────────────────────────────────────────
step() { echo -e "\n${GREEN}▸${NC} ${WHITE}$1${NC}"; }
info() { echo -e " ${DIM}$1${NC}"; }
ok() { echo -e " ${GREEN}✓${NC} ${GREY}$1${NC}"; }
warn() { echo -e " ${YELLOW}⚠${NC} $1"; }
fail() { echo -e "\n${RED}✗ $1${NC}"; exit 1; }
# Unified step header (matches the Python AI-setup style)
TOTAL_STEPS=10
# ─── AI Providers Catalog ──────────────────────────────────────
# Set by select_provider(): PROVIDER_NAME, PROVIDER_LABEL, PROVIDER_URL,
# PROVIDER_VERIFY_URL, PROVIDER_VERIFY_MODEL, PROVIDER_RUN_MODEL,
# PROVIDER_KEY_PREFIX, PROVIDER_PI_NAME, PROVIDER_NOTE.
load_provider() {
case "$1" in
deepseek)
PROVIDER_NAME="deepseek"
PROVIDER_LABEL="DeepSeek"
PROVIDER_URL="platform.deepseek.com"
PROVIDER_VERIFY_URL="https://api.deepseek.com/chat/completions"
PROVIDER_VERIFY_MODEL="deepseek-chat"
PROVIDER_RUN_MODEL="deepseek-v4-flash:off"
PROVIDER_KEY_PREFIX="sk-"
PROVIDER_PI_NAME="deepseek"
PROVIDER_NOTE="Cheapest by far. ~\$2/month for active chat-bot use. \$2 starter credit ≈ 1 month."
;;
openai)
PROVIDER_NAME="openai"
PROVIDER_LABEL="ChatGPT"
PROVIDER_URL="platform.openai.com"
PROVIDER_VERIFY_URL="https://api.openai.com/v1/chat/completions"
PROVIDER_VERIFY_MODEL="gpt-4o-mini"
PROVIDER_RUN_MODEL="gpt-4o-mini"
PROVIDER_KEY_PREFIX="sk-"
PROVIDER_PI_NAME="openai"
PROVIDER_NOTE="GPT-4o-mini. ~\$5/month for active chat-bot use."
;;
anthropic)
PROVIDER_NAME="anthropic"
PROVIDER_LABEL="Opus"
PROVIDER_URL="console.anthropic.com"
PROVIDER_VERIFY_URL="https://api.anthropic.com/v1/messages"
# Verify with Haiku (cheap "hi" probe) but RUN with Opus (flagship)
PROVIDER_VERIFY_MODEL="claude-haiku-4-5"
PROVIDER_RUN_MODEL="claude-opus-4-7"
PROVIDER_KEY_PREFIX="sk-ant-"
PROVIDER_PI_NAME="anthropic"
PROVIDER_NOTE="Claude Opus 4.7 — smartest model on the market. ~\$200–400/month for active use without prompt caching."
;;
kimi)
PROVIDER_NAME="kimi"
PROVIDER_LABEL="Kimi 2.6"
PROVIDER_URL="platform.moonshot.ai"
PROVIDER_VERIFY_URL="https://api.moonshot.ai/v1/chat/completions"
PROVIDER_VERIFY_MODEL="kimi-k2.6"
PROVIDER_RUN_MODEL="kimi-k2.6"
PROVIDER_KEY_PREFIX="sk-"
PROVIDER_PI_NAME="moonshotai"
PROVIDER_NOTE="Moonshot Kimi-K2.6. 262K context, strong on coding. ~\$25–35/month for active chat-bot use."
;;
groq)
PROVIDER_NAME="groq"
PROVIDER_LABEL="Groq"
PROVIDER_URL="console.groq.com"
PROVIDER_VERIFY_URL="https://api.groq.com/openai/v1/chat/completions"
PROVIDER_VERIFY_MODEL="llama-3.3-70b-versatile"
PROVIDER_RUN_MODEL="llama-3.3-70b-versatile"
PROVIDER_KEY_PREFIX="gsk_"
PROVIDER_PI_NAME="groq"
PROVIDER_NOTE="Free tier with daily limits. Fastest inference. \$0/month if you stay within free quota."
;;
esac
}
step_header() {
local idx="$1" # 1-based
local label="$2"
local tag="$3" # required / optional
local filled=$((idx - 1))
local empty=$((TOTAL_STEPS - filled))
local bar=""
local i
for ((i=0; i<filled; i++)); do bar="${bar}█"; done
local dots=""
for ((i=0; i<empty; i++)); do dots="${dots}·"; done
echo ""
echo -e " ${DIM}─────────────────────────────────────────────────${NC}"
echo -e " ${GREEN}${bar}${NC}${DIM}${dots}${NC} ${DIM}step ${idx}/${TOTAL_STEPS}${NC} · ${BOLD}${WHITE}${label}${NC} ${DIM}${tag}${NC}"
echo -e " ${DIM}─────────────────────────────────────────────────${NC}"
echo ""
}
# ─── Detect OS ────────────────────────────────────────────────
detect_os() {
case "$(uname -s)" in
Darwin) OS="mac" ;;
Linux) OS="linux" ;;
*) fail "Unsupported OS: $(uname -s). MavKa supports macOS and Linux." ;;
esac
ARCH="$(uname -m)"
}
# ─── Header ──────────────────────────────────────────────────
show_header() {
clear
echo ""
echo -e "${GREEN}"
echo ' ███╗ ███╗ █████╗ ██╗ ██╗██╗ ██╗ █████╗ '
echo ' ████╗ ████║██╔══██╗██║ ██║██║ ██╔╝██╔══██╗'
echo ' ██╔████╔██║███████║██║ ██║█████╔╝ ███████║'
echo ' ██║╚██╔╝██║██╔══██║╚██╗ ██╔╝██╔═██╗ ██╔══██║'
echo ' ██║ ╚═╝ ██║██║ ██║ ╚████╔╝ ██║ ██╗██║ ██║'
echo ' ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝'
echo -e "${NC}"
echo -e " ${PURPLE}forest ai 🍃 alive 🍃 listening${NC}"
echo ""
echo -e " ${DIM}───────────────────────────────────────────────${NC}"
echo ""
echo -e " ${DIM}Platform: ${OS} (${ARCH}) Home: ~/mavka-bot${NC}"
echo ""
}
# ─── i18n ─────────────────────────────────────────────────────
set_lang() {
case "$1" in
uk)
L_step1="Крок 1: Мова"; L_step2="Крок 2: API ключі"
L_step3="Крок 3: Telegram бот"; L_step4="Крок 4: Особистість"
L_pick_lang="Оберіть мову бота:"
L_get_keys="Отримайте ключі (всі безкоштовні або майже):"
L_deepseek_key="DeepSeek API Key: "; L_groq_key="Groq API Key (голос): "
L_gemini_key="Gemini API Key (фото): "; L_tavily_key="Tavily API Key (пошук): "
L_ds_brain="DeepSeek — мозок MavKa"
L_ds_url="platform.deepseek.com"
L_ds_credit="\$2 стартового кредиту вистачає приблизно на місяць активного використання"
L_ds_signup="Зареєструйся, поповни рахунок на \$2, створи API Key і встав сюди."
L_verifying="Перевіряємо ключ..."
L_ds_works="DeepSeek API ключ працює!"
L_ai_activated="Помічник активовано!"
L_ai_guide="MavKa проведе тебе через решту налаштування."
L_ai_natural="Пиши природно — задавай питання, якщо щось незрозуміло."
L_ai_skip="Пиши 'пропустити' для необов'язкових кроків."
L_optional="(необов'язково — пропустіть для відключення)"; L_required="обов'язкове поле"
L_lbl_lang="Мова"; L_lbl_provider="AI-провайдер"; L_lbl_api_key="API ключ"
L_tag_required="обов'язково"; L_tag_optional="необов'язково"
L_provider_intro="Обери мозок для бота. Можна змінити пізніше."
L_recommended="(рекомендується)"
L_p_deepseek_desc="~\$2/місяць, найдешевший"
L_p_chatgpt_desc="OpenAI, API ключ"
L_p_opus_desc="Anthropic, API ключ"
L_p_kimi_desc="Moonshot, API ключ. Довгий контекст"
L_p_groq_desc="Llama 3.3 70B, безкоштовний тариф з лімітами"
L_brain_of="мозок MavKa"
L_signup_at="Зареєструйся на"; L_create_paste="створи API ключ і встав сюди"
L_key_works="API ключ працює!"
L_create_bot="Створіть бота:"
L_botfather_url="t.me/BotFather"
L_botfather_cmd="/newbot"
L_userid_get="Отримай свій ID:"
L_userid_url="t.me/userinfobot"
L_tg_token="Telegram Bot Token: "; L_tg_id="Ваш Telegram User ID: "
L_bot_name="Ім'я бота [MavKa]: "
L_choose_persona="Оберіть особистість або опишіть свою:"
L_p1="Розумний асистент (за замовчуванням)"; L_p2="Дієтолог та фітнес-тренер"
L_p3="Кухар та підбір рецептів"; L_p4="Мовний репетитор"
L_p5="Свій варіант (опишіть)"; L_describe="Опишіть особистість бота: "
L_ready="Готово до встановлення!"
L_press_enter="Натисніть Enter для продовження (або Ctrl+C для скасування)..."
L_is_ready="MavKa готова!"; L_say_hi="Відкрийте Telegram і напишіть привіт!"
;;
ru)
L_step1="Шаг 1: Язык"; L_step2="Шаг 2: API ключи"
L_step3="Шаг 3: Telegram бот"; L_step4="Шаг 4: Личность"
L_pick_lang="Выберите язык бота:"
L_get_keys="Получите ключи (все бесплатные или почти):"
L_deepseek_key="DeepSeek API Key: "; L_groq_key="Groq API Key (голос): "
L_gemini_key="Gemini API Key (фото): "; L_tavily_key="Tavily API Key (поиск): "
L_ds_brain="DeepSeek — мозг MavKa"
L_ds_url="platform.deepseek.com"
L_ds_credit="\$2 стартового кредита хватает примерно на месяц активного использования"
L_ds_signup="Зарегистрируйся, пополни счёт на \$2, создай API Key и вставь сюда."
L_verifying="Проверяем ключ..."
L_ds_works="DeepSeek API ключ работает!"
L_ai_activated="Помощник активирован!"
L_ai_guide="MavKa проведёт тебя через остальные шаги."
L_ai_natural="Пиши естественно — задавай вопросы, если что-то неясно."
L_ai_skip="Пиши 'пропустить' для необязательных шагов."
L_optional="(необязательно — пропустите для отключения)"; L_required="обязательное поле"
L_lbl_lang="Язык"; L_lbl_provider="AI-провайдер"; L_lbl_api_key="API ключ"
L_tag_required="обязательно"; L_tag_optional="необязательно"
L_provider_intro="Выбери мозг для бота. Можно сменить позже."
L_recommended="(рекомендуется)"
L_p_deepseek_desc="~\$2/месяц, самый дешёвый"
L_p_chatgpt_desc="OpenAI, API ключ"
L_p_opus_desc="Anthropic, API ключ"
L_p_kimi_desc="Moonshot, API ключ. Длинный контекст"
L_p_groq_desc="Llama 3.3 70B, бесплатный тариф с лимитами"
L_brain_of="мозг MavKa"
L_signup_at="Зарегистрируйся на"; L_create_paste="создай API ключ и вставь сюда"
L_key_works="API ключ работает!"
L_create_bot="Создайте бота:"
L_botfather_url="t.me/BotFather"
L_botfather_cmd="/newbot"
L_userid_get="Получи свой ID:"
L_userid_url="t.me/userinfobot"
L_tg_token="Telegram Bot Token: "; L_tg_id="Ваш Telegram User ID: "
L_bot_name="Имя бота [MavKa]: "
L_choose_persona="Выберите личность или опишите свою:"
L_p1="Умный ассистент (по умолчанию)"; L_p2="Диетолог и фитнес-тренер"
L_p3="Повар и подбор рецептов"; L_p4="Языковой репетитор"
L_p5="Свой вариант (опишите)"; L_describe="Опишите личность бота: "
L_ready="Готово к установке!"
L_press_enter="Нажмите Enter для продолжения (или Ctrl+C для отмены)..."
L_is_ready="MavKa готова!"; L_say_hi="Откройте Telegram и напишите привет!"
;;
*)
L_step1="Step 1: Language"; L_step2="Step 2: API Keys"
L_step3="Step 3: Telegram Bot"; L_step4="Step 4: Personality"
L_pick_lang="Choose your bot's language:"
L_get_keys="Get your keys (all free or nearly free):"
L_deepseek_key="DeepSeek API Key: "; L_groq_key="Groq API Key (voice): "
L_gemini_key="Gemini API Key (photos): "; L_tavily_key="Tavily API Key (web search): "
L_ds_brain="DeepSeek — MavKa's brain"
L_ds_url="platform.deepseek.com"
L_ds_credit="\$2 starter credit ≈ 1 month of active chat-bot use"
L_ds_signup="Sign up, top up \$2, create an API key, and paste it here."
L_verifying="Verifying API key..."
L_ds_works="DeepSeek API key works!"
L_ai_activated="AI Assistant activated!"
L_ai_guide="MavKa will now guide you through the rest of setup."
L_ai_natural="Type naturally — ask questions if anything is unclear."
L_ai_skip="Type 'skip' to skip optional steps."
L_optional="(optional — skip to disable)"; L_required="required"
L_lbl_lang="Language"; L_lbl_provider="AI Provider"; L_lbl_api_key="API Key"
L_tag_required="required"; L_tag_optional="optional"
L_provider_intro="Pick the brain that powers your bot. You can switch later."
L_recommended="(recommended)"
L_p_deepseek_desc="~\$2/month, cheapest"
L_p_chatgpt_desc="OpenAI, API key"
L_p_opus_desc="Anthropic, API key"
L_p_kimi_desc="Moonshot, API key. Long-context"
L_p_groq_desc="Llama 3.3 70B, free tier with daily limits"
L_brain_of="MavKa's brain"
L_signup_at="Sign up at"; L_create_paste="create an API key and paste it here"
L_key_works="API key works!"
L_create_bot="Create a bot:"
L_botfather_url="t.me/BotFather"
L_botfather_cmd="/newbot"
L_userid_get="Get your ID:"
L_userid_url="t.me/userinfobot"
L_tg_token="Telegram Bot Token: "; L_tg_id="Your Telegram User ID: "
L_bot_name="Bot name [MavKa]: "
L_choose_persona="Choose a personality or write your own:"
L_p1="Smart assistant (default)"; L_p2="Nutritionist & fitness coach"
L_p3="Chef & recipe finder"; L_p4="Language tutor"
L_p5="Custom (you describe it)"; L_describe="Describe your bot's personality: "
L_ready="Ready to install!"
L_press_enter="Press Enter to continue (or Ctrl+C to cancel)..."
L_is_ready="MavKa is ready!"; L_say_hi="Open Telegram and say hi!"
;;
esac
}
# ─── Collect Info ─────────────────────────────────────────────
collect_info() {
# Step 1: Language (label is universal — "Language" before user has picked a language)
step_header 1 "Language" "required"
echo -e " 🇬🇧 ${WHITE}1${NC} ${DIM}English${NC} 🇺🇦 ${WHITE}2${NC} ${DIM}Українська${NC} 🇩🇪 ${WHITE}3${NC} ${DIM}Deutsch${NC}"
echo -e " 🇫🇷 ${WHITE}4${NC} ${DIM}Français${NC} 🇪🇸 ${WHITE}5${NC} ${DIM}Español${NC} 🇷🇺 ${WHITE}6${NC} ${DIM}Русский${NC}"
echo ""
echo -e " ${DIM}Pick / Оберіть / Choisissez (1–6)${NC}"
read -p " ▸ " LANG_CHOICE
case "${LANG_CHOICE:-1}" in
1) BOT_LANG="en" ;;
2) BOT_LANG="uk" ;;
3) BOT_LANG="de" ;;
4) BOT_LANG="fr" ;;
5) BOT_LANG="es" ;;
6) BOT_LANG="ru" ;;
*) BOT_LANG="en" ;;
esac
set_lang "$BOT_LANG"
# Step 2: AI Provider
step_header 2 "$L_lbl_provider" "$L_tag_required"
echo -e " ${DIM}$L_provider_intro${NC}"
echo ""
echo -e " ${WHITE}1${NC} ${BOLD}DeepSeek${NC} ${DIM}— $L_p_deepseek_desc${NC} ${PURPLE}$L_recommended${NC}"
echo -e " ${WHITE}2${NC} ${BOLD}ChatGPT${NC} ${DIM}— $L_p_chatgpt_desc${NC}"
echo -e " ${WHITE}3${NC} ${BOLD}Opus${NC} ${DIM}— $L_p_opus_desc${NC}"
echo -e " ${WHITE}4${NC} ${BOLD}Kimi 2.6${NC} ${DIM}— $L_p_kimi_desc${NC}"
echo -e " ${WHITE}5${NC} ${BOLD}Groq${NC} ${DIM}— $L_p_groq_desc${NC}"
echo ""
read -p " ▸ " PROV_CHOICE
case "${PROV_CHOICE:-1}" in
1) load_provider "deepseek" ;;
2) load_provider "openai" ;;
3) load_provider "anthropic" ;;
4) load_provider "kimi" ;;
5) load_provider "groq" ;;
*) load_provider "deepseek" ;;
esac
# Step 3: API Key for chosen provider
step_header 3 "${PROVIDER_LABEL} ${L_lbl_api_key}" "$L_tag_required"
echo -e " ${DIM}${PROVIDER_LABEL} — ${L_brain_of} ${NC}🍃${DIM} — ${PURPLE}${PROVIDER_URL}${NC}"
echo -e " ${DIM}${PROVIDER_NOTE}${NC}"
echo ""
while true; do
read -p " ${PROVIDER_LABEL} ${L_lbl_api_key}: " PROVIDER_KEY
[ -n "$PROVIDER_KEY" ] && break
echo -e " ${RED}⚠ ${PROVIDER_LABEL} ${L_lbl_api_key} — $L_required${NC}"
echo -e " ${DIM} ${L_signup_at} ${PROVIDER_URL}, ${L_create_paste}.${NC}"
done
# Verify the key against the chosen provider
info "$L_verifying"
if [ "$PROVIDER_NAME" = "anthropic" ]; then
KEY_CHECK=$(curl -s -o /dev/null -w "%{http_code}" \
-H "x-api-key: $PROVIDER_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d "{\"model\":\"$PROVIDER_VERIFY_MODEL\",\"max_tokens\":1,\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}]}" \
"$PROVIDER_VERIFY_URL" 2>/dev/null)
else
KEY_CHECK=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $PROVIDER_KEY" \
-H "Content-Type: application/json" \
-d "{\"model\":\"$PROVIDER_VERIFY_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":1}" \
"$PROVIDER_VERIFY_URL" 2>/dev/null)
fi
if [ "$KEY_CHECK" = "200" ]; then
ok "${PROVIDER_LABEL} ${L_key_works}"
echo ""
echo -e " ${GREEN}${BOLD} 🍃 $L_ai_activated${NC}"
echo -e " ${DIM} $L_ai_guide${NC}"
echo -e " ${DIM} $L_ai_natural${NC}"
echo -e " ${DIM} $L_ai_skip${NC}"
echo ""
# Launch AI-guided setup
export MAVKA_AI_KEY="$PROVIDER_KEY"
export MAVKA_AI_PROVIDER="$PROVIDER_NAME"
export MAVKA_AI_VERIFY_URL="$PROVIDER_VERIFY_URL"
export MAVKA_AI_MODEL="$PROVIDER_VERIFY_MODEL"
export MAVKA_LANG="$BOT_LANG"
export MAVKA_STEP_OFFSET=3 # language + provider + key
export MAVKA_TOTAL_STEPS=$TOTAL_STEPS
# legacy alias for compatibility within ai_guided_setup
export MAVKA_DS_KEY="$PROVIDER_KEY"
DEEPSEEK_KEY="$PROVIDER_KEY"
ai_guided_setup
else
warn "Could not verify API key (HTTP $KEY_CHECK). Continuing with manual setup..."
DEEPSEEK_KEY="$PROVIDER_KEY"
manual_collect_remaining
fi
}
# ─── AI-Guided Setup ─────────────────────────────────────────
ai_guided_setup() {
CONFIG_FILE="/tmp/mavka-setup-config.json"
AI_SCRIPT="/tmp/mavka-ai-setup.py"
cat > "$AI_SCRIPT" << 'AIEOF'
import json, sys, os, re, subprocess, textwrap
AI_KEY = os.environ.get("MAVKA_AI_KEY", os.environ.get("MAVKA_DS_KEY", ""))
AI_PROVIDER = os.environ.get("MAVKA_AI_PROVIDER", "deepseek")
AI_URL = os.environ.get("MAVKA_AI_VERIFY_URL", "https://api.deepseek.com/chat/completions")
AI_MODEL = os.environ.get("MAVKA_AI_MODEL", "deepseek-chat")
BOT_LANG = os.environ.get("MAVKA_LANG", "en")
STEP_OFFSET = int(os.environ.get("MAVKA_STEP_OFFSET", "0"))
TOTAL_STEPS = int(os.environ.get("MAVKA_TOTAL_STEPS", "7"))
CONFIG_FILE = "/tmp/mavka-setup-config.json"
LANG_NAMES = {"en": "English", "uk": "Ukrainian", "ru": "Russian", "de": "German", "fr": "French", "es": "Spanish"}
lang_name = LANG_NAMES.get(BOT_LANG, "English")
GREEN = "\033[0;32m"
PURPLE = "\033[0;35m"
WHITE = "\033[1;37m"
GREY = "\033[0;37m"
DIM = "\033[2m"
RED = "\033[0;31m"
YELLOW = "\033[0;33m"
ORANGE = "\033[38;5;208m"
NC = "\033[0m"
STEPS = [
("groq_key", "Groq API Key (voice)", False),
("gemini_key", "Gemini API Key (photos)", False),
("tavily_key", "Tavily API Key (search)", False),
("telegram_token", "Telegram Bot Token", True),
("telegram_id", "Telegram User ID", True),
("bot_name", "Bot Name", False),
("persona", "Personality", False),
]
config = {
"groq_key": "", "gemini_key": "", "tavily_key": "",
"telegram_token": "", "telegram_id": "",
"bot_name": "MavKa",
"persona": "a smart, proactive, and friendly AI assistant. You help with any questions: research, writing, planning, coding, analysis. You are knowledgeable, concise, and always honest — if you don't know something, you say so."
}
CYAN = "\033[0;36m"
BOLD = "\033[1m"
LINE_WIDTH = 72 # wrap AI messages at this width
def ai_print(text):
# AI message — leaf on first line, indented green text on continuations.
# Wraps long lines at LINE_WIDTH so output never reaches the screen edge.
print() # gap above the message
paragraphs = [p.strip() for p in text.strip().split("\n") if p.strip()]
first = True
for para in paragraphs:
wrapped = textwrap.wrap(
para, width=LINE_WIDTH,
break_long_words=False, break_on_hyphens=False
) or [""]
for j, line in enumerate(wrapped):
if first and j == 0:
print(f" 🍃 {GREEN}{line}{NC}")
first = False
else:
print(f" {GREEN}{line}{NC}")
def ai_ok(text):
print()
print(f" {GREEN}✓{NC} {WHITE}{text}{NC}")
def ai_skip(text):
print()
print(f" {ORANGE}◌{NC} {ORANGE}{text}{NC}")
def ai_warn(text):
print()
print(f" {RED}⚠{NC} {GREY}{text}{NC}")
def step_header(step_idx, label, required):
# step_idx is 0-based local; convert to global with offset
global_idx = step_idx + STEP_OFFSET + 1 # 1-based for display
filled = global_idx - 1
empty = TOTAL_STEPS - filled
bar = f"{GREEN}{'█' * filled}{NC}{DIM}{'·' * empty}{NC}"
tag = f"{DIM}required{NC}" if required else f"{DIM}optional{NC}"
print()
print(f" {DIM}─────────────────────────────────────────────────{NC}")
print(f" {bar} {DIM}step {global_idx}/{TOTAL_STEPS}{NC} · {BOLD}{WHITE}{label}{NC} {tag}")
print(f" {DIM}─────────────────────────────────────────────────{NC}")
print()
def step_done():
print(f"\n {DIM}─────────────────────────────────────────────────{NC}")
def call_deepseek(messages, retries=3):
"""Call the chosen AI provider for the conversational setup. Name kept for compatibility."""
if AI_PROVIDER == "anthropic":
return _call_anthropic(messages, retries)
return _call_openai_compatible(messages, retries)
def _call_openai_compatible(messages, retries):
"""OpenAI-compatible chat completions: works for DeepSeek, OpenAI, Groq."""
payload = json.dumps({
"model": AI_MODEL,
"messages": messages,
"max_tokens": 400,
"temperature": 0.5
})
for attempt in range(retries):
try:
result = subprocess.run(
["curl", "-s", "-X", "POST", AI_URL,
"-H", f"Authorization: Bearer {AI_KEY}",
"-H", "Content-Type: application/json",
"-d", payload],
capture_output=True, text=True, timeout=30
)
data = json.loads(result.stdout)
return data["choices"][0]["message"]["content"]
except Exception:
if attempt < retries - 1:
import time; time.sleep(2)
return None
def _call_anthropic(messages, retries):
"""Anthropic /v1/messages format — system prompt is separate, no `developer` role."""
sys_msg = ""
convo = []
for m in messages:
if m["role"] == "system":
sys_msg = m["content"]
elif m["role"] in ("user", "assistant"):
convo.append({"role": m["role"], "content": m["content"]})
payload_obj = {
"model": AI_MODEL,
"max_tokens": 400,
"messages": convo,
}
if sys_msg:
payload_obj["system"] = sys_msg
payload = json.dumps(payload_obj)
for attempt in range(retries):
try:
result = subprocess.run(
["curl", "-s", "-X", "POST", AI_URL,
"-H", f"x-api-key: {AI_KEY}",
"-H", "anthropic-version: 2023-06-01",
"-H", "Content-Type: application/json",
"-d", payload],
capture_output=True, text=True, timeout=30
)
data = json.loads(result.stdout)
# Anthropic returns content as a list of blocks
blocks = data.get("content", [])
text = "".join(b.get("text", "") for b in blocks if b.get("type") == "text")
return text or None
except Exception:
if attempt < retries - 1:
import time; time.sleep(2)
return None
def validate_input(field, value):
"""STRICT: only return value if it matches expected key format. No fallback on length."""
v = value.strip()
if not v:
return None
if field == "groq_key":
m = re.search(r'(gsk_[A-Za-z0-9]{20,})', v)
return m.group(1) if m else None
elif field == "gemini_key":
m = re.search(r'(AI[A-Za-z0-9_-]{30,})', v)
return m.group(1) if m else None
elif field == "tavily_key":
# Tavily keys: tvly-XXX (legacy), tvly-dev-XXX, tvly-prod-XXX (current).
# Payload may contain dashes/underscores, so allow them in the token.
m = re.search(r'(tvly-[A-Za-z0-9_-]{10,})', v)
return m.group(1) if m else None
elif field == "telegram_token":
m = re.search(r'(\d{8,}:[A-Za-z0-9_-]{30,})', v)
return m.group(1) if m else None
elif field == "telegram_id":
# Channels and bot accounts can have 13-15 digit IDs, regular users 9-12.
m = re.fullmatch(r'\s*(\d{5,15})\s*\.?', v)
return m.group(1) if m else None
elif field == "bot_name":
# Bot name only accepted if input looks like a name (short, no punctuation marks like ?)
if len(v) <= 30 and "?" not in v and "!" not in v:
return v
return None
elif field == "persona":
return v
return None
SKIP_WORDS = (
"skip", "no", "n", "no thanks", "no thank you", "later", "next", "pass", "not now",
"нет", "не", "ні", "ні дякую", "пропусти", "пропустить", "пропустим", "пропуск", "пропустимо",
"потом", "позже", "пізніше", "пізніш", "не сейчас", "не зараз", "поки ні", "не надо",
"далее", "дальше", "дальній", "наступний", "следующий", "перехід", "переходим", "переходимо",
"не хочу", "не буду", "не треба", "без этого", "обійдусь", "обойдусь",
"-", "",
)
def is_skip(text):
t = text.strip().lower().rstrip(".!?,;:")
if t in SKIP_WORDS:
return True
# also catch phrases that contain a skip cue ("можем потом", "сделаю позже", "let's skip")
skip_cues = ("skip", "потом", "позже", "пізніше", "пропуст", "later", "далее", "дальше", "наступн", "следующ", "не сейчас", "не зараз", "обойд", "обійд", "без этого", "не нужно", "не треба", "без него")
return any(cue in t for cue in skip_cues)
CMD_RE = re.compile(r'\[CMD:(skip|stay|none)\]', re.IGNORECASE)
def split_cmd(reply_text):
"""Extract the [CMD:...] tag from AI reply. Returns (visible_text, cmd) where cmd in {skip, stay, none, ''}"""
if not reply_text:
return "", ""
matches = CMD_RE.findall(reply_text)
cmd = matches[-1].lower() if matches else ""
visible = CMD_RE.sub("", reply_text).strip()
return visible, cmd
SYSTEM_PROMPT = f"""You are MavKa — a setup assistant inside a terminal installer.
You help users set up their personal AI Telegram bot.
LANGUAGE — CRITICAL:
- Detect the language of the user's LATEST message and ALWAYS reply in that exact language.
- Only when there is no user message yet (the very first greeting), use {lang_name}.
- If the user switches language mid-conversation, switch with them on the next reply.
- Never mix languages in one response.
STYLE:
- Concise (1-2 sentences usually).
- NO emojis.
- Professional but warm. Treat the user like a friend who's slightly intimidated by the terminal.
YOUR JOB:
Guide the user through ONE setup step at a time. The installer prepends each turn with a [STEP X] hint telling you what to ask for. You handle the conversation; the installer extracts the actual values from user input.
STEPS:
1. groq_key — Groq API key for voice transcription. OPTIONAL. Free at console.groq.com/keys — sign up, go to API Keys, create one.
2. gemini_key — Google Gemini API key for photo analysis. OPTIONAL. Free at aistudio.google.com/apikey — click "Create API key".
3. tavily_key — Tavily API key for web search. OPTIONAL. Free at app.tavily.com/home — sign up, copy key from dashboard.
4. telegram_token — Telegram Bot Token. REQUIRED. How to get it: open Telegram, search for @BotFather, send /newbot, choose a name and username, copy the token (format: 1234567890:AAH...).
5. telegram_id — Telegram numeric user ID. REQUIRED. How to get it: open Telegram, search for @userinfobot, send /start, copy the number.
6. bot_name — Name for the bot. Default: MavKa.
7. persona — Bot personality. ASK FREEFORM, not a numbered menu. Phrase it like: "What role do you want me to play? Describe me — your assistant for what? E.g. 'Be my personal coach', 'Help me with English and recipes', 'Be a study buddy for my kid'. Whatever you write becomes my personality." Accept ANY description ≥ 10 chars as the answer. The bot will save the user's reply directly as its persona. If the user writes something very short (≤9 chars) or asks a question, ask them to elaborate.
CONVERSATION RULES — VERY IMPORTANT:
- The installer (not you) decides when to advance. You signal intent via a control tag at the end of every reply.
- ALWAYS finish every reply with a single control tag on its own line — the installer hides it from the user. Choose ONE:
[CMD:skip] — the user wants to skip this step (clearly: "пропусти", "later", "next", "ну", "давай", "пошли дальше", typos in any layout, gibberish like "lfdfq ghjgrecnbv" if it semantically means "go ahead").
For REQUIRED steps, ONLY emit [CMD:skip] for telegram_token / telegram_id if the user explicitly insists they don't want to set it up at all (rare). Normally for required steps emit [CMD:stay].
[CMD:stay] — the user is asking a question, chatting, confused, or hasn't given a clear answer yet. Stay on this step, no skip.
[CMD:none] — the user pasted what looks like the actual value (key/token/ID/name/persona). The installer will validate the format itself.
- Read the user's intent carefully. If they say anything that means "yes go on / let's skip / move on / next / not now / I don't have it / fine without it / lfdfq" → emit [CMD:skip].
- If they say something like "wait / I have a question / how do I get this / what does it do" → emit [CMD:stay].
- DO NOT narrate "переходим к следующему шагу" in your visible reply — just acknowledge briefly ("Окей, пропускаем" or "Хорошо") and let the installer show the next header.
- For REQUIRED steps (telegram_token, telegram_id), even if the user says skip, emit [CMD:stay] and gently walk them through getting the value, unless they REPEATEDLY refuse — only then [CMD:skip].
- If user pastes a long string that may be the actual value, emit [CMD:none] — let the installer's regex decide.
- If user's reply is empty or ambiguous, emit [CMD:stay] and ask a clarifying question.
- NO emojis ever in your visible reply.
- NEVER output CONFIG lines.
"""
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
step_idx = 0
while step_idx < len(STEPS):
field, label, required = STEPS[step_idx]
step_header(step_idx, label, required)
step_msg = f"[STEP {step_idx+1}] Ask the user for: {label}."
if required:
step_msg += " This is REQUIRED — help them get it if they don't have it."
else:
step_msg += " This is optional — they can skip it."
if step_idx == 0:
step_msg = f"Greet the user warmly! Their DeepSeek key is set up. Now: {step_msg}"
messages.append({"role": "user", "content": step_msg})
response = call_deepseek(messages)
if not response:
ai_warn("Connection issue, retrying...")
messages.pop()
continue
messages.append({"role": "assistant", "content": response})
visible, _ = split_cmd(response) # first AI greeting — no cmd expected
ai_print(visible if visible else response)
while True:
print()
print() # extra gap between AI message and user prompt
try:
user_input = input(f" 🕊️ {WHITE}")
except (EOFError, KeyboardInterrupt):
print()
ai_print("Setup cancelled. Run 'bash install.sh' to start again.")
sys.exit(1)
# 1. Try to extract a valid value via regex first — fast path, no API call
extracted = validate_input(field, user_input) if field not in ("persona", "bot_name") else None
if extracted:
config[field] = extracted
display_val = extracted[:8] + "•••" if len(extracted) > 12 else extracted
ai_ok(f"{label}: {display_val}")
step_idx += 1
break
# 2. Local skip detection (covers obvious cases without API call)
if is_skip(user_input):
if required:
ai_warn(f"{label} is required and cannot be skipped.")
messages.append({"role": "user", "content": "I want to skip this"})
resp = call_deepseek(messages)
if resp:
messages.append({"role": "assistant", "content": resp})
visible, _ = split_cmd(resp)
ai_print(visible if visible else resp)
continue
else:
config[field] = ""
ai_skip(f"{label} — skipped")
step_idx += 1
break
choice = user_input.strip()
# Persona — accept any non-trivial freeform description as the answer.
# The user's own words become the bot's personality, no menu, no presets.
# Short replies (≤9 chars) or questions fall through to AI for clarification.
if field == "persona":
is_question = "?" in choice or choice.lower().startswith((
"how", "what", "why", "where", "can ", "could ",
"как", "что", "почему", "где", "можешь",
"як", "що", "чому", "де"
))
if not is_question and len(choice) >= 10:
config["persona"] = choice
ai_ok("Personality set!")
step_idx += 1
break
# Ask the AI to interpret intent for everything we couldn't classify locally
messages.append({"role": "user", "content": user_input})
resp = call_deepseek(messages)
if not resp:
ai_warn("Connection issue, retrying...")
messages.pop()
continue
messages.append({"role": "assistant", "content": resp})
visible, cmd = split_cmd(resp)
ai_print(visible if visible else resp)
if cmd == "skip":
if required:
# Required step — reinforce, but stay (don't advance)
continue
config[field] = ""
ai_skip(f"{label} — skipped")
step_idx += 1
break
if cmd == "none":
# AI thinks user provided a value. Try field-specific extraction.
if field == "bot_name" and 1 <= len(choice) <= 30:
config["bot_name"] = choice
ai_ok(f"Bot name: {choice}")
step_idx += 1
break
if field == "persona" and len(choice) >= 15:
config["persona"] = choice
ai_ok("Personality set!")
step_idx += 1
break
extracted = validate_input(field, user_input)
if extracted:
config[field] = extracted
display_val = extracted[:8] + "•••" if len(extracted) > 12 else extracted
ai_ok(f"{label}: {display_val}")
step_idx += 1
break
# Couldn't validate — stay, AI's reply already informed the user.
print()
print(f" {GREEN}{'█' * TOTAL_STEPS}{NC} {DIM}{TOTAL_STEPS}/{TOTAL_STEPS} all steps done{NC}")
print(f" {DIM}─────────────────────────────────────────────────{NC}")
with open(CONFIG_FILE, "w") as f:
json.dump(config, f)
print()
ai_print("Setup complete! Installing your bot now... 🍃")
print()
AIEOF
python3 "$AI_SCRIPT"
rm -f "$AI_SCRIPT"
# Read config from AI session
if [ -f "$CONFIG_FILE" ]; then
GROQ_KEY=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('groq_key',''))" 2>/dev/null)
GEMINI_KEY=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('gemini_key',''))" 2>/dev/null)
TAVILY_KEY=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('tavily_key',''))" 2>/dev/null)
TG_TOKEN=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('telegram_token',''))" 2>/dev/null)
TG_USER_ID=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('telegram_id',''))" 2>/dev/null)
BOT_NAME=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('bot_name','MavKa'))" 2>/dev/null)
PERSONA=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('persona','a smart, proactive, and friendly AI assistant.'))" 2>/dev/null)
rm -f "$CONFIG_FILE"
fi
# Validate required fields — fallback to manual if AI missed them
if [ -z "$TG_TOKEN" ]; then
echo -e " ${RED}⚠ Telegram Bot Token is still needed.${NC}"
while true; do
read -p " Telegram Bot Token: " TG_TOKEN
[ -n "$TG_TOKEN" ] && break
echo -e " ${DIM} $L_create_bot ${NC}${PURPLE}$L_botfather_url${NC} ${DIM}→ $L_botfather_cmd${NC}"
done
fi
if [ -z "$TG_USER_ID" ]; then
echo -e " ${RED}⚠ Telegram User ID is still needed.${NC}"
while true; do
read -p " Your Telegram User ID: " TG_USER_ID
[ -n "$TG_USER_ID" ] && break
echo -e " ${DIM} $L_userid_get ${NC}${PURPLE}$L_userid_url${NC}"
done
fi
}
# ─── Manual Fallback (if DeepSeek key fails) ─────────────────
manual_collect_remaining() {
read -p " $L_groq_key" GROQ_KEY
echo -e " ${DIM}$L_optional${NC}"
read -p " $L_gemini_key" GEMINI_KEY
echo -e " ${DIM}$L_optional${NC}"
read -p " $L_tavily_key" TAVILY_KEY
echo -e " ${DIM}$L_optional${NC}"
echo ""
echo -e "${GREEN}${BOLD} $L_step3${NC}"
echo -e " ${DIM}$L_create_bot${NC} ${PURPLE}$L_botfather_url${NC} ${DIM}→ $L_botfather_cmd${NC}"
echo ""
while true; do
read -p " $L_tg_token" TG_TOKEN
[ -n "$TG_TOKEN" ] && break
echo -e " ${RED}⚠ Telegram Bot Token — $L_required${NC}"
echo -e " ${DIM} Create one: t.me/BotFather → /newbot${NC}"
done
while true; do
read -p " $L_tg_id" TG_USER_ID
[ -n "$TG_USER_ID" ] && break
echo -e " ${RED}⚠ Telegram User ID — $L_required${NC}"
echo -e " ${DIM} Get it: t.me/userinfobot${NC}"
done
echo ""
echo -e "${GREEN}${BOLD} $L_step4${NC}"
echo ""
read -p " $L_bot_name" BOT_NAME
BOT_NAME="${BOT_NAME:-MavKa}"
echo ""
echo -e " ${DIM}$L_choose_persona${NC}"
echo -e " ${DIM} 1) $L_p1${NC}"
echo -e " ${DIM} 2) $L_p2${NC}"
echo -e " ${DIM} 3) $L_p3${NC}"
echo -e " ${DIM} 4) $L_p4${NC}"
echo -e " ${DIM} 5) $L_p5${NC}"
echo ""
read -p " Choice [1]: " PERSONA_CHOICE
PERSONA_CHOICE="${PERSONA_CHOICE:-1}"
case "$PERSONA_CHOICE" in
1) PERSONA="a smart, proactive, and friendly AI assistant. You help with any questions: research, writing, planning, coding, analysis. You are knowledgeable, concise, and always honest — if you don't know something, you say so." ;;
2) PERSONA="an expert nutritionist and fitness coach. You analyze meals (including from photos), count calories, create meal plans and workout routines. You are motivating, supportive, and science-based." ;;
3) PERSONA="a professional chef and recipe expert. You suggest recipes based on available ingredients, dietary restrictions, and preferences. You explain techniques clearly and make cooking fun." ;;
4) PERSONA="a patient and encouraging language tutor. You help learn new languages through conversation, correct mistakes gently, explain grammar, and adapt to the learner's level." ;;
5) read -p " $L_describe" PERSONA
[ -z "$PERSONA" ] && PERSONA="a smart, proactive, and friendly AI assistant." ;;
*) PERSONA="a smart, proactive, and friendly AI assistant." ;;
esac
echo ""
echo -e "${GREEN}${BOLD} $L_ready${NC}"
echo -e " ${DIM}Bot: ${BOT_NAME} | Lang: ${BOT_LANG} | Platform: ${OS}${NC}"
echo ""
read -p " $L_press_enter"
}
# ─── Install Dependencies ────────────────────────────────────
install_deps() {
step "Installing dependencies..."
# Node.js via nvm
if ! command -v node &>/dev/null; then
info "Installing Node.js via nvm..."
curl -so- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash 2>/dev/null
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
nvm install 22 2>/dev/null
ok "Node.js $(node -v) installed"
else
ok "Node.js $(node -v) found"
fi
# Python3
if ! command -v python3 &>/dev/null; then
if [ "$OS" = "mac" ]; then
info "Installing Python3..."
if command -v brew &>/dev/null; then
brew install python3 --quiet
else
fail "Python3 not found. Install it: https://python.org/downloads"
fi
else
info "Installing Python3..."
sudo apt-get install -y python3 python3-pip 2>/dev/null || \
sudo yum install -y python3 python3-pip 2>/dev/null || \
fail "Could not install Python3. Install manually."
fi
ok "Python3 installed"
else
ok "Python3 found"
fi
# tmux or screen (Pi Agent needs TTY)
if command -v tmux &>/dev/null; then
ok "tmux found"
elif command -v screen &>/dev/null; then
ok "screen found"
else
if [ "$OS" = "linux" ]; then
info "Installing tmux..."
sudo apt-get install -y tmux 2>/dev/null || sudo yum install -y tmux 2>/dev/null || \
sudo pacman -S --noconfirm tmux 2>/dev/null || true
elif [ "$OS" = "mac" ]; then
# On a fresh Mac brew may not be installed yet — install it non-interactively
if ! command -v brew &>/dev/null; then
info "Installing Homebrew (one-time, ~1 minute)..."
NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" </dev/null 2>/dev/null || true
# Add brew to PATH for this session
if [ -x /opt/homebrew/bin/brew ]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -x /usr/local/bin/brew ]; then
eval "$(/usr/local/bin/brew shellenv)"
fi
fi
command -v brew &>/dev/null && brew install tmux --quiet 2>/dev/null || true
fi
if command -v tmux &>/dev/null; then
ok "tmux installed"
elif command -v screen &>/dev/null; then
ok "screen found (fallback)"
else
warn "Neither tmux nor screen found — bot will run via nohup fallback."
fi
fi
# Pi Agent
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
if command -v pi &>/dev/null; then
ok "Pi Agent found"
else
info "Installing Pi Agent..."
npm install -g @mariozechner/pi-coding-agent 2>/dev/null
ok "Pi Agent installed"
fi
# Python packages
info "Installing Python packages..."
if pip3 install --user edge-tts duckduckgo-search aiohttp --quiet 2>/dev/null || \
pip3 install --user --break-system-packages edge-tts duckduckgo-search aiohttp --quiet 2>/dev/null || \
python3 -m pip install --user edge-tts duckduckgo-search aiohttp --quiet 2>/dev/null || \
python3 -m pip install --user --break-system-packages edge-tts duckduckgo-search aiohttp --quiet 2>/dev/null; then
ok "Python packages installed"
else
warn "Some Python packages failed. Install manually: pip3 install --user edge-tts duckduckgo-search aiohttp"
fi
}