forked from kortix-ai/suna
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.py
More file actions
1982 lines (1725 loc) · 84.4 KB
/
setup.py
File metadata and controls
1982 lines (1725 loc) · 84.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
import os
import sys
import time
import platform
import subprocess
import re
import json
import secrets
import base64
# --- Constants ---
IS_WINDOWS = platform.system() == "Windows"
PROGRESS_FILE = ".setup_progress"
ENV_DATA_FILE = ".setup_env.json"
# --- ANSI Colors ---
class Colors:
HEADER = "\033[95m"
BLUE = "\033[94m"
CYAN = "\033[96m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
# --- UI Helpers ---
def print_banner():
"""Prints the Kortix Super Worker setup banner."""
print(
f"""
{Colors.BLUE}{Colors.BOLD}
███████╗██╗ ██╗███╗ ██╗ █████╗
██╔════╝██║ ██║████╗ ██║██╔══██╗
███████╗██║ ██║██╔██╗ ██║███████║
╚════██║██║ ██║██║╚██╗██║██╔══██║
███████║╚██████╔╝██║ ╚████║██║ ██║
╚══════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝
Installation Wizard
{Colors.ENDC}
"""
)
def print_step(step_num, total_steps, step_name):
"""Prints a formatted step header."""
print(
f"\n{Colors.BLUE}{Colors.BOLD}Step {step_num}/{total_steps}: {step_name}{Colors.ENDC}"
)
print(f"{Colors.CYAN}{'='*50}{Colors.ENDC}\n")
def print_info(message):
"""Prints an informational message."""
print(f"{Colors.CYAN}ℹ️ {message}{Colors.ENDC}")
def print_success(message):
"""Prints a success message."""
print(f"{Colors.GREEN}✅ {message}{Colors.ENDC}")
def print_warning(message):
"""Prints a warning message."""
print(f"{Colors.YELLOW}⚠️ {message}{Colors.ENDC}")
def print_error(message):
"""Prints an error message."""
print(f"{Colors.RED}❌ {message}{Colors.ENDC}")
def detect_docker_compose_command():
"""Detects whether 'docker compose' or 'docker-compose' is available."""
candidates = [
["docker", "compose"],
["docker-compose"],
]
for cmd in candidates:
try:
subprocess.run(
cmd + ["version"],
capture_output=True,
text=True,
check=True,
shell=IS_WINDOWS,
)
return cmd
except (subprocess.CalledProcessError, FileNotFoundError):
continue
print_error("Docker Compose command not found. Install Docker Desktop or docker-compose.")
return None
def format_compose_cmd(compose_cmd):
"""Formats the compose command list for display."""
return " ".join(compose_cmd) if compose_cmd else "docker compose"
# --- Environment File Parsing ---
def parse_env_file(filepath):
"""Parses a .env file and returns a dictionary of key-value pairs."""
env_vars = {}
if not os.path.exists(filepath):
return env_vars
try:
with open(filepath, "r") as f:
for line in f:
line = line.strip()
# Skip empty lines and comments
if not line or line.startswith("#"):
continue
# Handle key=value pairs
if "=" in line:
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
# Remove quotes if present
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
env_vars[key] = value
except Exception as e:
print_warning(f"Could not parse {filepath}: {e}")
return env_vars
def load_existing_env_vars():
"""Loads existing environment variables from .env files."""
backend_env = parse_env_file(os.path.join("backend", ".env"))
frontend_env = parse_env_file(os.path.join("apps", "frontend", ".env.local"))
# Organize the variables by category
existing_vars = {
"supabase": {
"SUPABASE_URL": backend_env.get("SUPABASE_URL", ""),
"NEXT_PUBLIC_SUPABASE_URL": frontend_env.get("NEXT_PUBLIC_SUPABASE_URL", ""),
"EXPO_PUBLIC_SUPABASE_URL": backend_env.get("EXPO_PUBLIC_SUPABASE_URL", ""),
"SUPABASE_ANON_KEY": backend_env.get("SUPABASE_ANON_KEY", ""),
"SUPABASE_SERVICE_ROLE_KEY": backend_env.get(
"SUPABASE_SERVICE_ROLE_KEY", ""
),
"SUPABASE_JWT_SECRET": backend_env.get("SUPABASE_JWT_SECRET", ""),
},
"daytona": {
"DAYTONA_API_KEY": backend_env.get("DAYTONA_API_KEY", ""),
"DAYTONA_SERVER_URL": backend_env.get("DAYTONA_SERVER_URL", ""),
"DAYTONA_TARGET": backend_env.get("DAYTONA_TARGET", ""),
},
"llm": {
"OPENAI_API_KEY": backend_env.get("OPENAI_API_KEY", ""),
"ANTHROPIC_API_KEY": backend_env.get("ANTHROPIC_API_KEY", ""),
"GROQ_API_KEY": backend_env.get("GROQ_API_KEY", ""),
"OPENROUTER_API_KEY": backend_env.get("OPENROUTER_API_KEY", ""),
"XAI_API_KEY": backend_env.get("XAI_API_KEY", ""),
"MORPH_API_KEY": backend_env.get("MORPH_API_KEY", ""),
"GEMINI_API_KEY": backend_env.get("GEMINI_API_KEY", ""),
"OPENAI_COMPATIBLE_API_KEY": backend_env.get("OPENAI_COMPATIBLE_API_KEY", ""),
"OPENAI_COMPATIBLE_API_BASE": backend_env.get("OPENAI_COMPATIBLE_API_BASE", ""),
"AWS_BEARER_TOKEN_BEDROCK": backend_env.get("AWS_BEARER_TOKEN_BEDROCK", ""),
},
"search": {
"TAVILY_API_KEY": backend_env.get("TAVILY_API_KEY", ""),
"FIRECRAWL_API_KEY": backend_env.get("FIRECRAWL_API_KEY", ""),
"FIRECRAWL_URL": backend_env.get("FIRECRAWL_URL", ""),
"SERPER_API_KEY": backend_env.get("SERPER_API_KEY", ""),
"EXA_API_KEY": backend_env.get("EXA_API_KEY", ""),
"SEMANTIC_SCHOLAR_API_KEY": backend_env.get("SEMANTIC_SCHOLAR_API_KEY", ""),
},
"rapidapi": {
"RAPID_API_KEY": backend_env.get("RAPID_API_KEY", ""),
},
"cron": {
# No secrets required. Make sure pg_cron and pg_net are enabled in Supabase
},
"webhook": {
"WEBHOOK_BASE_URL": backend_env.get("WEBHOOK_BASE_URL", ""),
"TRIGGER_WEBHOOK_SECRET": backend_env.get("TRIGGER_WEBHOOK_SECRET", ""),
},
"mcp": {
"MCP_CREDENTIAL_ENCRYPTION_KEY": backend_env.get(
"MCP_CREDENTIAL_ENCRYPTION_KEY", ""
),
},
"composio": {
"COMPOSIO_API_KEY": backend_env.get("COMPOSIO_API_KEY", ""),
"COMPOSIO_WEBHOOK_SECRET": backend_env.get("COMPOSIO_WEBHOOK_SECRET", ""),
},
"kortix": {
"KORTIX_ADMIN_API_KEY": backend_env.get("KORTIX_ADMIN_API_KEY", ""),
},
"vapi": {
"VAPI_PRIVATE_KEY": backend_env.get("VAPI_PRIVATE_KEY", ""),
"VAPI_PHONE_NUMBER_ID": backend_env.get("VAPI_PHONE_NUMBER_ID", ""),
"VAPI_SERVER_URL": backend_env.get("VAPI_SERVER_URL", ""),
},
"stripe": {
"STRIPE_SECRET_KEY": backend_env.get("STRIPE_SECRET_KEY", ""),
"STRIPE_WEBHOOK_SECRET": backend_env.get("STRIPE_WEBHOOK_SECRET", ""),
},
"langfuse": {
"LANGFUSE_PUBLIC_KEY": backend_env.get("LANGFUSE_PUBLIC_KEY", ""),
"LANGFUSE_SECRET_KEY": backend_env.get("LANGFUSE_SECRET_KEY", ""),
"LANGFUSE_HOST": backend_env.get("LANGFUSE_HOST", ""),
},
"braintrust": {
"BRAINTRUST_API_KEY": backend_env.get("BRAINTRUST_API_KEY", ""),
},
"monitoring": {
"SENTRY_DSN": backend_env.get("SENTRY_DSN", ""),
"FREESTYLE_API_KEY": backend_env.get("FREESTYLE_API_KEY", ""),
"CLOUDFLARE_API_TOKEN": backend_env.get("CLOUDFLARE_API_TOKEN", ""),
},
"storage": {
},
"email": {
},
"frontend": {
"NEXT_PUBLIC_SUPABASE_URL": frontend_env.get(
"NEXT_PUBLIC_SUPABASE_URL", ""
),
"NEXT_PUBLIC_SUPABASE_ANON_KEY": frontend_env.get(
"NEXT_PUBLIC_SUPABASE_ANON_KEY", ""
),
"NEXT_PUBLIC_BACKEND_URL": frontend_env.get("NEXT_PUBLIC_BACKEND_URL", ""),
"NEXT_PUBLIC_URL": frontend_env.get("NEXT_PUBLIC_URL", ""),
"NEXT_PUBLIC_ENV_MODE": frontend_env.get("NEXT_PUBLIC_ENV_MODE", ""),
"NEXT_PUBLIC_POSTHOG_KEY": frontend_env.get("NEXT_PUBLIC_POSTHOG_KEY", ""),
"NEXT_PUBLIC_SENTRY_DSN": frontend_env.get("NEXT_PUBLIC_SENTRY_DSN", ""),
"NEXT_PUBLIC_PHONE_NUMBER_MANDATORY": frontend_env.get("NEXT_PUBLIC_PHONE_NUMBER_MANDATORY", ""),
"NEXT_PUBLIC_APP_URL": frontend_env.get("NEXT_PUBLIC_APP_URL", ""),
},
}
return existing_vars
def mask_sensitive_value(value, show_last=4):
"""Masks sensitive values for display, showing only the last few characters."""
if not value or len(value) <= show_last:
return value
return "*" * (len(value) - show_last) + value[-show_last:]
# --- State Management ---
def save_progress(step, data):
"""Saves the current step and collected data."""
with open(PROGRESS_FILE, "w") as f:
json.dump({"step": step, "data": data}, f)
def load_progress():
"""Loads the last saved step and data."""
if os.path.exists(PROGRESS_FILE):
with open(PROGRESS_FILE, "r") as f:
try:
return json.load(f)
except (json.JSONDecodeError, KeyError):
return {"step": 0, "data": {}}
return {"step": 0, "data": {}}
# --- Validators ---
def validate_url(url, allow_empty=False):
"""Validates a URL format."""
if allow_empty and not url:
return True
pattern = re.compile(
r"^(?:http|https)://"
r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|"
r"localhost|"
r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
r"(?::\d+)?"
r"(?:/?|[/?]\S+)$",
re.IGNORECASE,
)
return bool(pattern.match(url))
def validate_api_key(api_key, allow_empty=False):
"""Performs a basic validation for an API key."""
if allow_empty and not api_key:
return True
return bool(api_key and len(api_key) >= 10)
def generate_encryption_key():
"""Generates a secure base64-encoded encryption key for MCP credentials."""
# Generate 32 random bytes (256 bits)
key_bytes = secrets.token_bytes(32)
# Encode as base64
return base64.b64encode(key_bytes).decode("utf-8")
def generate_admin_api_key():
"""Generates a secure admin API key for Kortix."""
# Generate 32 random bytes and encode as hex for a readable API key
key_bytes = secrets.token_bytes(32)
return key_bytes.hex()
def generate_webhook_secret():
"""Generates a secure shared secret for trigger webhooks."""
# 32 random bytes as hex (64 hex chars)
return secrets.token_hex(32)
# --- Main Setup Class ---
class SetupWizard:
def __init__(self):
progress = load_progress()
self.current_step = progress.get("step", 0)
# Load existing environment variables from .env files
existing_env_vars = load_existing_env_vars()
# Start with existing values, then override with any saved progress
self.env_vars = {
"setup_method": None,
"supabase_setup_method": None,
"supabase": existing_env_vars["supabase"],
"daytona": existing_env_vars["daytona"],
"llm": existing_env_vars["llm"],
"search": existing_env_vars["search"],
"rapidapi": existing_env_vars["rapidapi"],
"cron": existing_env_vars.get("cron", {}),
"webhook": existing_env_vars["webhook"],
"mcp": existing_env_vars["mcp"],
"composio": existing_env_vars["composio"],
"kortix": existing_env_vars["kortix"],
"vapi": existing_env_vars.get("vapi", {}),
"stripe": existing_env_vars.get("stripe", {}),
"langfuse": existing_env_vars.get("langfuse", {}),
"braintrust": existing_env_vars.get("braintrust", {}),
"monitoring": existing_env_vars.get("monitoring", {}),
"storage": existing_env_vars.get("storage", {}),
"email": existing_env_vars.get("email", {}),
}
# Override with any progress data (in case user is resuming)
saved_data = progress.get("data", {})
for key, value in saved_data.items():
if key in self.env_vars and isinstance(value, dict):
self.env_vars[key].update(value)
else:
self.env_vars[key] = value
self.total_steps = 17
self.compose_cmd = None
def get_compose_command(self):
"""Returns the docker compose command list, caching the detection result."""
if self.compose_cmd:
return self.compose_cmd
self.compose_cmd = detect_docker_compose_command()
return self.compose_cmd
def show_current_config(self):
"""Shows the current configuration status."""
config_items = []
# Check Supabase
supabase_complete = (
self.env_vars["supabase"]["SUPABASE_URL"] and
self.env_vars["supabase"]["SUPABASE_ANON_KEY"] and
self.env_vars["supabase"]["SUPABASE_SERVICE_ROLE_KEY"]
)
supabase_secure = self.env_vars["supabase"]["SUPABASE_JWT_SECRET"]
if supabase_complete and supabase_secure:
config_items.append(f"{Colors.GREEN}✓{Colors.ENDC} Supabase (secure)")
elif supabase_complete:
config_items.append(f"{Colors.YELLOW}⚠{Colors.ENDC} Supabase (missing JWT secret)")
else:
config_items.append(f"{Colors.YELLOW}○{Colors.ENDC} Supabase")
# Check Daytona
if self.env_vars["daytona"]["DAYTONA_API_KEY"]:
config_items.append(f"{Colors.GREEN}✓{Colors.ENDC} Daytona")
else:
config_items.append(f"{Colors.YELLOW}○{Colors.ENDC} Daytona")
# Check LLM providers
llm_keys = [
k
for k in self.env_vars["llm"]
if self.env_vars["llm"][k] and k != "MORPH_API_KEY"
]
if llm_keys:
providers = [k.split("_")[0].capitalize() for k in llm_keys]
config_items.append(
f"{Colors.GREEN}✓{Colors.ENDC} LLM ({', '.join(providers)})"
)
else:
config_items.append(f"{Colors.YELLOW}○{Colors.ENDC} LLM providers")
# Check Search APIs
required_search_configured = (
self.env_vars["search"]["TAVILY_API_KEY"]
and self.env_vars["search"]["FIRECRAWL_API_KEY"]
)
optional_search_keys = [
self.env_vars["search"]["SERPER_API_KEY"],
self.env_vars["search"]["EXA_API_KEY"],
self.env_vars["search"]["SEMANTIC_SCHOLAR_API_KEY"],
]
optional_search_count = sum(1 for key in optional_search_keys if key)
if required_search_configured:
if optional_search_count > 0:
config_items.append(f"{Colors.GREEN}✓{Colors.ENDC} Search APIs ({optional_search_count} optional)")
else:
config_items.append(f"{Colors.GREEN}✓{Colors.ENDC} Search APIs")
else:
config_items.append(f"{Colors.YELLOW}○{Colors.ENDC} Search APIs")
# Check RapidAPI (optional)
if self.env_vars["rapidapi"]["RAPID_API_KEY"]:
config_items.append(
f"{Colors.GREEN}✓{Colors.ENDC} RapidAPI (optional)")
else:
config_items.append(
f"{Colors.CYAN}○{Colors.ENDC} RapidAPI (optional)")
# Check Cron/Webhook setup
if self.env_vars["webhook"]["WEBHOOK_BASE_URL"]:
config_items.append(
f"{Colors.GREEN}✓{Colors.ENDC} Supabase Cron & Webhooks")
else:
config_items.append(
f"{Colors.YELLOW}○{Colors.ENDC} Supabase Cron & Webhooks")
# Check MCP encryption key
if self.env_vars["mcp"]["MCP_CREDENTIAL_ENCRYPTION_KEY"]:
config_items.append(
f"{Colors.GREEN}✓{Colors.ENDC} MCP encryption key")
else:
config_items.append(
f"{Colors.YELLOW}○{Colors.ENDC} MCP encryption key")
# Check Composio configuration
if self.env_vars["composio"]["COMPOSIO_API_KEY"]:
config_items.append(
f"{Colors.GREEN}✓{Colors.ENDC} Composio (optional)")
else:
config_items.append(
f"{Colors.CYAN}○{Colors.ENDC} Composio (optional)")
# Check Webhook configuration
if self.env_vars["webhook"]["WEBHOOK_BASE_URL"]:
config_items.append(f"{Colors.GREEN}✓{Colors.ENDC} Webhook")
else:
config_items.append(f"{Colors.YELLOW}○{Colors.ENDC} Webhook")
# Check Morph (optional but recommended)
if self.env_vars["llm"].get("MORPH_API_KEY"):
config_items.append(
f"{Colors.GREEN}✓{Colors.ENDC} Morph (Code Editing)")
elif self.env_vars["llm"].get("OPENROUTER_API_KEY"):
config_items.append(
f"{Colors.CYAN}○{Colors.ENDC} Morph (fallback to OpenRouter)")
else:
config_items.append(
f"{Colors.YELLOW}○{Colors.ENDC} Morph (recommended)")
# Check Kortix configuration
if self.env_vars["kortix"]["KORTIX_ADMIN_API_KEY"]:
config_items.append(f"{Colors.GREEN}✓{Colors.ENDC} Kortix Admin")
else:
config_items.append(f"{Colors.YELLOW}○{Colors.ENDC} Kortix Admin")
if any("✓" in item for item in config_items):
print_info("Current configuration status:")
for item in config_items:
print(f" {item}")
print()
def is_setup_complete(self):
"""Checks if the setup has been completed."""
# Check if essential env files exist and have required keys
try:
# Check backend .env
if not os.path.exists("backend/.env"):
return False
with open("backend/.env", "r") as f:
backend_content = f.read()
if "SUPABASE_URL" not in backend_content or "ENCRYPTION_KEY" not in backend_content:
return False
# Check frontend .env.local
if not os.path.exists("apps/frontend/.env.local"):
return False
with open("apps/frontend/.env.local", "r") as f:
frontend_content = f.read()
if "NEXT_PUBLIC_SUPABASE_URL" not in frontend_content:
return False
return True
except Exception:
return False
def run(self):
"""Runs the setup wizard."""
print_banner()
print(
"This wizard will guide you through setting up Kortix Super Worker, an open-source generalist AI Worker.\n"
)
# Show current configuration status
self.show_current_config()
# Check if setup is already complete
if self.is_setup_complete():
print_info("Setup already complete!")
print_info("Would you like to start Kortix Super Worker?")
print()
print("[1] Start with Docker Compose")
print("[2] Start manually (show commands)")
print("[3] Re-run setup wizard")
print("[4] Exit")
print()
choice = input("Enter your choice (1-4): ").strip()
if choice == "1":
print_info("Starting Kortix Super Worker with Docker Compose...")
self.start_suna()
return
elif choice == "2":
self.final_instructions()
return
elif choice == "3":
print_info("Re-running setup wizard...")
# Delete progress file and reset
if os.path.exists(PROGRESS_FILE):
os.remove(PROGRESS_FILE)
self.env_vars = {}
self.total_steps = 17
self.current_step = 0
# Continue with normal setup
elif choice == "4":
print_info("Exiting...")
return
else:
print_error("Invalid choice. Exiting...")
return
try:
self.run_step(1, self.choose_setup_method)
self.run_step(2, self.check_requirements)
self.run_step(3, self.collect_supabase_info)
self.run_step(4, self.collect_daytona_info)
self.run_step(5, self.collect_llm_api_keys)
# Optional tools - users can skip these
self.run_step_optional(6, self.collect_morph_api_key, "Morph API Key (Optional)")
self.run_step_optional(7, self.collect_search_api_keys, "Search API Keys (Optional)")
self.run_step_optional(8, self.collect_rapidapi_keys, "RapidAPI Keys (Optional)")
self.run_step(9, self.collect_kortix_keys)
# Supabase Cron does not require keys; ensure DB migrations enable cron functions
self.run_step_optional(10, self.collect_webhook_keys, "Webhook Configuration (Optional)")
self.run_step_optional(11, self.collect_mcp_keys, "MCP Configuration (Optional)")
self.run_step_optional(12, self.collect_composio_keys, "Composio Integration (Optional)")
# Removed duplicate webhook collection step
self.run_step(13, self.configure_env_files)
self.run_step(14, self.setup_supabase_database)
self.run_step(15, self.install_dependencies)
self.run_step(16, self.start_suna)
self.final_instructions()
except KeyboardInterrupt:
print("\n\nSetup interrupted. Your progress has been saved.")
print("You can resume setup anytime by running this script again.")
sys.exit(1)
except Exception as e:
print_error(f"An unexpected error occurred: {e}")
print_error(
"Please check the error message and try running the script again."
)
sys.exit(1)
def run_step(self, step_number, step_function, *args, **kwargs):
"""Executes a setup step if it hasn't been completed."""
if self.current_step < step_number:
step_function(*args, **kwargs)
self.current_step = step_number
save_progress(self.current_step, self.env_vars)
def run_step_optional(self, step_number, step_function, step_name, *args, **kwargs):
"""Executes an optional setup step if it hasn't been completed."""
if self.current_step < step_number:
print_info(f"\n--- {step_name} ---")
print_info("This step is OPTIONAL. You can skip it and configure later if needed.")
while True:
choice = input("Do you want to configure this now? (y/n/skip): ").lower().strip()
if choice in ['y', 'yes']:
step_function(*args, **kwargs)
break
elif choice in ['n', 'no', 'skip', '']:
print_info(f"Skipped {step_name}. You can configure this later.")
break
else:
print_warning("Please enter 'y' for yes, 'n' for no, or 'skip' to skip.")
self.current_step = step_number
save_progress(self.current_step, self.env_vars)
def choose_setup_method(self):
"""Asks the user to choose between Docker and manual setup."""
print_step(1, self.total_steps, "Choose Setup Method")
if self.env_vars.get("setup_method"):
print_info(
f"Continuing with '{self.env_vars['setup_method']}' setup method."
)
return
print_info(
"You can start Kortix Super Worker using either Docker Compose or by manually starting the services."
)
# Important note about Supabase compatibility
print(f"\n{Colors.YELLOW}⚠️ IMPORTANT - Supabase Compatibility:{Colors.ENDC}")
print(f" • {Colors.GREEN}Docker Compose{Colors.ENDC} → Only supports {Colors.CYAN}Cloud Supabase{Colors.ENDC}")
print(f" • {Colors.GREEN}Manual Setup{Colors.ENDC} → Supports both {Colors.CYAN}Cloud and Local Supabase{Colors.ENDC}")
print(f"\n Why? Docker networking can't easily reach local Supabase containers.")
print(f" Want to fix this? See: {Colors.CYAN}https://github.com/kortix-ai/suna/issues/1920{Colors.ENDC}")
print(f"\n{Colors.CYAN}How would you like to set up Kortix Super Worker?{Colors.ENDC}")
print(
f"{Colors.CYAN}[1] {Colors.GREEN}Manual{Colors.ENDC} {Colors.CYAN}(supports both Cloud and Local Supabase){Colors.ENDC}"
)
print(
f"{Colors.CYAN}[2] {Colors.GREEN}Docker Compose{Colors.ENDC} {Colors.CYAN}(requires Cloud Supabase){Colors.ENDC}\n"
)
while True:
choice = input("Enter your choice (1 or 2): ").strip()
if choice == "1":
self.env_vars["setup_method"] = "manual"
break
elif choice == "2":
self.env_vars["setup_method"] = "docker"
break
else:
print_error(
"Invalid selection. Please enter '1' for Manual or '2' for Docker."
)
print_success(f"Selected '{self.env_vars['setup_method']}' setup.")
def check_requirements(self):
"""Checks if all required tools for the chosen setup method are installed."""
print_step(2, self.total_steps, "Checking Requirements")
compose_cmd = self.get_compose_command()
compose_cmd_str = format_compose_cmd(compose_cmd) if compose_cmd else "docker compose"
if self.env_vars["setup_method"] == "docker":
requirements = {
"git": "https://git-scm.com/downloads",
"docker": "https://docs.docker.com/get-docker/",
}
else: # manual
requirements = {
"git": "https://git-scm.com/downloads",
"uv": "https://github.com/astral-sh/uv#installation",
"node": "https://nodejs.org/en/download/",
"pnpm": "https://pnpm.io/installation",
"docker": "https://docs.docker.com/get-docker/", # For Redis
}
missing = []
for cmd, url in requirements.items():
try:
cmd_to_check = cmd
# On Windows, python3 is just python
if IS_WINDOWS and cmd in ["python3", "pip3"]:
cmd_to_check = cmd.replace("3", "")
subprocess.run(
[cmd_to_check, "--version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
shell=IS_WINDOWS,
)
print_success(f"{cmd} is installed.")
except (subprocess.SubprocessError, FileNotFoundError):
missing.append((cmd, url))
print_error(f"{cmd} is not installed.")
if missing:
print_error(
"\nMissing required tools. Please install them before continuing:"
)
for cmd, url in missing:
print(f" - {cmd}: {url}")
sys.exit(1)
self.check_docker_running()
self.check_suna_directory()
def check_docker_running(self):
"""Checks if the Docker daemon is running."""
print_info("Checking if Docker is running...")
try:
subprocess.run(
["docker", "info"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True,
shell=IS_WINDOWS,
)
print_success("Docker is running.")
return True
except subprocess.SubprocessError:
print_error(
"Docker is installed but not running. Please start Docker and try again."
)
sys.exit(1)
def check_suna_directory(self):
"""Checks if the script is run from the correct project root directory."""
print_info("Verifying project structure...")
required_dirs = ["backend", "apps/frontend"]
required_files = ["README.md", "docker-compose.yaml"]
for directory in required_dirs:
if not os.path.isdir(directory):
print_error(
f"'{directory}' directory not found. Make sure you're in the Kortix Super Worker repository root."
)
sys.exit(1)
for file in required_files:
if not os.path.isfile(file):
print_error(
f"'{file}' not found. Make sure you're in the Kortix Super Worker repository root."
)
sys.exit(1)
print_success("Kortix Super Worker repository detected.")
return True
def _get_input(
self, prompt, validator, error_message, allow_empty=False, default_value=""
):
"""Helper to get validated user input with optional default value."""
while True:
# Show default value in prompt if it exists
if default_value:
# Mask sensitive values for display
if "key" in prompt.lower() or "token" in prompt.lower():
display_default = mask_sensitive_value(default_value)
else:
display_default = default_value
full_prompt = (
f"{prompt}[{Colors.GREEN}{display_default}{Colors.ENDC}]: "
)
else:
full_prompt = prompt
value = input(full_prompt).strip()
# Use default value if user just pressed Enter
if not value and default_value:
value = default_value
if validator(value, allow_empty=allow_empty):
return value
print_error(error_message)
def collect_supabase_info(self):
"""Collects Supabase project information from the user."""
print_step(3, self.total_steps, "Collecting Supabase Information")
# Always ask user to choose between local and cloud Supabase
print_info("Kortix Super Worker REQUIRES a Supabase project to function. Without these keys, the application will crash on startup.")
print_info("You can choose between:")
print_info(" 1. Local Supabase (automatic setup, recommended for development & local use - runs in Docker)")
print_info(" 2. Cloud Supabase (hosted on supabase.com - requires manual setup)")
while True:
choice = input("Choose your Supabase setup (1 for local, 2 for cloud): ").strip()
if choice == "1":
self.env_vars["supabase_setup_method"] = "local"
break
elif choice == "2":
self.env_vars["supabase_setup_method"] = "cloud"
break
else:
print_error("Please enter 1 for local or 2 for cloud.")
# Handle local Supabase setup
if self.env_vars["supabase_setup_method"] == "local":
self._setup_local_supabase()
else:
self._setup_cloud_supabase()
def _setup_local_supabase(self):
"""Sets up local Supabase using Docker."""
print_info("Setting up local Supabase...")
print_info("This will download and start Supabase using Docker.")
# Check if Docker is available
try:
import subprocess
result = subprocess.run(["docker", "--version"], capture_output=True, text=True)
if result.returncode != 0:
print_error("Docker is not installed or not running. Please install Docker first.")
return
except FileNotFoundError:
print_error("Docker is not installed. Please install Docker first.")
return
# Initialize Supabase project if not already done
supabase_config_path = "backend/supabase/config.toml"
if not os.path.exists(supabase_config_path):
print_info("Initializing Supabase project...")
try:
subprocess.run(
["npx", "supabase", "init"],
cwd="backend",
check=True,
shell=IS_WINDOWS,
)
print_success("Supabase project initialized.")
except subprocess.SubprocessError as e:
print_error(f"Failed to initialize Supabase project: {e}")
return
else:
print_info("Using existing Supabase project configuration.")
# Stop any running Supabase instance first (to ensure config changes are picked up)
print_info("Checking for existing Supabase instance...")
try:
subprocess.run(
["npx", "supabase", "stop"],
cwd="backend",
capture_output=True,
shell=IS_WINDOWS,
)
print_info("Stopped any existing Supabase instance.")
except:
pass # It's OK if stop fails (nothing running)
# Configure local Supabase settings for development
print_info("Configuring Supabase for local development...")
self._configure_local_supabase_settings()
# Start Supabase services using Supabase CLI instead of Docker Compose
print_info("Starting Supabase services using Supabase CLI...")
print_info("This may take a few minutes on first run (downloading Docker images)...")
print_info("Please wait while Supabase starts...\n")
try:
# Run without capturing output so user sees progress in real-time
result = subprocess.run(
["npx", "supabase", "start"],
cwd="backend",
check=True,
text=True,
shell=IS_WINDOWS,
)
print_success("\nSupabase services started successfully!")
# Now run 'supabase status' to get the connection details
print_info("Retrieving connection details...")
status_result = subprocess.run(
["npx", "supabase", "status"],
cwd="backend",
check=True,
capture_output=True,
text=True,
shell=IS_WINDOWS,
)
# Extract keys from the status output
output = status_result.stdout
print_info(f"Parsing Supabase status output...")
for line in output.split('\n'):
line = line.strip()
if 'API URL:' in line:
url = line.split('API URL:')[1].strip()
self.env_vars["supabase"]["SUPABASE_URL"] = url
self.env_vars["supabase"]["NEXT_PUBLIC_SUPABASE_URL"] = url
self.env_vars["supabase"]["EXPO_PUBLIC_SUPABASE_URL"] = url
print_success(f"✓ Found API URL: {url}")
elif 'Publishable key:' in line or 'anon key:' in line:
# Supabase status uses "Publishable key" which is the anon key
anon_key = line.split(':')[1].strip()
self.env_vars["supabase"]["SUPABASE_ANON_KEY"] = anon_key
print_success(f"✓ Found Anon Key: {anon_key[:20]}...")
elif 'Secret key:' in line or 'service_role key:' in line:
# Supabase status uses "Secret key" which is the service role key
service_key = line.split(':')[1].strip()
self.env_vars["supabase"]["SUPABASE_SERVICE_ROLE_KEY"] = service_key
print_success(f"✓ Found Service Role Key: {service_key[:20]}...")
print_success("Supabase keys configured from CLI output!")
except subprocess.SubprocessError as e:
print_error(f"Failed to start Supabase services: {e}")
if hasattr(e, 'stderr') and e.stderr:
print_error(f"Error output: {e.stderr}")
return
# Wait a moment for services to be ready
print_info("Waiting for services to be ready...")
import time
time.sleep(5)
# Set JWT secret (this is usually a fixed value for local development)
self.env_vars["supabase"]["SUPABASE_JWT_SECRET"] = "your-super-secret-jwt-token-with-at-least-32-characters-long"
def _configure_local_supabase_settings(self):
"""Configures local Supabase settings for development (disables email confirmations)."""
config_path = "backend/supabase/config.toml"
if not os.path.exists(config_path):
print_warning("Config file not found, will be created by Supabase CLI.")
return
try:
with open(config_path, "r") as f:
config_content = f.read()
# Replace enable_confirmations = true with enable_confirmations = false
if "enable_confirmations = true" in config_content:
config_content = config_content.replace(
"enable_confirmations = true",
"enable_confirmations = false"
)
with open(config_path, "w") as f:
f.write(config_content)
print_success("Configured local Supabase to disable email confirmations for development.")
elif "enable_confirmations = false" in config_content:
print_info("Email confirmations already disabled in local Supabase config.")
else:
print_warning("Could not find enable_confirmations setting in config.toml")
except Exception as e:
print_warning(f"Could not modify Supabase config: {e}")
print_info("You may need to manually set enable_confirmations = false in backend/supabase/config.toml")
def _setup_cloud_supabase(self):
"""Sets up cloud Supabase configuration."""
print_info("Setting up cloud Supabase...")
print_info("Visit https://supabase.com/dashboard/projects to create one.")
print_info("In your project settings, go to 'API' to find the required information:")
print_info(" - Project URL (at the top)")
print_info(" - anon public key (under 'Project API keys')")
print_info(" - service_role secret key (under 'Project API keys')")
print_info(" - JWT Secret (under 'JWT Settings' - critical for security!)")
input("Press Enter to continue once you have your project details...")
self.env_vars["supabase"]["SUPABASE_URL"] = self._get_input(
"Enter your Supabase Project URL (e.g., https://xyz.supabase.co): ",
validate_url,
"Invalid URL format. Please enter a valid URL.",
)
# Extract and store project reference for CLI operations
match = re.search(r"https://([^.]+)\.supabase\.co", self.env_vars["supabase"]["SUPABASE_URL"])
if match:
project_ref = match.group(1)
self.env_vars["supabase"]["SUPABASE_PROJECT_REF"] = project_ref
print_info(f"Detected project reference: {project_ref}")
else:
# Ask for project reference if URL parsing fails
self.env_vars["supabase"]["SUPABASE_PROJECT_REF"] = self._get_input(
"Enter your Supabase Project Reference (found in project settings): ",
lambda x: len(x) > 5,
"Project reference should be at least 6 characters long.",
)
# Set the public URLs to match the main URL
self.env_vars["supabase"]["NEXT_PUBLIC_SUPABASE_URL"] = self.env_vars["supabase"]["SUPABASE_URL"]
self.env_vars["supabase"]["EXPO_PUBLIC_SUPABASE_URL"] = self.env_vars["supabase"]["SUPABASE_URL"]
self.env_vars["supabase"]["SUPABASE_ANON_KEY"] = self._get_input(
"Enter your Supabase anon key: ",
validate_api_key,