-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmini
More file actions
executable file
·488 lines (396 loc) · 16.8 KB
/
mini
File metadata and controls
executable file
·488 lines (396 loc) · 16.8 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
#!/usr/bin/env python3
# ─────────────────────────────────────────────────────
# 0xeeMini v0.1.0 — mini CLI (deploy/status/logs/backup/wallet)
# https://mini.0xee.li
# ─────────────────────────────────────────────────────
import hashlib
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
# ── Configuration VPS ─────────────────────────────────
VPS_USER = os.getenv("OXEEMINI_VPS_USER", "debian")
VPS_HOST = os.getenv("OXEEMINI_VPS_HOST", "193.108.54.70")
VPS_PATH = os.getenv("OXEEMINI_VPS_PATH", "/home/debian/0xeeMini")
VPS_WEB_PATH = os.getenv("OXEEMINI_VPS_WEB_PATH", "/home/debian/vhosts/mini.0xee.li/www")
LOCAL_PATH = str(Path(__file__).parent.resolve())
SERVICE_NAME = "0xeemini"
KEEP_BACKUPS = 10
# ── Cerveau réflexe ────────────────────────────────────
GGUF_MODEL_NAME = "qwen2.5-0.5b-instruct-q4_k_m.gguf"
GGUF_URL = (
"https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF"
"/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf"
)
GGUF_REMOTE_PATH = f"{VPS_PATH}/models/{GGUF_MODEL_NAME}"
# ── Mode Samouraï — audit GGUF 1.5B ───────────────────
SAMURAI_MODEL_NAME = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
SAMURAI_URL = (
"https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
"/resolve/main/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
)
SAMURAI_REMOTE_PATH = f"{VPS_PATH}/models/{SAMURAI_MODEL_NAME}"
# ── Helpers ───────────────────────────────────────────
def _run(cmd: list[str], check: bool = True, capture: bool = False) -> subprocess.CompletedProcess:
return subprocess.run(
cmd, check=check,
capture_output=capture,
text=True,
)
def _ssh(remote_cmd: str, capture: bool = False) -> subprocess.CompletedProcess:
return _run(
["ssh", "-o", "StrictHostKeyChecking=no",
f"{VPS_USER}@{VPS_HOST}", remote_cmd],
check=False,
capture=capture,
)
def _print_section(title: str) -> None:
width = 50
print(f"\n{'─' * width}")
print(f" {title}")
print(f"{'─' * width}")
def _check_vps_configured() -> bool:
if VPS_HOST == "REMPLACER_PAR_IP_VPS":
print("❌ VPS non configuré.")
print(" Édite le fichier 'mini' et remplace VPS_HOST par l'IP réelle.")
return False
return True
# ── Commandes ─────────────────────────────────────────
def cmd_deploy() -> None:
"""Déploie le projet sur le VPS et redémarre le service."""
if not _check_vps_configured():
return
print(f"🚀 Déploiement vers {VPS_USER}@{VPS_HOST}:{VPS_PATH}")
# rsync — exclure secrets, DB, logs
_print_section("rsync")
_run([
"rsync", "-avz",
"--exclude=.git/",
"--exclude=*.db", "--exclude=*.db-shm", "--exclude=*.db-wal",
"--exclude=logs/", "--exclude=.env", "--exclude=backups/",
"--exclude=__pycache__/", "--exclude=*.pyc", "--exclude=.venv/",
f"{LOCAL_PATH}/",
f"{VPS_USER}@{VPS_HOST}:{VPS_PATH}/",
])
# Venv + dépendances
_print_section("venv + pip install")
_ssh(
f"cd {VPS_PATH} && "
f"python3 -m venv .venv && "
f".venv/bin/pip install -q -r requirements.txt"
)
# Installer le service systemd (idempotent)
_print_section("install service")
_ssh(
f"mkdir -p ~/.config/systemd/user && "
f"cp {VPS_PATH}/0xeemini.service ~/.config/systemd/user/ && "
f"systemctl --user daemon-reload && "
f"systemctl --user enable {SERVICE_NAME}.service && "
f"loginctl enable-linger debian"
)
# Synchroniser le frontend vers le vhost lighttpd (tous les fichiers)
_print_section("sync www → lighttpd vhost")
_run([
"rsync", "-avz",
"--exclude='.DS_Store'",
"-e", "ssh -o StrictHostKeyChecking=no",
f"{LOCAL_PATH}/www/",
f"{VPS_USER}@{VPS_HOST}:{VPS_WEB_PATH}/",
])
# Redémarrer le service
_print_section("restart service")
_ssh(f"systemctl --user restart {SERVICE_NAME}.service")
# Status en cascade
print()
cmd_status()
def cmd_status() -> None:
"""Affiche le statut du service VPS + RAM + logs récents."""
if not _check_vps_configured():
return
try:
from rich.console import Console
from rich.panel import Panel
console = Console()
use_rich = True
except ImportError:
use_rich = False
_print_section("Service systemd")
_ssh(f"systemctl --user status {SERVICE_NAME}.service --no-pager")
_print_section("RAM")
_ssh("free -h | grep Mem")
_print_section("Derniers logs (5 lignes)")
result = _ssh(
f"tail -5 ~/.local/share/0xeemini/logs/agent.log",
capture=True,
)
if result.stdout:
print(result.stdout)
else:
print("(aucun log disponible)")
def cmd_logs() -> None:
"""Suit les logs en temps réel (tail -f via SSH)."""
if not _check_vps_configured():
return
print(f"📋 Logs en temps réel — {VPS_USER}@{VPS_HOST}")
print("(Ctrl+C pour quitter)\n")
subprocess.run([
"ssh", "-o", "StrictHostKeyChecking=no",
"-t", f"{VPS_USER}@{VPS_HOST}",
"tail -f ~/.local/share/0xeemini/logs/agent.log",
])
def cmd_backup() -> None:
"""Télécharge et vérifie la base de données SQLite."""
if not _check_vps_configured():
return
backup_dir = Path(LOCAL_PATH) / "backups"
backup_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
local_file = backup_dir / f"state_{ts}.db"
remote_file = f"~/.local/share/0xeemini/state.db"
print(f"📦 Backup DB → {local_file}")
# SCP
_run([
"scp",
"-o", "StrictHostKeyChecking=no",
f"{VPS_USER}@{VPS_HOST}:{remote_file}",
str(local_file),
])
# Vérification MD5
_print_section("Vérification MD5")
remote_md5 = _ssh(
f"md5sum ~/.local/share/0xeemini/state.db | cut -d' ' -f1",
capture=True,
).stdout.strip()
with open(local_file, "rb") as f:
local_md5 = hashlib.md5(f.read()).hexdigest()
if local_md5 == remote_md5:
print(f"✅ MD5 vérifié : {local_md5}")
else:
print(f"❌ MD5 mismatch ! Remote={remote_md5} Local={local_md5}")
# Garder seulement les KEEP_BACKUPS derniers
backups = sorted(backup_dir.glob("state_*.db"))
if len(backups) > KEEP_BACKUPS:
to_delete = backups[: len(backups) - KEEP_BACKUPS]
for f in to_delete:
f.unlink()
print(f"🗑️ Supprimé ancien backup : {f.name}")
print(f"\n📂 {len(list(backup_dir.glob('state_*.db')))} backup(s) dans {backup_dir}")
def cmd_wallet() -> None:
"""Affiche le statut du wallet 0xeeMini."""
if not _check_vps_configured():
return
_print_section("Wallet Status")
_ssh(
f"cd {VPS_PATH} && .venv/bin/python -c \""
f"import importlib, sys; sys.path.insert(0, '.'); "
f"cfg_mod = importlib.import_module('0xeemini.config'); "
f"pe_mod = importlib.import_module('0xeemini.profit_engine'); "
f"pe_mod.ProfitEngine(cfg_mod.CFG).print_wallet_status()"
f"\""
)
def cmd_transfer_test() -> None:
"""Envoie 10 USDC vers le wallet owner (test du ProfitEngine)."""
if not _check_vps_configured():
return
print(f"💸 Test transfert 10 USDC → OWNER_SOLFLARE_ADDRESS")
print(f" Kill window : 60s après signature (SIGTERM pour annuler)")
print(f" Ctrl+C pour annuler AVANT la signature\n")
_ssh(
f"cd {VPS_PATH} && .venv/bin/python -c \""
f"import importlib, sys, asyncio; sys.path.insert(0, '.'); "
f"cfg_mod = importlib.import_module('0xeemini.config'); "
f"pe_mod = importlib.import_module('0xeemini.profit_engine'); "
f"pe = pe_mod.ProfitEngine(cfg_mod.CFG); "
f"result = asyncio.run(pe.execute_transfer({{"
f" 'tx_type': 'OWNER_TEST', "
f" 'amount_usdc': 10.0, "
f" 'to_wallet': cfg_mod.CFG['owner_address'], "
f" 'memo': '0xeeMini test transfer', "
f" 'idempotency_key': 'owner_test_2026_02'"
f"}}))"
f"\""
)
def cmd_stop() -> None:
"""Arrête le service 0xeeMini sur le VPS."""
if not _check_vps_configured():
return
print(f"🛑 Arrêt de {SERVICE_NAME}.service")
_ssh(f"systemctl --user stop {SERVICE_NAME}.service")
_ssh(f"systemctl --user status {SERVICE_NAME}.service --no-pager")
def cmd_start() -> None:
"""Démarre le service 0xeeMini sur le VPS."""
if not _check_vps_configured():
return
print(f"▶️ Démarrage de {SERVICE_NAME}.service")
_ssh(f"systemctl --user start {SERVICE_NAME}.service")
_ssh(f"systemctl --user status {SERVICE_NAME}.service --no-pager")
def cmd_download_model() -> None:
"""Télécharge le modèle GGUF (cerveau réflexe) sur le VPS."""
if not _check_vps_configured():
return
# Vérifier si déjà présent
check = _ssh(f"test -f {GGUF_REMOTE_PATH} && echo EXISTS", capture=True)
if "EXISTS" in check.stdout:
print(f"✅ Modèle déjà présent : {GGUF_REMOTE_PATH}")
size = _ssh(f"du -h {GGUF_REMOTE_PATH} | cut -f1", capture=True).stdout.strip()
print(f" Taille : {size}")
return
print(f"📥 Téléchargement du cerveau réflexe → {GGUF_REMOTE_PATH}")
print(f" Source : {GGUF_URL}")
print(f" ~400 Mo — patience...\n")
_ssh(f"mkdir -p {VPS_PATH}/models")
_ssh(
f"wget -q --show-progress -O {GGUF_REMOTE_PATH} '{GGUF_URL}'"
)
# Vérification
check2 = _ssh(f"test -f {GGUF_REMOTE_PATH} && du -h {GGUF_REMOTE_PATH} | cut -f1", capture=True)
if check2.returncode == 0:
print(f"\n✅ Modèle téléchargé : {check2.stdout.strip()}")
else:
print("\n❌ Téléchargement échoué.")
def cmd_install_brain() -> None:
"""Installe llama-cpp-python sur le VPS (compilation C++ ~10 min)."""
if not _check_vps_configured():
return
# Vérifier si déjà installé
check = _ssh(
f"{VPS_PATH}/.venv/bin/python -c 'import llama_cpp; print(llama_cpp.__version__)'",
capture=True,
)
if check.returncode == 0:
print(f"✅ llama-cpp-python déjà installé : v{check.stdout.strip()}")
return
print("🔧 Installation de llama-cpp-python sur le VPS")
print(" Compilation C++ native — ~10 minutes selon le CPU\n")
# Dépendances système
_print_section("apt — outils de compilation")
_ssh("sudo apt-get install -y -q cmake build-essential python3-dev")
# Compilation llama-cpp-python (BLAS off, 1 thread pour économiser la RAM)
_print_section("pip — llama-cpp-python (compilation)")
_ssh(
f"cd {VPS_PATH} && "
f"CMAKE_ARGS='-DLLAMA_BLAS=OFF' MAKEFLAGS='-j1' "
f".venv/bin/pip install llama-cpp-python"
)
# Vérification
check2 = _ssh(
f"{VPS_PATH}/.venv/bin/python -c 'import llama_cpp; print(llama_cpp.__version__)'",
capture=True,
)
if check2.returncode == 0:
print(f"\n✅ llama-cpp-python installé : v{check2.stdout.strip()}")
print("\n📋 Prochaine étape :")
print(f" ./mini download-model (si pas encore fait)")
print(f" ./mini deploy (redémarre l'agent)")
else:
print("\n❌ Installation échouée — voir erreurs ci-dessus.")
def cmd_download_audit_model() -> None:
"""Télécharge le modèle Samouraï GGUF 1.5B (audit GitHub) sur le VPS."""
if not _check_vps_configured():
return
# Vérifier si déjà présent
check = _ssh(f"test -f {SAMURAI_REMOTE_PATH} && echo EXISTS", capture=True)
if "EXISTS" in check.stdout:
print(f"✅ Modèle Samouraï déjà présent : {SAMURAI_REMOTE_PATH}")
size = _ssh(f"du -h {SAMURAI_REMOTE_PATH} | cut -f1", capture=True).stdout.strip()
print(f" Taille : {size}")
return
print(f"📥 Téléchargement du Mode Samouraï → {SAMURAI_REMOTE_PATH}")
print(f" Source : {SAMURAI_URL}")
print(f" ~900 Mo — patience...\n")
_ssh(f"mkdir -p {VPS_PATH}/models")
_ssh(
f"wget -q --show-progress -O {SAMURAI_REMOTE_PATH} '{SAMURAI_URL}'"
)
# Vérification
check2 = _ssh(
f"test -f {SAMURAI_REMOTE_PATH} && du -h {SAMURAI_REMOTE_PATH} | cut -f1",
capture=True,
)
if check2.returncode == 0:
print(f"\n✅ Modèle Samouraï téléchargé : {check2.stdout.strip()}")
print(f" BRAIN_AUDIT_MODEL_PATH déjà configuré par défaut dans config.py")
print(f" Redémarre l'agent : ./mini deploy")
else:
print("\n❌ Téléchargement échoué — voir erreurs ci-dessus.")
def cmd_register_agent() -> None:
"""Enregistre 0xeeMini sur le registre EIP-8004 (EmberAI/Arbitrum)."""
print("📡 Enregistrement de 0xeeMini — EIP-8004 / EmberAI / Arbitrum")
print(" Prérequis : Node.js installé localement, wallet Arbitrum avec gas\n")
print(" Ça va coûter quelques centimes de gas ARB pour l'on-chain TX.\n")
_run([
"npx", "-y", "@emberai/agent-node@latest", "register",
"--name", "0xeeMini",
"--description", (
"Autonomous AI agent detecting fake blockchain developers via GitHub commit analysis. "
"Bullshit score 0-100. 0.50 USDC per audit via Solana HTTP402. "
"26 tests. Open source."
),
"--url", f"https://mini.0xee.li",
"--version", "0.3.0",
"--image", "https://mini.0xee.li/favicon.ico",
], check=False)
def cmd_setup_vps() -> None:
"""Configure ~/.config/0xeeMini/ sur le VPS pour la première fois."""
if not _check_vps_configured():
return
print(f"🔐 Configuration initiale du VPS {VPS_HOST}")
# Créer le répertoire config
_ssh("mkdir -p ~/.config/0xeeMini && chmod 700 ~/.config/0xeeMini")
# Copier setup_secrets.sh
_run([
"scp",
"-o", "StrictHostKeyChecking=no",
f"{LOCAL_PATH}/setup_secrets.sh",
f"{VPS_USER}@{VPS_HOST}:~/setup_secrets.sh",
])
# Copier .env.example
_run([
"scp",
"-o", "StrictHostKeyChecking=no",
f"{LOCAL_PATH}/.env.example",
f"{VPS_USER}@{VPS_HOST}:~/.config/0xeeMini/.env.example",
])
print("\n✅ setup_secrets.sh copié sur le VPS")
print("\n📋 PROCHAINE ÉTAPE — sur le VPS :")
print(f" ssh {VPS_USER}@{VPS_HOST}")
print(f" cd {VPS_PATH}")
print(f" bash ~/setup_secrets.sh")
print(f" nano ~/.config/0xeeMini/.env")
# ── Dispatcher ────────────────────────────────────────
COMMANDS = {
"deploy": (cmd_deploy, "Déploie sur le VPS et redémarre"),
"status": (cmd_status, "Affiche statut service + RAM + logs"),
"logs": (cmd_logs, "Suit les logs en temps réel"),
"backup": (cmd_backup, "Télécharge et vérifie la DB"),
"wallet": (cmd_wallet, "Affiche le statut du wallet USDC"),
"stop": (cmd_stop, "Arrête le service"),
"start": (cmd_start, "Démarre le service"),
"setup-vps": (cmd_setup_vps, "Configure les secrets sur le VPS"),
"register-agent": (cmd_register_agent, "Enregistre sur le registre EIP-8004 (EmberAI)"),
"install-brain": (cmd_install_brain, "Installe llama-cpp-python sur le VPS"),
"download-model": (cmd_download_model, "Télécharge le cerveau réflexe 0.5B (~400 Mo)"),
"download-audit-model": (cmd_download_audit_model, "Télécharge le Mode Samouraï 1.5B (~900 Mo)"),
"transfer-test": (cmd_transfer_test, "Envoie 10 USDC vers le wallet owner (test)"),
}
def _usage() -> None:
print(f"\n0xeeMini CLI v0.1.0 — {VPS_USER}@{VPS_HOST}")
print(f"Platform : https://mini.0xee.li\n")
print("Usage : ./mini <commande>\n")
print("Commandes disponibles :")
for name, (_, desc) in COMMANDS.items():
print(f" {name:<14} {desc}")
print()
def main() -> None:
if len(sys.argv) < 2:
_usage()
sys.exit(1)
cmd = sys.argv[1].lower()
if cmd not in COMMANDS:
print(f"❌ Commande inconnue : '{cmd}'")
_usage()
sys.exit(1)
COMMANDS[cmd][0]()
if __name__ == "__main__":
main()