forked from joi-lab/ouroboros
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlauncher.py
More file actions
1385 lines (1211 loc) · 51.8 KB
/
launcher.py
File metadata and controls
1385 lines (1211 loc) · 51.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
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
# ============================
# Prometheus — VPS Runtime launcher (entry point)
# ============================
# Thin orchestrator: secrets, bootstrap, main loop.
# Heavy logic lives in supervisor/ package.
# Reads config from env vars or ~/prometheus/config.env
import logging
import os
import sys
import json
import time
import uuid
import pathlib
import subprocess
import datetime
import threading
import queue as _queue_mod
from typing import Any, Dict, List, Optional, Tuple
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
log = logging.getLogger(__name__)
_LAUNCH_TIME = time.time()
# ----------------------------
# 0) Load config from env file if present
# ----------------------------
_CONFIG_FILE = pathlib.Path.home() / "prometheus" / "config.env"
if _CONFIG_FILE.exists():
log.info("Loading config from %s", _CONFIG_FILE)
for line in _CONFIG_FILE.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, _, value = line.partition("=")
key = key.strip()
value = value.strip().strip('"').strip("'")
# Strip inline comments (e.g. "MiniMax-M2.5 # fallback")
if " #" in value:
value = value.split(" #")[0].strip()
if key and key not in os.environ:
os.environ[key] = value
# ----------------------------
# 0.1) provide apply_patch shim
# ----------------------------
from prometheus.apply_patch import install as install_apply_patch
from prometheus.llm import DEFAULT_LIGHT_MODEL, get_kimi_usage
install_apply_patch()
# ----------------------------
# 1) Secrets + runtime config (from env vars)
# ----------------------------
def get_secret(name: str, default: Optional[str] = None, required: bool = False) -> Optional[str]:
v = os.environ.get(name)
if v is None or str(v).strip() == "":
v = default
if required:
assert v is not None and str(v).strip() != "", f"Missing required config: {name}"
return v
def get_cfg(name: str, default: Optional[str] = None) -> Optional[str]:
v = os.environ.get(name)
if v is not None and str(v).strip() != "":
return v
return default
def _parse_int_cfg(raw: Optional[str], default: int, minimum: int = 0) -> int:
try:
val = int(str(raw))
except Exception:
val = default
return max(minimum, val)
# --- Env var migration: PROMETHEUS_* → PROMETHEUS_* ---
# Backward compat: if old names exist but new ones don't, copy them over.
_ENV_PREFIX_OLD = "PROMETHEUS_"
_ENV_PREFIX_NEW = "PROMETHEUS_"
for _key in list(os.environ):
if _key.startswith(_ENV_PREFIX_OLD):
_new_key = _ENV_PREFIX_NEW + _key[len(_ENV_PREFIX_OLD):]
if _new_key not in os.environ:
os.environ[_new_key] = os.environ[_key]
# --- End migration ---
# Required secrets
OPENROUTER_API_KEY = get_secret("OPENROUTER_API_KEY", default="")
TELEGRAM_BOT_TOKEN = get_secret("TELEGRAM_BOT_TOKEN", required=True)
GITHUB_TOKEN = get_secret("GITHUB_TOKEN", required=True)
# Budget
import re
_raw_budget = str(get_secret("TOTAL_BUDGET", default="0") or "")
_clean_budget = re.sub(r'[^0-9.\-]', '', _raw_budget)
TOTAL_BUDGET_LIMIT = float(_clean_budget) if _clean_budget else 0.0
OPENAI_API_KEY = get_secret("OPENAI_API_KEY", default="")
ANTHROPIC_API_KEY = get_secret("ANTHROPIC_API_KEY", default="")
GITHUB_USER = get_cfg("GITHUB_USER")
GITHUB_REPO = get_cfg("GITHUB_REPO")
assert GITHUB_USER and str(GITHUB_USER).strip(), "GITHUB_USER not set in config."
assert GITHUB_REPO and str(GITHUB_REPO).strip(), "GITHUB_REPO not set in config."
MAX_WORKERS = int(get_cfg("PROMETHEUS_MAX_WORKERS", default="3") or "3")
MODEL_MAIN = get_cfg("PROMETHEUS_MODEL", default="codex-mini")
MODEL_CODE = get_cfg("PROMETHEUS_MODEL_CODE", default="codex-mini")
MODEL_LIGHT = get_cfg("PROMETHEUS_MODEL_LIGHT", default=DEFAULT_LIGHT_MODEL)
# Telegram group allowlist (comma-separated group chat IDs)
_raw_groups = get_cfg("TELEGRAM_ALLOWED_GROUPS", default="")
ALLOWED_GROUPS_CONFIG: set = set()
if _raw_groups:
for _g in str(_raw_groups).split(","):
_g = _g.strip()
if _g:
try:
ALLOWED_GROUPS_CONFIG.add(int(_g))
except ValueError:
log.warning("Invalid group ID in TELEGRAM_ALLOWED_GROUPS: %s", _g)
BUDGET_REPORT_EVERY_MESSAGES = 10
SOFT_TIMEOUT_SEC = max(60, int(get_cfg("PROMETHEUS_SOFT_TIMEOUT_SEC", default="600") or "600"))
HARD_TIMEOUT_SEC = max(120, int(get_cfg("PROMETHEUS_HARD_TIMEOUT_SEC", default="1800") or "1800"))
DIAG_HEARTBEAT_SEC = _parse_int_cfg(get_cfg("PROMETHEUS_DIAG_HEARTBEAT_SEC", default="30"), default=30, minimum=0)
DIAG_SLOW_CYCLE_SEC = _parse_int_cfg(get_cfg("PROMETHEUS_DIAG_SLOW_CYCLE_SEC", default="20"), default=20, minimum=0)
# Export to env for submodules that read from env
if OPENROUTER_API_KEY:
os.environ["OPENROUTER_API_KEY"] = str(OPENROUTER_API_KEY)
os.environ.setdefault("OPENAI_API_KEY", str(OPENAI_API_KEY or ""))
os.environ.setdefault("ANTHROPIC_API_KEY", str(ANTHROPIC_API_KEY or ""))
os.environ["GITHUB_USER"] = str(GITHUB_USER)
os.environ["GITHUB_REPO"] = str(GITHUB_REPO)
os.environ["PROMETHEUS_MODEL"] = str(MODEL_MAIN or "codex-mini")
os.environ["PROMETHEUS_MODEL_CODE"] = str(MODEL_CODE or "codex-mini")
if MODEL_LIGHT:
os.environ["PROMETHEUS_MODEL_LIGHT"] = str(MODEL_LIGHT)
os.environ["PROMETHEUS_DIAG_HEARTBEAT_SEC"] = str(DIAG_HEARTBEAT_SEC)
os.environ["PROMETHEUS_DIAG_SLOW_CYCLE_SEC"] = str(DIAG_SLOW_CYCLE_SEC)
os.environ["TELEGRAM_BOT_TOKEN"] = str(TELEGRAM_BOT_TOKEN)
# ----------------------------
# 2) Filesystem paths (VPS local)
# ----------------------------
DRIVE_ROOT = pathlib.Path(
os.environ.get("PROMETHEUS_DATA_DIR", str(pathlib.Path.home() / "prometheus" / "data"))
).resolve()
REPO_DIR = pathlib.Path(
os.environ.get("PROMETHEUS_REPO_DIR", str(pathlib.Path.home() / "prometheus" / "repo"))
).resolve()
for sub in ["state", "logs", "memory", "index", "locks", "archive"]:
(DRIVE_ROOT / sub).mkdir(parents=True, exist_ok=True)
REPO_DIR.mkdir(parents=True, exist_ok=True)
# Clear stale owner mailbox files from previous session
try:
from prometheus.owner_inject import get_pending_path
_stale_inject = get_pending_path(DRIVE_ROOT)
if _stale_inject.exists():
_stale_inject.unlink(missing_ok=True)
_mailbox_dir = DRIVE_ROOT / "memory" / "owner_mailbox"
if _mailbox_dir.exists():
for _f in _mailbox_dir.iterdir():
_f.unlink(missing_ok=True)
except Exception:
pass
CHAT_LOG_PATH = DRIVE_ROOT / "logs" / "chat.jsonl"
if not CHAT_LOG_PATH.exists():
CHAT_LOG_PATH.write_text("", encoding="utf-8")
# ----------------------------
# 3) Git constants
# ----------------------------
BRANCH_DEV = get_cfg("PROMETHEUS_BRANCH_DEV", default="main")
BRANCH_STABLE = get_cfg("PROMETHEUS_BRANCH_STABLE", default="main")
REMOTE_URL = f"https://{GITHUB_TOKEN}:x-oauth-basic@github.com/{GITHUB_USER}/{GITHUB_REPO}.git"
# ----------------------------
# 4) Initialize supervisor modules
# ----------------------------
from supervisor.state import (
init as state_init, load_state, save_state, append_jsonl,
update_budget_from_usage, status_text, rotate_chat_log_if_needed,
init_state,
)
state_init(DRIVE_ROOT, TOTAL_BUDGET_LIMIT)
init_state()
from supervisor.telegram import (
init as telegram_init, TelegramClient, send_with_budget, log_chat,
)
TG = TelegramClient(str(TELEGRAM_BOT_TOKEN))
telegram_init(
drive_root=DRIVE_ROOT,
total_budget_limit=TOTAL_BUDGET_LIMIT,
budget_report_every=BUDGET_REPORT_EVERY_MESSAGES,
tg_client=TG,
)
from supervisor.git_ops import (
init as git_ops_init, ensure_repo_present, checkout_and_reset,
sync_runtime_dependencies, import_test, safe_restart,
)
git_ops_init(
repo_dir=REPO_DIR, drive_root=DRIVE_ROOT, remote_url=REMOTE_URL,
branch_dev=BRANCH_DEV, branch_stable=BRANCH_STABLE,
)
from supervisor.queue import (
enqueue_task, enforce_task_timeouts, enqueue_evolution_task_if_needed,
persist_queue_snapshot, restore_pending_from_snapshot,
cancel_task_by_id, queue_review_task, sort_pending,
)
from supervisor.workers import (
init as workers_init, get_event_q, WORKERS, PENDING, RUNNING,
spawn_workers, kill_workers, assign_tasks, ensure_workers_healthy,
handle_chat_direct, _get_chat_agent, auto_resume_after_restart,
)
workers_init(
repo_dir=REPO_DIR, drive_root=DRIVE_ROOT, max_workers=MAX_WORKERS,
soft_timeout=SOFT_TIMEOUT_SEC, hard_timeout=HARD_TIMEOUT_SEC,
total_budget_limit=TOTAL_BUDGET_LIMIT,
branch_dev=BRANCH_DEV, branch_stable=BRANCH_STABLE,
)
from supervisor.events import dispatch_event
def _load_allowed_groups() -> set:
"""Get current allowed groups: config + state.json runtime additions."""
groups = set(ALLOWED_GROUPS_CONFIG)
st = load_state()
for gid in st.get("allowed_groups", []):
try:
groups.add(int(gid))
except (ValueError, TypeError):
pass
return groups
def _get_group_config(chat_id: int) -> dict:
"""Get per-group config from state.json. Returns defaults if not configured."""
st = load_state()
cfg = st.get("group_config", {}).get(str(chat_id), {})
return {
"policy": cfg.get("policy", "allowlist"),
"require_mention": cfg.get("require_mention", True),
"allowed_users": set(cfg.get("allowed_users", [])),
"history_limit": cfg.get("history_limit", 50),
}
def _set_group_config(chat_id: int, key: str, value) -> None:
"""Update a single field in a group's config."""
st = load_state()
gc = st.setdefault("group_config", {})
cfg = gc.setdefault(str(chat_id), {})
cfg[key] = value
save_state(st)
# ----------------------------
# 5) Bootstrap repo
# ----------------------------
ensure_repo_present()
ok, msg = safe_restart(reason="bootstrap", unsynced_policy="rescue_and_reset")
assert ok, f"Bootstrap failed: {msg}"
# ----------------------------
# 6) Start workers
# ----------------------------
kill_workers()
spawn_workers(MAX_WORKERS)
restored_pending = restore_pending_from_snapshot()
persist_queue_snapshot(reason="startup")
if restored_pending > 0:
log.info("Restored %d pending tasks from snapshot", restored_pending)
# Persist launch time so dashboard can calculate uptime
_st_boot = load_state()
_st_boot["launch_time_unix"] = _LAUNCH_TIME
save_state(_st_boot)
append_jsonl(DRIVE_ROOT / "logs" / "supervisor.jsonl", {
"ts": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"type": "launcher_start",
"branch": load_state().get("current_branch"),
"sha": load_state().get("current_sha"),
"max_workers": MAX_WORKERS,
"model_default": MODEL_MAIN, "model_code": MODEL_CODE, "model_light": MODEL_LIGHT,
"soft_timeout_sec": SOFT_TIMEOUT_SEC, "hard_timeout_sec": HARD_TIMEOUT_SEC,
"worker_start_method": str(os.environ.get("PROMETHEUS_WORKER_START_METHOD") or ""),
"diag_heartbeat_sec": DIAG_HEARTBEAT_SEC,
"diag_slow_cycle_sec": DIAG_SLOW_CYCLE_SEC,
})
# ----------------------------
# 6.1) Auto-resume after restart
# ----------------------------
auto_resume_after_restart()
# ----------------------------
# 6.2) Direct-mode watchdog
# ----------------------------
def _chat_watchdog_loop():
"""Monitor direct-mode chat agent for hangs. Runs as daemon thread."""
soft_warned = False
while True:
time.sleep(30)
try:
agent = _get_chat_agent()
if not agent._busy:
soft_warned = False
continue
now = time.time()
idle_sec = now - agent._last_progress_ts
total_sec = now - agent._task_started_ts
if idle_sec >= HARD_TIMEOUT_SEC:
st = load_state()
if st.get("owner_chat_id"):
send_with_budget(
int(st["owner_chat_id"]),
f"Task stuck ({int(total_sec)}s without progress). Restarting agent.",
)
reset_chat_agent()
soft_warned = False
continue
if idle_sec >= SOFT_TIMEOUT_SEC and not soft_warned:
soft_warned = True
st = load_state()
if st.get("owner_chat_id"):
send_with_budget(
int(st["owner_chat_id"]),
f"Task running for {int(total_sec)}s, "
f"last progress {int(idle_sec)}s ago. Continuing.",
)
except Exception:
log.debug("Failed to check/notify chat watchdog", exc_info=True)
pass
_watchdog_thread = threading.Thread(target=_chat_watchdog_loop, daemon=True)
_watchdog_thread.start()
# ----------------------------
# 6.3) Background consciousness
# ----------------------------
from prometheus.consciousness import BackgroundConsciousness
def _get_owner_chat_id() -> Optional[int]:
try:
st = load_state()
cid = st.get("owner_chat_id")
return int(cid) if cid else None
except Exception:
return None
_consciousness = BackgroundConsciousness(
drive_root=DRIVE_ROOT,
repo_dir=REPO_DIR,
event_queue=get_event_q(),
owner_chat_id_fn=_get_owner_chat_id,
)
# ----------------------------
# 6.3b) Scheduler thread
# ----------------------------
try:
from prometheus.tools.scheduler import start_scheduler as _start_sched
from prometheus.tools.registry import ToolContext as _TC
_sched_ctx = _TC(drive_root=DRIVE_ROOT, repo_dir=REPO_DIR)
_start_sched(_sched_ctx)
log.info("Scheduler thread started")
except Exception as _se:
log.warning("Failed to start scheduler: %s", _se)
def reset_chat_agent():
"""Reset the direct-mode chat agent (called by watchdog on hangs)."""
import supervisor.workers as _w
_w._chat_agent = None
# ----------------------------
# 6.4) Dashboard server (toggleable background thread)
# ----------------------------
_DASHBOARD_PORT = int(os.environ.get("DASHBOARD_PORT", "8080"))
_DASHBOARD_HOST = os.environ.get("DASHBOARD_HOST", "178.62.224.22")
_dashboard_server = None # uvicorn.Server instance (for clean shutdown)
_dashboard_thread = None
def _start_dashboard():
"""Start the dashboard. Returns True if started, False if already running or failed."""
global _dashboard_server, _dashboard_thread
if _dashboard_thread and _dashboard_thread.is_alive():
return False # already running
def _run():
global _dashboard_server
try:
import uvicorn
from dashboard.server import app as dashboard_app
config = uvicorn.Config(
dashboard_app, host="0.0.0.0", port=_DASHBOARD_PORT, log_level="warning",
)
_dashboard_server = uvicorn.Server(config)
log.info("Dashboard started on 0.0.0.0:%s", _DASHBOARD_PORT)
_dashboard_server.run()
except ImportError as e:
log.warning("Dashboard not started (missing dependency): %s", e)
except Exception:
log.exception("Dashboard server failed")
finally:
_dashboard_server = None
_dashboard_thread = threading.Thread(target=_run, daemon=True, name="dashboard")
_dashboard_thread.start()
return True
def _stop_dashboard():
"""Stop the dashboard. Returns True if stopped, False if not running."""
global _dashboard_server
if _dashboard_server:
_dashboard_server.should_exit = True
return True
return False
def _dashboard_running() -> bool:
return _dashboard_thread is not None and _dashboard_thread.is_alive()
# Auto-start if state says enabled
if load_state().get("dashboard_enabled"):
_start_dashboard()
# ----------------------------
# 6.5) Codex OAuth state (for /login command)
# ----------------------------
_pending_oauth: Dict[str, Any] = {}
# ----------------------------
# 7) Main loop
# ----------------------------
import types
_pending_events: List[Dict[str, Any]] = [] # For events generated by event handlers
_event_ctx = types.SimpleNamespace(
DRIVE_ROOT=DRIVE_ROOT,
REPO_DIR=REPO_DIR,
BRANCH_DEV=BRANCH_DEV,
BRANCH_STABLE=BRANCH_STABLE,
TG=TG,
WORKERS=WORKERS,
PENDING=PENDING,
RUNNING=RUNNING,
MAX_WORKERS=MAX_WORKERS,
send_with_budget=send_with_budget,
load_state=load_state,
save_state=save_state,
update_budget_from_usage=update_budget_from_usage,
append_jsonl=append_jsonl,
enqueue_task=enqueue_task,
cancel_task_by_id=cancel_task_by_id,
queue_review_task=queue_review_task,
persist_queue_snapshot=persist_queue_snapshot,
safe_restart=safe_restart,
kill_workers=kill_workers,
spawn_workers=spawn_workers,
sort_pending=sort_pending,
consciousness=_consciousness,
pending_events=_pending_events,
)
def _safe_qsize(q: Any) -> int:
try:
return int(q.qsize())
except Exception:
return -1
# Rate limiter for read-only supervisor commands (prevent /queue flood)
_CMD_RATE_LIMIT: Dict[str, float] = {} # cmd -> last_processed_ts
_CMD_RATE_LIMIT_SEC = 2.0 # min seconds between identical commands
def _fmt_tokens(n: int) -> str:
"""Format token count for display (e.g. 1.2M, 50k)."""
if n >= 1_000_000:
return f"{n / 1_000_000:.1f}M"
if n >= 1_000:
return f"{n / 1_000:.0f}k"
return str(n)
def _build_status_text() -> str:
"""Build the /status message text."""
st = load_state()
sha = st.get("current_sha", "?")[:7]
version = st.get("version") or "?"
# Uptime
uptime_sec = int(time.time() - _LAUNCH_TIME)
if uptime_sec < 60:
uptime_str = f"{uptime_sec}s"
elif uptime_sec < 3600:
uptime_str = f"{uptime_sec // 60}m {uptime_sec % 60}s"
elif uptime_sec < 86400:
h, rem = divmod(uptime_sec, 3600)
uptime_str = f"{h}h {rem // 60}m"
else:
d, rem = divmod(uptime_sec, 86400)
uptime_str = f"{d}d {rem // 3600}h"
# Token usage
prompt_tok = st.get("spent_tokens_prompt", 0)
comp_tok = st.get("spent_tokens_completion", 0)
calls = st.get("spent_calls", 0)
# Queue / Evolution / Consciousness / Model
pending_count = len(PENDING)
running_count = len(RUNNING)
evo_enabled = st.get("evolution_mode_enabled", False)
evo_cycle = st.get("evolution_cycle", 0)
bg_status = "on" if _consciousness.is_running else "off"
model_primary = MODEL_MAIN or "?"
model_fallback = MODEL_LIGHT or "?"
# Kimi 5h window usage
kimi = get_kimi_usage()
kimi_remaining = kimi["window_remaining_sec"]
if kimi["calls"] > 0:
kh, km = divmod(kimi_remaining, 3600)
kimi_time = f"{kh}h {km // 60}m left"
kimi_total = kimi["input_tokens"] + kimi["output_tokens"]
kimi_line = f"\U0001f4a0 Kimi (5h): {_fmt_tokens(kimi_total)} tokens \u00b7 {kimi['calls']} calls \u00b7 {kimi_time}"
else:
kimi_line = "\U0001f4a0 Kimi (5h): idle"
return "\n".join([
f"\U0001f525 Prometheus {version} ({sha})",
f"\U0001f9e0 Model: {model_primary} \u00b7 Fallback: {model_fallback}",
f"\U0001f9ee Tokens: {_fmt_tokens(prompt_tok)} in / {_fmt_tokens(comp_tok)} out \u00b7 {calls} calls",
kimi_line,
f"\U0001f9f5 Queue: {pending_count} pending \u00b7 {running_count} running \u00b7 {len(WORKERS)} workers",
f"\U00002699\ufe0f Evo: {'cycle ' + str(evo_cycle) if evo_enabled else 'off'} \u00b7 BG: {bg_status} \u00b7 Up: {uptime_str}",
])
def _handle_groups_command(text: str, chat_id: int):
"""Handle /groups subcommands: add, remove, info, policy, mention, allow, deny, users, history, help."""
parts = text.strip().split()
allowed = _load_allowed_groups()
# /groups help
if len(parts) >= 2 and parts[1].lower() == "help":
send_with_budget(chat_id, "\n".join([
"👥 /groups commands:",
" /groups — list all groups",
" /groups add <id> — add group to allowlist",
" /groups remove <id> — remove group",
" /groups <id> info — show group config",
" /groups <id> policy open|allowlist|disabled",
" /groups <id> mention on|off",
" /groups <id> allow <user_id> — add allowed user",
" /groups <id> deny <user_id> — remove allowed user",
" /groups <id> users — list allowed users",
" /groups <id> history <N> — set history limit",
"",
"⚠️ Privacy Mode:",
"For 'open' policy without @mentions, the bot must see all messages.",
"Either: @BotFather → /setprivacy → Disable (then re-add bot to group)",
"Or: Make the bot a group admin.",
]))
return
# /groups add <id>
if len(parts) >= 3 and parts[1].lower() == "add":
try:
gid = int(parts[2])
except ValueError:
send_with_budget(chat_id, "❌ Invalid group ID. Use numeric chat ID (e.g. -1001234567890)")
return
st = load_state()
rt_groups = list(st.get("allowed_groups", []))
if gid not in rt_groups:
rt_groups.append(gid)
st["allowed_groups"] = rt_groups
# Initialize default config for the group
gc = st.setdefault("group_config", {})
if str(gid) not in gc:
gc[str(gid)] = {"policy": "allowlist", "require_mention": True, "allowed_users": [], "history_limit": 50}
save_state(st)
send_with_budget(chat_id, f"✅ Group {gid} added. Use /groups {gid} info to see config.")
return
# /groups remove <id>
if len(parts) >= 3 and parts[1].lower() == "remove":
try:
gid = int(parts[2])
except ValueError:
send_with_budget(chat_id, "❌ Invalid group ID.")
return
st = load_state()
st["allowed_groups"] = [g for g in st.get("allowed_groups", []) if int(g) != gid]
st.get("group_config", {}).pop(str(gid), None)
save_state(st)
ALLOWED_GROUPS_CONFIG.discard(gid)
send_with_budget(chat_id, f"✅ Group {gid} removed.")
return
# /groups <id> <subcommand> — try to parse parts[1] as group ID
if len(parts) >= 3:
try:
gid = int(parts[1])
sub = parts[2].lower()
except ValueError:
gid = None
sub = None
if gid is not None and gid in allowed:
gcfg = _get_group_config(gid)
if sub == "info":
users_str = ", ".join(str(u) for u in sorted(gcfg["allowed_users"])) or "any"
send_with_budget(chat_id, "\n".join([
f"👥 Group {gid}:",
f" Policy: {gcfg['policy']}",
f" Require mention: {'yes' if gcfg['require_mention'] else 'no'}",
f" History limit: {gcfg['history_limit']}",
f" Allowed users: {users_str}",
]))
return
if sub == "policy" and len(parts) >= 4:
mode = parts[3].lower()
if mode not in ("open", "allowlist", "disabled"):
send_with_budget(chat_id, "❌ Policy must be: open, allowlist, or disabled")
return
_set_group_config(gid, "policy", mode)
send_with_budget(chat_id, f"✅ Group {gid} policy set to '{mode}'.")
return
if sub == "mention" and len(parts) >= 4:
val = parts[3].lower()
_set_group_config(gid, "require_mention", val in ("on", "true", "yes", "1"))
send_with_budget(chat_id, f"✅ Group {gid} require_mention: {val}")
return
if sub == "allow" and len(parts) >= 4:
try:
uid = int(parts[3])
except ValueError:
send_with_budget(chat_id, "❌ User ID must be numeric.")
return
st = load_state()
gc = st.setdefault("group_config", {}).setdefault(str(gid), {})
users = list(gc.get("allowed_users", []))
if uid not in users:
users.append(uid)
gc["allowed_users"] = users
save_state(st)
send_with_budget(chat_id, f"✅ User {uid} added to group {gid} allowlist.")
return
if sub == "deny" and len(parts) >= 4:
try:
uid = int(parts[3])
except ValueError:
send_with_budget(chat_id, "❌ User ID must be numeric.")
return
st = load_state()
gc = st.setdefault("group_config", {}).setdefault(str(gid), {})
gc["allowed_users"] = [u for u in gc.get("allowed_users", []) if u != uid]
save_state(st)
send_with_budget(chat_id, f"✅ User {uid} removed from group {gid} allowlist.")
return
if sub == "users":
users_str = ", ".join(str(u) for u in sorted(gcfg["allowed_users"])) or "(empty — all users allowed)"
send_with_budget(chat_id, f"👥 Group {gid} allowed users:\n{users_str}")
return
if sub == "history" and len(parts) >= 4:
try:
limit = max(0, int(parts[3]))
except ValueError:
send_with_budget(chat_id, "❌ History limit must be a number.")
return
_set_group_config(gid, "history_limit", limit)
send_with_budget(chat_id, f"✅ Group {gid} history limit set to {limit}.")
return
send_with_budget(chat_id, f"❌ Unknown subcommand '{sub}'. Use /groups help")
return
# /groups (bare) — list all groups with config summary
if not allowed:
send_with_budget(chat_id, "👥 No groups configured.\n\nUse /groups add <chat_id> or /groups help")
else:
lines = ["👥 Allowed groups:"]
for gid in sorted(allowed):
gcfg = _get_group_config(gid)
source = "config" if gid in ALLOWED_GROUPS_CONFIG else "runtime"
lines.append(f" {gid} ({source}) — {gcfg['policy']}, mention={'on' if gcfg['require_mention'] else 'off'}")
lines.append(f"\nTotal: {len(allowed)}. Use /groups <id> info or /groups help")
send_with_budget(chat_id, "\n".join(lines))
def _handle_skills_command(text: str, chat_id: int):
"""Handle /skills subcommands for managing agent skills."""
import shutil as _shutil
from pathlib import Path as _Path
skills_root = DRIVE_ROOT / "skills"
parts = text.strip().split(None, 3)
sub = parts[1].lower() if len(parts) > 1 else ""
# --- /skills (no args) or /skills list ---
if not sub or sub == "list":
if not skills_root.exists() or not any(skills_root.iterdir()):
send_with_budget(chat_id, "📦 No skills installed.")
return
lines = ["📦 Skills:"]
for entry in sorted(skills_root.iterdir()):
if not entry.is_dir():
continue
sf = entry / "SKILL.md"
if not sf.exists():
continue
try:
from prometheus.tools.skills import parse_skill_file
parsed = parse_skill_file(sf.read_text(encoding="utf-8"))
status = "✅" if parsed["enabled"] else "⬜"
auto = " [auto]" if parsed["auto_invoke"] and parsed["enabled"] else ""
desc = (parsed["description"] or "No description")[:60]
lines.append(f" {status} {entry.name}{auto} — {desc}")
except Exception:
lines.append(f" ⚠️ {entry.name} — parse error")
send_with_budget(chat_id, "\n".join(lines))
return
# --- /skills help ---
if sub == "help":
lines = [
"📦 /skills — Skill management:",
" /skills — list all skills",
" /skills create <name> — create skill (send content in next message)",
" /skills delete <name> — delete a skill",
" /skills enable <name> — enable a skill",
" /skills disable <name> — disable a skill",
" /skills info <name> — show full skill content",
"",
"Skills are instruction packages (SKILL.md) that teach the agent",
"new capabilities. They are injected into the LLM system prompt.",
"Auto-invoke skills are included automatically; others are read on-demand.",
]
send_with_budget(chat_id, "\n".join(lines))
return
# --- /skills create <name> ---
if sub == "create":
name = parts[2].strip().lower() if len(parts) > 2 else ""
if not name:
send_with_budget(chat_id, "Usage: /skills create <name>")
return
skill_dir = skills_root / name
if skill_dir.exists():
send_with_budget(chat_id, f"⚠️ Skill '{name}' already exists.")
return
# Create with placeholder — user can edit via dashboard or agent
skill_dir.mkdir(parents=True, exist_ok=True)
content = parts[3].strip() if len(parts) > 3 else ""
from prometheus.tools.skills import build_skill_frontmatter
frontmatter = build_skill_frontmatter(name, "New skill (edit description)", True, True)
body = content if content else "## Instructions\n\n(Add skill instructions here)"
(skill_dir / "SKILL.md").write_text(frontmatter + "\n" + body, encoding="utf-8")
send_with_budget(chat_id, f"✅ Skill '{name}' created. Edit via dashboard or agent.")
return
# --- /skills delete <name> ---
if sub == "delete":
name = parts[2].strip().lower() if len(parts) > 2 else ""
if not name:
send_with_budget(chat_id, "Usage: /skills delete <name>")
return
skill_dir = skills_root / name
if not skill_dir.exists():
send_with_budget(chat_id, f"⚠️ Skill '{name}' not found.")
return
_shutil.rmtree(str(skill_dir))
send_with_budget(chat_id, f"🗑 Skill '{name}' deleted.")
return
# --- /skills enable <name> ---
if sub == "enable":
name = parts[2].strip().lower() if len(parts) > 2 else ""
if not name:
send_with_budget(chat_id, "Usage: /skills enable <name>")
return
sf = skills_root / name / "SKILL.md"
if not sf.exists():
send_with_budget(chat_id, f"⚠️ Skill '{name}' not found.")
return
from prometheus.tools.skills import parse_skill_file, build_skill_frontmatter
parsed = parse_skill_file(sf.read_text(encoding="utf-8"))
fm = build_skill_frontmatter(parsed["name"] or name, parsed["description"], True, parsed["auto_invoke"], parsed["version"])
sf.write_text(fm + "\n" + parsed["body"], encoding="utf-8")
send_with_budget(chat_id, f"✅ Skill '{name}' enabled.")
return
# --- /skills disable <name> ---
if sub == "disable":
name = parts[2].strip().lower() if len(parts) > 2 else ""
if not name:
send_with_budget(chat_id, "Usage: /skills disable <name>")
return
sf = skills_root / name / "SKILL.md"
if not sf.exists():
send_with_budget(chat_id, f"⚠️ Skill '{name}' not found.")
return
from prometheus.tools.skills import parse_skill_file, build_skill_frontmatter
parsed = parse_skill_file(sf.read_text(encoding="utf-8"))
fm = build_skill_frontmatter(parsed["name"] or name, parsed["description"], False, parsed["auto_invoke"], parsed["version"])
sf.write_text(fm + "\n" + parsed["body"], encoding="utf-8")
send_with_budget(chat_id, f"⬜ Skill '{name}' disabled.")
return
# --- /skills info <name> ---
if sub == "info":
name = parts[2].strip().lower() if len(parts) > 2 else ""
if not name:
send_with_budget(chat_id, "Usage: /skills info <name>")
return
sf = skills_root / name / "SKILL.md"
if not sf.exists():
send_with_budget(chat_id, f"⚠️ Skill '{name}' not found.")
return
content = sf.read_text(encoding="utf-8")
# Truncate for Telegram (max ~4000 chars)
if len(content) > 3800:
content = content[:3800] + "\n\n... (truncated)"
send_with_budget(chat_id, f"📦 Skill: {name}\n\n{content}")
return
send_with_budget(chat_id, "Unknown /skills subcommand. Try /skills help")
def _handle_supervisor_command(text: str, chat_id: int, tg_offset: int = 0):
"""Handle supervisor slash-commands.
Returns:
True — terminal command fully handled (caller should `continue`)
str — dual-path note to prepend (caller falls through to LLM)
"" — not a recognized command (falsy, caller falls through)
"""
lowered = text.strip().lower()
# Rate-limit read-only commands to prevent flood
rate_limited_cmds = ("/queue", "/status", "/budget", "/workers", "/evolve", "/dashboard", "/skills", "/help")
for prefix in rate_limited_cmds:
if lowered.startswith(prefix) and " " not in lowered.strip().strip("/"):
now = time.time()
last = _CMD_RATE_LIMIT.get(prefix, 0)
if (now - last) < _CMD_RATE_LIMIT_SEC:
return True # silently skip duplicate
_CMD_RATE_LIMIT[prefix] = now
break
if lowered.startswith("/panic"):
send_with_budget(chat_id, "PANIC: stopping everything now.")
kill_workers()
st2 = load_state()
st2["tg_offset"] = tg_offset
save_state(st2)
raise SystemExit("PANIC")
if lowered.startswith("/restart"):
st2 = load_state()
st2["session_id"] = uuid.uuid4().hex
st2["tg_offset"] = tg_offset
save_state(st2)
send_with_budget(chat_id, "Restarting (soft).")
ok, msg = safe_restart(reason="owner_restart", unsynced_policy="rescue_and_reset")
if not ok:
send_with_budget(chat_id, f"Restart cancelled: {msg}")
return True
kill_workers()
os.execv(sys.executable, [sys.executable, __file__])
# /login — Codex OAuth flow via Telegram
if lowered.startswith("/login"):
try:
from prometheus.codex_auth import get_login_url, exchange_code_for_tokens, save_auth
url, verifier, state = get_login_url()
_pending_oauth["code_verifier"] = verifier
_pending_oauth["state"] = state
send_with_budget(chat_id,
f"Open this URL to authenticate with ChatGPT:\n\n{url}\n\n"
"After logging in, you'll be redirected. Copy the full redirect URL and send it back here."
)
except Exception as e:
send_with_budget(chat_id, f"Login failed: {e}")
return True
if lowered.startswith("/queue"):
lines = ["\U0001f4cb Queue:"]
if PENDING:
for t in PENDING:
tid = str(t.get("id", "?"))[:8]
typ = t.get("type", "?")
txt = str(t.get("text") or t.get("description") or "")[:40]
lines.append(f" {tid} | {typ} | {txt}")
else:
lines.append(" (empty)")
lines.append(f"\n\U0001f7e1 Pending: {len(PENDING)} \u00b7 \U0001f7e2 Running: {len(RUNNING)}")
send_with_budget(chat_id, "\n".join(lines))
return True
if lowered.startswith("/status"):
send_with_budget(chat_id, _build_status_text())
return True
if lowered.startswith("/budget"):
st = load_state()
msg = (
f"💰 **Budget:**\n"
f"- Spent: ${st.get('spent_usd', 0):.2f}\n"
f"- Limit: ${TOTAL_BUDGET_LIMIT:.2f}\n"
f"- Calls: {st.get('spent_calls', 0)}"
)
send_with_budget(chat_id, msg)
return True
if lowered.startswith("/workers"):
msg = f"👷 **Workers:** {len(WORKERS)}\n"
for i, w in enumerate(WORKERS):
msg += f"- {i}: {_safe_qsize(w.task_q)} tasks queued\n"
send_with_budget(chat_id, msg.strip())
return True
if lowered.startswith("/evolve"):
if "start" in lowered or "on" in lowered:
st = load_state()
st["evolution_mode_enabled"] = True
st["evolution_consecutive_failures"] = 0
save_state(st)
send_with_budget(chat_id, "Evolution enabled.")
elif "stop" in lowered or "off" in lowered:
st = load_state()
st["evolution_mode_enabled"] = False
save_state(st)
send_with_budget(chat_id, "Evolution disabled.")
else:
st = load_state()
enabled = st.get("evolution_mode_enabled", False)
send_with_budget(chat_id, f"Evolution: {'enabled' if enabled else 'disabled'}")
return True
if lowered.startswith("/bg"):
if "start" in lowered or "on" in lowered:
_consciousness.start()
send_with_budget(chat_id, "Background consciousness started.")
elif "stop" in lowered or "off" in lowered:
_consciousness.stop()
send_with_budget(chat_id, "Background consciousness stopped.")
else:
send_with_budget(chat_id, f"Background: {'running' if _consciousness.is_running else 'stopped'}")
return True
if lowered.startswith("/review"):
queue_review_task(reason="owner request")
send_with_budget(chat_id, "Review queued.")
return True
if lowered.startswith("/dashboard"):
url = f"http://{_DASHBOARD_HOST}:{_DASHBOARD_PORT}"
if "on" in lowered or "start" in lowered:
if _dashboard_running():
send_with_budget(chat_id, f"📊 Dashboard already running: {url}")