-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·575 lines (462 loc) · 20.2 KB
/
Copy pathsetup.py
File metadata and controls
executable file
·575 lines (462 loc) · 20.2 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
#!/usr/bin/env python3
"""
0pnMatrx — Interactive First-Boot Setup
Guides you through configuring 0pnMatrx on your machine.
Run once after cloning:
python setup.py
Creates openmatrix.config.json with your settings, installs
dependencies, verifies connectivity, and boots the platform.
"""
import json
import os
import subprocess
import sys
import time
from pathlib import Path
# ─── ANSI Colors ─────────────────────────────────────────────────────────────
BOLD = "\033[1m"
DIM = "\033[2m"
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RED = "\033[31m"
MAGENTA = "\033[35m"
RESET = "\033[0m"
CLEAR_LINE = "\033[2K"
def banner():
art = [
" ██████╗ ██████╗ ███╗ ██╗ ███╗ ███╗ █████╗ ████████╗██████╗ ██╗ ██╗",
"██╔═████╗██╔══██╗████╗ ██║ ████╗ ████║██╔══██╗╚══██╔══╝██╔══██╗╚██╗██╔╝",
"██║██╔██║██████╔╝██╔██╗ ██║ ██╔████╔██║███████║ ██║ ██████╔╝ ╚███╔╝ ",
"████╔╝██║██╔═══╝ ██║╚██╗██║ ██║╚██╔╝██║██╔══██║ ██║ ██╔══██╗ ██╔██╗ ",
"╚██████╔╝██║ ██║ ╚████║ ██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║██╔╝ ██╗",
" ╚═════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝",
]
w = max(len(line) for line in art)
art = [line.ljust(w) for line in art]
inner = w + 4
hr = "═" * inner
pad = " " * inner
wel = "Welcome to the Matrix".center(inner)
rows = "\n".join(f" ║{line.center(inner)}║" for line in art)
print(f"""
{CYAN}{BOLD} ╔{hr}╗
║{pad}║
{rows}
║{pad}║
║{wel}║
║{pad}║
╚{hr}╝
{RESET}""")
def step(num, total, text):
print(f"\n{CYAN}{BOLD}[{num}/{total}]{RESET} {BOLD}{text}{RESET}")
print(f"{DIM}{'─' * 60}{RESET}")
def ask(prompt, default="", secret=False, required=False, options=None):
"""Interactive prompt with default values and validation."""
suffix = ""
if options:
suffix = f" ({'/'.join(options)})"
elif default:
suffix = f" [{default}]"
while True:
if secret:
import getpass
value = getpass.getpass(f" {YELLOW}>{RESET} {prompt}{suffix}: ")
else:
value = input(f" {YELLOW}>{RESET} {prompt}{suffix}: ").strip()
if not value and default:
return default
if not value and required:
print(f" {RED}This field is required.{RESET}")
continue
if options and value.lower() not in [o.lower() for o in options]:
print(f" {RED}Choose one of: {', '.join(options)}{RESET}")
continue
return value
def success(text):
print(f" {GREEN}✓{RESET} {text}")
def warn(text):
print(f" {YELLOW}!{RESET} {text}")
def fail(text):
print(f" {RED}✗{RESET} {text}")
def info(text):
print(f" {DIM}{text}{RESET}")
def spinner(text, duration=1.0):
"""Simple progress indicator."""
frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
end_time = time.time() + duration
i = 0
while time.time() < end_time:
print(f"\r {CYAN}{frames[i % len(frames)]}{RESET} {text}", end="", flush=True)
time.sleep(0.08)
i += 1
print(f"\r{CLEAR_LINE}", end="")
# ─── Setup Steps ─────────────────────────────────────────────────────────────
def check_python():
"""Verify Python version.
If the running interpreter is too old but a suitable venv exists in
the project directory, restart under that venv automatically so
users who cloned the repo on a system with an older global Python
aren't blocked.
"""
v = sys.version_info
if v.major >= 3 and v.minor >= 10:
success(f"Python {v.major}.{v.minor}.{v.micro}")
return
# The running Python is too old — check for a usable venv before
# giving up.
venv_python = Path(__file__).parent / ".venv" / "bin" / "python3"
if venv_python.exists():
warn(f"System Python is {v.major}.{v.minor}.{v.micro}, but .venv has a newer version.")
info("Restarting setup under .venv/bin/python3 …")
os.execv(str(venv_python), [str(venv_python)] + sys.argv)
# execv replaces the process; this line is never reached.
fail(f"Python 3.10+ required. You have {v.major}.{v.minor}.{v.micro}")
info("Create a venv with a newer Python, or install Python 3.10+:")
info(" python3.12 -m venv .venv && source .venv/bin/activate && python setup.py")
sys.exit(1)
def install_dependencies():
"""Install Python packages."""
spinner("Installing dependencies...")
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", "requirements.txt", "-q"],
capture_output=True, text=True,
)
if result.returncode != 0:
fail("Dependency installation failed")
print(f" {DIM}{result.stderr[:500]}{RESET}")
return False
# Install optional but recommended packages
subprocess.run(
[sys.executable, "-m", "pip", "install", "pytest", "pytest-asyncio", "-q"],
capture_output=True, text=True,
)
success("All dependencies installed")
return True
def configure_model(config):
"""Set up AI model provider."""
print(f"""
{BOLD}Which AI model provider do you want to use?{RESET}
{CYAN}1{RESET} Ollama {DIM}(free, local, private — recommended for getting started){RESET}
{CYAN}2{RESET} Anthropic {DIM}(best quality){RESET}
{CYAN}3{RESET} OpenAI {DIM}(GPT models){RESET}
{CYAN}4{RESET} NVIDIA {DIM}(NVIDIA AI endpoints){RESET}
{CYAN}5{RESET} Google {DIM}(Gemini models){RESET}
""")
choice = ask("Choose provider", default="1", options=["1", "2", "3", "4", "5"])
providers = {
"1": ("ollama", "llama3.1:8b"),
"2": ("anthropic", "claude-sonnet-4-20250514"),
"3": ("openai", "gpt-4o"),
"4": ("nvidia", "meta/llama-3.1-70b-instruct"),
"5": ("gemini", "gemini-pro"),
}
provider, default_model = providers[choice]
config["model"] = {"provider": provider, "primary": default_model}
if provider == "ollama":
host = ask("Ollama host", default="http://localhost:11434")
model = ask("Ollama model", default=default_model)
config["model"]["ollama"] = {"host": host, "model": model}
info("Make sure Ollama is running: ollama serve")
info(f"Pull the model if needed: ollama pull {model}")
elif provider == "anthropic":
key = ask("Anthropic API key", secret=True, required=True)
model = ask("Model", default=default_model)
config["model"]["anthropic"] = {"api_key": key, "model": model}
elif provider == "openai":
key = ask("OpenAI API key", secret=True, required=True)
model = ask("Model", default=default_model)
config["model"]["openai"] = {"api_key": key, "model": model}
elif provider == "nvidia":
key = ask("NVIDIA API key", secret=True, required=True)
model = ask("Model", default=default_model)
config["model"]["nvidia"] = {"api_key": key, "model": model}
elif provider == "gemini":
key = ask("Google API key", secret=True, required=True)
model = ask("Model", default=default_model)
config["model"]["gemini"] = {"api_key": key, "model": model}
success(f"Model provider: {provider} ({config['model'].get(provider, {}).get('model', default_model)})")
def configure_blockchain(config):
"""Set up blockchain connection."""
print(f"""
{BOLD}Blockchain Network{RESET}
0pnMatrx runs on Base (Ethereum L2). Choose your network:
{CYAN}1{RESET} Base Sepolia {DIM}(testnet — free, for development){RESET}
{CYAN}2{RESET} Base Mainnet {DIM}(real money — for production){RESET}
{CYAN}3{RESET} Skip {DIM}(configure blockchain later){RESET}
""")
choice = ask("Choose network", default="1", options=["1", "2", "3"])
if choice == "3":
config["blockchain"] = {"enabled": False}
warn("Blockchain skipped. Some features will be unavailable.")
return
networks = {
"1": {
"network": "base-sepolia",
"chain_id": 84532,
"rpc_url": "https://sepolia.base.org",
},
"2": {
"network": "base",
"chain_id": 8453,
"rpc_url": "https://mainnet.base.org",
},
}
net = networks[choice]
rpc = ask("RPC URL", default=net["rpc_url"])
net["rpc_url"] = rpc
wallet = ask("Platform wallet address (optional, press Enter to skip)")
if wallet:
net["platform_wallet"] = wallet
private_key = ""
if wallet:
private_key = ask("Wallet private key (for signing transactions)", secret=True)
if private_key:
net["platform_wallet_private_key"] = private_key
config["blockchain"] = net
config["blockchain"]["enabled"] = True
success(f"Network: {net['network']} (chain {net['chain_id']})")
def configure_agents(config):
"""Set up agent configuration."""
print(f"""
{BOLD}Agent Configuration{RESET}
0pnMatrx has three agents:
• {CYAN}Trinity{RESET} — your AI assistant (user-facing)
• {CYAN}Neo{RESET} — the execution engine (backend)
• {CYAN}Morpheus{RESET} — the guardian (safety & guidance)
""")
config["agents"] = {
"neo": {"enabled": True},
"trinity": {"enabled": True},
"morpheus": {"enabled": True},
}
disable = ask("Disable any agents? (comma-separated, or Enter for all)", default="")
if disable:
for name in disable.split(","):
name = name.strip().lower()
if name in config["agents"]:
config["agents"][name]["enabled"] = False
warn(f"{name} disabled")
success("Agents configured")
def configure_gateway(config):
"""Set up gateway server."""
port = ask("Gateway port", default="18790")
api_key = ask("API key for gateway auth (Enter to auto-generate, 'none' to disable)")
if api_key.lower() == "none":
api_key = ""
warn("Gateway authentication disabled. Not recommended for production.")
elif not api_key:
import secrets
api_key = f"omx_{secrets.token_hex(24)}"
success(f"Generated API key: {BOLD}{api_key}{RESET}")
info("Save this key — you'll need it to call the API.")
config["gateway"] = {
"port": int(port),
"host": "0.0.0.0",
"cors_origins": ["*"],
"api_key": api_key,
"rate_limit_rpm": 60,
"rate_limit_burst": 15,
}
success(f"Gateway: http://localhost:{port}")
def configure_security(config):
"""Set up security settings."""
config["security"] = {
"block_on_critical": True,
"block_on_high": False,
}
block_high = ask("Block deployment on HIGH severity audit findings too?", default="no", options=["yes", "no"])
if block_high.lower() == "yes":
config["security"]["block_on_high"] = True
success("Blocking on CRITICAL + HIGH findings")
else:
success("Blocking on CRITICAL findings only")
def configure_communications(config):
"""Set up notification / communication channels.
Delegates each channel to its dedicated configurator in ``setup/``. All
nine channels (Telegram, Discord, Slack, Email, SMS, WhatsApp, Web chat,
iOS push, Webhook) can be added here at first boot — and any of them
can be added or updated later with:
python setup_communications.py
"""
print(f"""
{BOLD}How should 0pnMatrx reach you?{RESET}
{DIM}You can enable any combination of channels. Everything is optional.{RESET}
{DIM}Rerun `python setup_communications.py` anytime to add more.{RESET}
""")
# Lazy imports so this works even before the repo is fully installed.
from setup import telegram as cfg_telegram
from setup import discord as cfg_discord
from setup import slack as cfg_slack
from setup import email as cfg_email
from setup import sms as cfg_sms
from setup import whatsapp as cfg_whatsapp
from setup import web_chat as cfg_web
from setup import ios_push as cfg_ios
from setup import webhook as cfg_webhook
prompts = [
("Telegram", "yes", cfg_telegram.configure),
("Discord", "no", cfg_discord.configure),
("Slack", "no", cfg_slack.configure),
("Email", "no", cfg_email.configure),
("SMS", "no", cfg_sms.configure),
("WhatsApp", "no", cfg_whatsapp.configure),
("Web chat", "yes", cfg_web.configure),
("iOS push", "no", cfg_ios.configure),
("Webhook", "no", cfg_webhook.configure),
]
for label, default, fn in prompts:
pick = ask(f"Configure {label}?", default=default, options=["yes", "no"])
if pick.lower().startswith("y"):
try:
fn(config)
except KeyboardInterrupt:
info("Skipped.")
except Exception as exc:
info(f"{label} setup failed ({exc}); continuing.")
# Ensure the unified "notifications" block exists even if empty.
config.setdefault("notifications", {})
if not config["notifications"]:
info("No channels configured. Add them later with: python setup_communications.py")
def configure_extras(config):
"""Optional extras: timezone, memory."""
tz = ask("Timezone", default="America/Los_Angeles")
config["timezone"] = tz
config["memory"] = {"max_turns": 200}
config["max_steps"] = 10
success(f"Timezone: {tz}")
def verify_setup(config):
"""Verify the setup works."""
spinner("Verifying configuration...")
# Check config is valid JSON
try:
json.dumps(config)
success("Configuration is valid")
except Exception as e:
fail(f"Config validation failed: {e}")
return False
# Check model provider connectivity
provider = config.get("model", {}).get("provider", "ollama")
if provider == "ollama":
host = config.get("model", {}).get("ollama", {}).get("host", "http://localhost:11434")
try:
import urllib.request
req = urllib.request.urlopen(f"{host}/api/tags", timeout=5)
if req.status == 200:
success(f"Ollama connected at {host}")
else:
warn(f"Ollama returned status {req.status}")
except Exception:
warn(f"Cannot reach Ollama at {host}. Start it with: ollama serve")
# Check blockchain RPC
if config.get("blockchain", {}).get("enabled"):
rpc = config["blockchain"].get("rpc_url", "")
try:
import urllib.request
body = json.dumps({"jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1}).encode()
req = urllib.request.Request(rpc, data=body, headers={"Content-Type": "application/json"})
resp = urllib.request.urlopen(req, timeout=10)
data = json.loads(resp.read())
chain_id = int(data.get("result", "0x0"), 16)
success(f"Blockchain RPC connected (chain {chain_id})")
except Exception:
warn(f"Cannot reach RPC at {rpc}. Check your network settings.")
return True
def write_config(config):
"""Write the config file."""
path = Path("openmatrix.config.json")
if path.exists():
overwrite = ask("openmatrix.config.json already exists. Overwrite?", default="no", options=["yes", "no"])
if overwrite.lower() != "yes":
warn("Setup cancelled. Existing config preserved.")
return False
path.write_text(json.dumps(config, indent=2) + "\n")
success(f"Config written to {path}")
return True
def setup_gitignore():
"""Ensure config file with real keys isn't committed."""
gitignore = Path(".gitignore")
if gitignore.exists():
content = gitignore.read_text()
if "openmatrix.config.json" not in content:
with open(gitignore, "a") as f:
f.write("\n# Real config with secrets — never commit\nopenmatrix.config.json\n")
success(".gitignore updated")
else:
gitignore.write_text("openmatrix.config.json\n__pycache__/\n*.pyc\n.env\n")
success(".gitignore created")
# ─── Main ────────────────────────────────────────────────────────────────────
def main():
os.chdir(Path(__file__).parent)
banner()
print(f" {DIM}This setup will guide you through configuring 0pnMatrx.{RESET}")
print(f" {DIM}Press Enter to accept defaults shown in [brackets].{RESET}")
print(f" {DIM}You can re-run this anytime to change settings.{RESET}")
total = 9
config = {
"platform": "0pnMatrx",
"database": {"path": "data/0pnmatrx.db"},
}
# Step 1: Python check
step(1, total, "Checking environment")
check_python()
# Step 2: Install deps
step(2, total, "Installing dependencies")
install_dependencies()
# Step 3: Model provider
step(3, total, "AI Model Provider")
configure_model(config)
# Step 4: Blockchain
step(4, total, "Blockchain Network")
configure_blockchain(config)
# Step 5: Agents
step(5, total, "Agent Configuration")
configure_agents(config)
# Step 6: Gateway
step(6, total, "Gateway Server")
configure_gateway(config)
# Step 7: Communications
step(7, total, "Communication Channels")
configure_communications(config)
# Step 8: Security
step(8, total, "Security Settings")
configure_security(config)
# Step 9: Extras
step(9, total, "Final Settings")
configure_extras(config)
# Write and verify
print(f"\n{CYAN}{BOLD}{'═' * 60}{RESET}")
step("✓", "✓", "Finalizing Setup")
if not write_config(config):
return
setup_gitignore()
verify_setup(config)
# Done
port = config.get('gateway', {}).get('port', 18790)
api_key = config.get('gateway', {}).get('api_key', '<your-key>')
print(f"""
{GREEN}{BOLD}
╔══════════════════════════════════════════════════════════════╗
║ ║
║ Setup Complete ║
║ ║
╚══════════════════════════════════════════════════════════════╝
{RESET}
{BOLD}Start the gateway:{RESET}
{CYAN}openmatrix gateway start{RESET} Foreground (see logs live)
{CYAN}openmatrix gateway start -d{RESET} Background (daemon mode)
{BOLD}Manage the gateway:{RESET}
{CYAN}openmatrix gateway status{RESET} Check if running
{CYAN}openmatrix gateway stop{RESET} Stop the gateway
{CYAN}openmatrix gateway restart{RESET} Restart
{CYAN}openmatrix gateway logs -f{RESET} Follow logs in real time
{CYAN}openmatrix health{RESET} Quick health check
{BOLD}Send a message:{RESET}
{CYAN}curl -X POST http://localhost:{port}/chat \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer {api_key}" \\
-d '{{"agent": "trinity", "message": "Hello", "session_id": "demo"}}'{RESET}
{DIM}Run 'openmatrix setup' anytime to reconfigure.{RESET}
""")
if __name__ == "__main__":
main()