-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui.py
More file actions
2158 lines (1852 loc) · 78.6 KB
/
Copy pathui.py
File metadata and controls
2158 lines (1852 loc) · 78.6 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
"""
ui.py -- RUMI Terminal UI (v10.0 Hermes Agent Style)
Works with or without rich/prompt_toolkit — falls back to ANSI codes.
"""
import sys as _sys
_sys.stderr.write(f"[RUMI-UI] Python {_sys.version.split()[0]} @ {_sys.executable}\n")
_sys.stderr.flush()
import sys
import os
import json
import time
import random
import platform
import threading
import re as _re
from pathlib import Path
from datetime import datetime
from collections import deque
# -- Terminal setup --
if sys.platform == "win32":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleOutputCP(65001)
kernel32.SetConsoleCP(65001)
STD_OUTPUT_HANDLE = -11
handle = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
mode = ctypes.c_ulong()
kernel32.GetConsoleMode(handle, ctypes.byref(mode))
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
mode.value |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
kernel32.SetConsoleMode(handle, mode.value)
except Exception:
pass
# -- Rich import (optional) --
HAVE_RICH = False
try:
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.text import Text
from rich.rule import Rule
from rich.table import Table
from rich.box import ROUNDED, MINIMAL, SIMPLE, HEAVY, DOUBLE, HORIZONTALS
from rich.style import Style
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn
from rich.layout import Layout
from rich.columns import Columns
from rich.align import Align
from rich.padding import Padding
from rich.theme import Theme
HAVE_RICH = True
except ImportError:
pass
# -- prompt_toolkit import (optional) --
HAVE_PT = False
try:
from prompt_toolkit import prompt as _pt_prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.styles import Style as PtStyle
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.formatted_text import HTML
HAVE_PT = True
except ImportError:
HAVE_PT = False
KeyBindings = None
HTML = None
BASE_DIR = Path(__file__).resolve().parent
CONFIG_DIR = BASE_DIR / "config"
API_FILE = CONFIG_DIR / "api_keys.json"
# ================================================================
# ANSI HELPERS (work without rich)
# ================================================================
def _ansi(color_hex: str) -> str:
"""Convert #RRGGBB to ANSI 24-bit escape sequence."""
if not color_hex or not color_hex.startswith("#"):
return ""
r = int(color_hex[1:3], 16)
g = int(color_hex[3:5], 16)
b = int(color_hex[5:7], 16)
return f"\033[38;2;{r};{g};{b}m"
def _ansi_bg(color_hex: str) -> str:
"""Convert #RRGGBB to ANSI bg escape sequence."""
if not color_hex or not color_hex.startswith("#"):
return ""
r = int(color_hex[1:3], 16)
g = int(color_hex[3:5], 16)
b = int(color_hex[5:7], 16)
return f"\033[48;2;{r};{g};{b}m"
_BOLD = "\033[1m"
_DIM = "\033[2m"
_RESET = "\033[0m"
_CLEAR_LINE = "\033[2K"
_CUR_UP = "\033[A"
def _aprint(text: str, color: str = "", bold: bool = False):
"""Print with ANSI color (works without rich)."""
parts = []
if bold:
parts.append(_BOLD)
if color and color.startswith("#"):
parts.append(_ansi(color))
parts.append(text)
parts.append(_RESET)
sys.stdout.write("".join(parts) + "\n")
sys.stdout.flush()
# ================================================================
# PREMIUM AI RESEARCH OS THEME
# Pure black, soft white, electric blue/cyan, no grey
# ================================================================
# Background
BG_DEEP = "#000000"
BG_SECOND = "#0a0a0a"
BG_PANEL = "#111111"
BG_ELEMENT = "#1a1a1a"
BG_HOVER = "#222222"
BG_INPUT = "#000000"
# Text hierarchy — NO GREY, all visible
TXT_BRIGHT = "#FFFFFF"
TXT_PRIMARY = "#EAEAEA"
TXT_SECOND = "#CCCCCC"
TXT_MUTED = "#AAAAAA"
TXT_DIM = "#888888"
# Accent palette — electric blue/cyan
ACCENT_CYAN = "#00E5FF"
ACCENT_BLUE = "#2979FF"
ACCENT_GREEN = "#00E676"
ACCENT_AMBER = "#FFD600"
ACCENT_RED = "#FF1744"
ACCENT_PURPLE = "#B388FF"
ACCENT_TEAL = "#00E5FF"
ACCENT_PINK = "#FF80AB"
# Semantic aliases
C_BLUE = ACCENT_BLUE
C_GREEN = ACCENT_GREEN
C_AMBER = ACCENT_AMBER
C_RED = ACCENT_RED
C_PURPLE = ACCENT_PURPLE
C_TEAL = ACCENT_TEAL
C_PINK = ACCENT_PINK
C_DIM = TXT_MUTED
C_WHITE = TXT_PRIMARY
C_BOLD = TXT_BRIGHT
# Borders
BORDER_SUBTLE = "#333333"
BORDER_NORMAL = "#555555"
BORDER_ACTIVE = "#2979FF"
# Status bar
SB_BG = "#000000"
SB_FG = "#CCCCCC"
# ================================================================
# CONSOLE (rich or ANSI fallback)
# ================================================================
if HAVE_RICH:
_dark_theme = Theme({
"black": BG_DEEP,
"white": TXT_PRIMARY,
"cyan": ACCENT_CYAN,
"green": ACCENT_GREEN,
"yellow": ACCENT_AMBER,
"blue": ACCENT_BLUE,
"magenta": ACCENT_PURPLE,
"red": ACCENT_RED,
"dim": TXT_MUTED,
})
# Force UTF-8 stdout for Rich on Windows
if sys.platform == "win32":
import io as _io
if hasattr(sys.stdout, 'buffer') and sys.stdout.encoding != 'utf-8':
sys.stdout = _io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
if hasattr(sys.stderr, 'buffer') and sys.stderr.encoding != 'utf-8':
sys.stderr = _io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
console = Console(
force_terminal=True,
color_system="truecolor",
theme=_dark_theme,
no_color=False,
)
_console_lock = threading.Lock()
_orig_console_print = console.print
def _thread_safe_print(*args, **kwargs):
with _console_lock:
_orig_console_print(*args, **kwargs)
console.print = _thread_safe_print
else:
# ANSI fallback console
class _AnsiConsole:
"""Minimal console using ANSI escape codes."""
def __init__(self):
self.width = 80
try:
import shutil
self.width = shutil.get_terminal_size().columns
except Exception:
pass
def print(self, *args, **kwargs):
for arg in args:
if isinstance(arg, str):
sys.stdout.write(arg + "\n")
elif hasattr(arg, '__str__'):
sys.stdout.write(str(arg) + "\n")
sys.stdout.flush()
def clear(self):
sys.stdout.write("\033[2J\033[H")
sys.stdout.flush()
console = _AnsiConsole()
# Stub out Rich classes when not available
class Text:
def __init__(self, text="", style=""):
self._parts = [(text, style)]
def append(self, text, style=""):
self._parts.append((text, style))
return self
def __str__(self):
out = []
for text, style in self._parts:
color = ""
bold = False
if style:
s = str(style)
if "bold" in s:
bold = True
# Extract hex color from style string
for part in s.split():
if part.startswith("#"):
color = part
break
if not color and s.startswith("#"):
color = s
if bold:
out.append(_BOLD)
if color and color.startswith("#"):
out.append(_ansi(color))
out.append(text)
out.append(_RESET)
return "".join(out)
@property
def plain(self):
return "".join(t for t, _ in self._parts)
class Markdown:
def __init__(self, text="", **kw):
self._text = text
def __str__(self):
return self._text
def _md(text):
return Markdown(text)
_console_lock = threading.Lock()
# ================================================================
# HERMES AGENT CONSTANTS
# ================================================================
# Prompt symbols
PROMPT_SYMBOL = "> "
PROMPT_BUSY = "> "
PROMPT_READY = "> "
# Clean ASCII indicators (no kaomoji)
THINKING_VERBS = [
"searching literature", "extracting entities", "building knowledge graph",
"mining contradictions", "generating hypotheses", "reviewing claims",
"designing experiments", "checking novelty", "synthesizing results",
"analyzing patterns", "computing metrics", "formulating theories",
]
# Per-tool verbs
TOOL_VERBS = {
"search": "searching",
"read": "reading",
"write": "writing",
"edit": "editing",
"graph": "graphing",
"discover": "discovering",
"hypothesize": "hypothesizing",
"review": "reviewing",
"experiment": "experimenting",
"analyze": "analyzing",
"papers": "fetching",
"contradictions": "mining",
"enrich": "enriching",
}
# Single indicator style — clean ASCII
INDICATOR_STYLES = {
"ascii": {
"frames": ["|", "/", "-", "\\"],
"tick": 0.1,
"show_verb": True,
},
}
INDICATOR_STYLE = "ascii"
# Streaming cursor
STREAMING_CURSOR = "_"
# Kaomoji faces (ported from Hermes Agent)
FACES = [
'(。•́︿•̀。)',
'(◔_◔)',
'(¬‿¬)',
'( •_•)>⌐■-■',
'(⌐■_■)',
'(´・_・`)',
'◉_◉',
'(°ロ°)',
'( ˘⌣˘)♡',
'ヽ(>∀<☆)☆',
'٩(๑❛ᴗ❛๑)۶',
'(⊙_⊙)',
'(¬_¬)',
'( ͡° ͜ʖ ͡°)',
'ಠ_ಠ',
]
# Role display system (Hermes Agent style)
ROLES = {
"user": {"glyph": "❯", "color": ACCENT_BLUE, "label": "USER"},
"assistant": {"glyph": "●", "color": ACCENT_CYAN, "label": "RUMI"},
"tool": {"glyph": "⚡", "color": ACCENT_AMBER, "label": "TOOL"},
"system": {"glyph": "·", "color": TXT_MUTED, "label": "SYS"},
}
# Thinking verbs (Hermes Agent style)
THINKING_VERBS_HERMES = [
"pondering", "contemplating", "musing", "cogitating",
"ruminating", "deliberating", "mulling", "reflecting",
"processing", "reasoning", "analyzing", "computing",
"synthesizing", "formulating", "brainstorming",
]
# Legacy compatibility
SPINNER_CHARS = "|/-\\"
THINKING_MESSAGES = THINKING_VERBS
# Status badges
BADGE_ONLINE = "[READY]"
BADGE_THINKING = "[THINKING]"
BADGE_RESEARCH = "[RESEARCHING]"
BADGE_DISCOVER = "[DISCOVERING]"
BADGE_MEMORY = "[MEMORY]"
BADGE_DREAM = "[DREAM]"
BADGE_IDLE = "[IDLE]"
# ================================================================
# ASCII LOGO
# ================================================================
RUMI_LOGO = r"""
██████╗ ██╗ ██╗███╗ ███╗██╗
██╔══██╗██║ ██║████╗ ████║██║
██████╔╝██║ ██║██╔████╔██║██║
██╔══██╗██║ ██║██║╚██╔╝██║██║
██║ ██║╚██████╔╝██║ ╚═╝ ██║██║
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝
"""
# ================================================================
# PERSONALITY SYSTEM
# ================================================================
PERSONALITIES = {
"cutesy": {
"label": "Cutesy / UwU",
"desc": "Playful, cute scientist",
"soul_file": "SOUL_cutesy.md",
"rumi_file": "RUMI_cutesy.md",
},
"professional": {
"label": "Professional / Sharp",
"desc": "Direct, analytical scientist",
"soul_file": "SOUL_professional.md",
"rumi_file": "RUMI_professional.md",
},
}
def _set_personality(choice: str):
p = PERSONALITIES.get(choice)
if not p:
return False
for dest, src_key in [("SOUL.md", "soul_file"), ("RUMI.md", "rumi_file")]:
src = BASE_DIR / p[src_key]
dst = BASE_DIR / dest
if src.exists():
dst.write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
cfg = BASE_DIR / "config" / "api_keys.json"
if cfg.exists():
try:
data = json.loads(cfg.read_text(encoding="utf-8"))
data["personality"] = choice
cfg.write_text(json.dumps(data, indent=4), encoding="utf-8")
except Exception:
pass
return True
# ================================================================
# UTILITY FUNCTIONS
# ================================================================
def _detect_os() -> str:
s = platform.system().lower()
return "mac" if s == "darwin" else "windows" if s == "windows" else "linux"
def _load_user_name() -> str:
try:
data = json.loads(API_FILE.read_text(encoding="utf-8"))
return data.get("user_name", "OPERATOR").upper()
except Exception:
return "OPERATOR"
def _api_keys_exist() -> bool:
if not API_FILE.exists():
return False
try:
data = json.loads(API_FILE.read_text(encoding="utf-8"))
has_gemini = bool(data.get("gemini_api_key"))
has_groq = bool(data.get("groq_api_key"))
has_os = bool(data.get("os_system"))
return has_gemini and has_groq and has_os
except Exception:
return False
def _make_progress_bar(pct: int, width: int = 10) -> str:
"""Progress bar: [████░░░░░░] 40%"""
filled = int(pct / 100 * width)
empty = width - filled
return f"[{'█' * filled}{'░' * empty}] {pct}%"
def _make_status_badge(text: str, color: str) -> Text:
badge = Text()
badge.append(f" {text} ", style=f"bold {color}")
return badge
# ================================================================
# HELP TEXT
# ================================================================
HELP_TEXT = f"""**RUMI** v3.1 — Research Unified Machine Intelligence
**Commands**
/help Show this help
/clear Clear screen
/status System status
/stats Session stats
/exit Shut down
**Discovery**
/discover <topic> Full pipeline
/search <query> Literature search
/hypothesize [topic] Generate hypotheses
/experiment Design experiment
/review Peer review
/domains List 17 domains
**New in v2.1**
/simulate <hypothesis> Monte Carlo simulation
/debate <hypothesis> Multi-agent debate
/continuous [N] Autonomous research loop
/transfer <domain>:<mech> to <domain> Cross-domain transfer
/curiosity Research frontier
/evolve Theory evolution
/consistency Math consistency check
**Modes**
/think Toggle reasoning mode
/dive Toggle deep research
**Shortcuts**
Ctrl+K Command palette
Ctrl+L Clear screen
Escape Interrupt"""
# ================================================================
# SLASH COMMANDS
# ================================================================
SLASH_COMMANDS = [
"/help", "/clear", "/think", "/dive",
"/status", "/stats", "/model", "/exit",
"/science", "/discover", "/search", "/enrich", "/hypothesize",
"/experiment", "/generate", "/contradictions",
"/papers", "/review", "/graph", "/dashboard", "/discoveries",
"/notebook", "/domains", "/domain",
"/personality", "/reason", "/theorize", "/grounded",
"/timeline",
"/simulate", "/debate", "/continuous", "/transfer",
"/curiosity", "/evolve", "/consistency",
]
# ================================================================
# SESSION TIMELINE
# ================================================================
class SessionTimeline:
def __init__(self):
self._events: list[dict] = []
self._lock = threading.Lock()
def add(self, event_type: str, description: str, detail: str = ""):
with self._lock:
self._events.append({
"time": datetime.now().strftime("%H:%M:%S"),
"type": event_type,
"desc": description,
"detail": detail,
})
def get_events(self, last_n: int = 20) -> list[dict]:
with self._lock:
return list(self._events[-last_n:])
def clear(self):
with self._lock:
self._events.clear()
def count(self) -> int:
with self._lock:
return len(self._events)
# ================================================================
# ACTIVITY FEED
# ================================================================
class ActivityFeed:
def __init__(self, max_items: int = 50):
self._items: deque = deque(maxlen=max_items)
self._lock = threading.Lock()
def add(self, message: str, color: str = TXT_SECOND):
with self._lock:
self._items.append({
"time": datetime.now().strftime("%H:%M:%S"),
"msg": message,
"color": color,
})
def get_recent(self, n: int = 10) -> list[dict]:
with self._lock:
return list(self._items)[-n:]
def clear(self):
with self._lock:
self._items.clear()
# ================================================================
# DISCOVERY PIPELINE TRACKER
# ================================================================
class PipelineTracker:
PHASES = [
("literature_search", "Literature Search"),
("paper_retrieval", "Paper Retrieval"),
("entity_extraction", "Entity Extraction"),
("knowledge_graph", "Knowledge Graph"),
("contradiction_mine", "Contradiction Mining"),
("hypothesis_gen", "Hypothesis Generation"),
("skeptic_review", "Skeptic Review"),
("experiment_plan", "Experiment Planning"),
("novelty_check", "Novelty Check"),
("report_gen", "Report Generation"),
]
def __init__(self):
self._phases: dict[str, str] = {}
self._current: str = ""
self._lock = threading.Lock()
self.reset()
def reset(self):
with self._lock:
for pid, _ in self.PHASES:
self._phases[pid] = "pending"
self._current = ""
def start_phase(self, phase_id: str):
with self._lock:
found = False
for pid, _ in self.PHASES:
if pid == phase_id:
found = True
self._phases[pid] = "running"
self._current = pid
elif not found and self._phases.get(pid) == "running":
self._phases[pid] = "done"
if not found:
self._phases[phase_id] = "running"
self._current = phase_id
def complete_phase(self, phase_id: str):
with self._lock:
self._phases[phase_id] = "done"
if self._current == phase_id:
self._current = ""
def error_phase(self, phase_id: str):
with self._lock:
self._phases[phase_id] = "error"
def all_done(self) -> bool:
with self._lock:
return all(v in ("done", "error") for v in self._phases.values())
def get_display(self) -> list[tuple[str, str, str]]:
with self._lock:
result = []
for pid, label in self.PHASES:
status = self._phases.get(pid, "pending")
if status == "done":
result.append((label, "done", ACCENT_GREEN))
elif status == "running":
result.append((label, "running", ACCENT_BLUE))
elif status == "error":
result.append((label, "error", ACCENT_RED))
else:
result.append((label, "pending", TXT_DIM))
return result
def get_progress_pct(self) -> int:
with self._lock:
done = sum(1 for v in self._phases.values() if v == "done")
return int(done / len(self.PHASES) * 100) if self.PHASES else 0
# ================================================================
# TOOL CALL TRACKER
# ================================================================
class ToolCallTracker:
def __init__(self):
self._calls: deque = deque(maxlen=50)
self._lock = threading.Lock()
def start(self, tool_name: str, query: str = ""):
with self._lock:
self._calls.append({
"name": tool_name,
"query": query,
"status": "running",
"start": time.time(),
"result": "",
})
def complete(self, tool_name: str, result: str = ""):
with self._lock:
for call in reversed(self._calls):
if call["name"] == tool_name and call["status"] == "running":
call["status"] = "done"
call["result"] = result
call["elapsed"] = time.time() - call["start"]
break
def error(self, tool_name: str, error: str = ""):
with self._lock:
for call in reversed(self._calls):
if call["name"] == tool_name and call["status"] == "running":
call["status"] = "error"
call["result"] = error
call["elapsed"] = time.time() - call["start"]
break
def get_recent(self, n: int = 10) -> list[dict]:
with self._lock:
return list(self._calls)[-n:]
# ================================================================
# KNOWLEDGE GRAPH METRICS
# ================================================================
class GraphMetrics:
def __init__(self):
self.nodes = 0
self.edges = 0
self.clusters = 0
self.contradictions = 0
self.novelty_candidates = 0
self.papers = 0
self.entities = 0
self.relationships = 0
self._lock = threading.Lock()
def update(self, **kwargs):
with self._lock:
for k, v in kwargs.items():
if hasattr(self, k):
setattr(self, k, v)
def snapshot(self) -> dict:
with self._lock:
return {
"nodes": self.nodes,
"edges": self.edges,
"clusters": self.clusters,
"contradictions": self.contradictions,
"novelty_candidates": self.novelty_candidates,
"papers": self.papers,
"entities": self.entities,
"relationships": self.relationships,
}
# ================================================================
# COMMAND PALETTE
# ================================================================
COMMAND_PALETTE_ITEMS = [
("discover", "Run Discovery Pipeline", "/discover "),
("grounded", "Grounded Discovery", "/grounded "),
("search", "Search Papers", "/search "),
("hypothesize", "Generate Hypotheses", "/hypothesize "),
("experiment", "Design Experiment", "/experiment"),
("review", "Peer Review", "/review"),
("graph", "Knowledge Graph Stats", "/graph"),
("science", "Scientist Modules", "/science"),
("domains", "List Domains", "/domains"),
("status", "System Status", "/status"),
("timeline", "Session Timeline", "/timeline"),
("clear", "Clear Screen", "/clear"),
("think", "Toggle Think Mode", "/think"),
("dive", "Toggle Deep Dive", "/dive"),
("dashboard", "Open Dashboard", "/dashboard"),
("enrich", "Enrich Knowledge Graph", "/enrich"),
("contradictions", "Find Contradictions", "/contradictions"),
("generate", "Generate Molecules/Materials", "/generate "),
]
# ================================================================
# PREMIUM RUMI UI
# ================================================================
class RumiUI:
"""Premium AI operating system terminal UI for RUMI Scientist AI."""
def __init__(self, face_path=None, size=None):
self.W = None
self.H = None
# State
self.speaking = False
self._think_mode = False
self._deep_dive_active = False
self._rumi_state = "READY"
self.status_text = "READY"
self._start_time = time.time()
self._personality = "professional"
self._discovery_running = False
self._discovery_step = ""
self._discovery_topic = ""
# Callbacks
self.on_text_command = None
self.on_discovery_command = None
self.on_think_mode_toggle = None
self.on_deep_dive_toggle = None
self.on_idle_scan = None
# Threading
self._running = True
self._input_lock = threading.Lock()
# Interrupt
self._interrupt_requested = threading.Event()
self._is_busy = False
# Idle Scan
self._last_input_time = time.time()
self._last_idle_scan_time = 0.0
self._idle_thread = threading.Thread(target=self._idle_monitor, daemon=True)
self._idle_thread.start()
self._message_queue_count = 0
self._current_spin_idx = 0
self._current_word_idx = 0
# Input history
self._pt_history = InMemoryHistory() if HAVE_PT else None
self._message_count = 0
# Session tracking
self._timeline = SessionTimeline()
self._pipeline = PipelineTracker()
self._tool_calls = ToolCallTracker()
self._graph_metrics = GraphMetrics()
self._activity_feed = ActivityFeed()
# Token tracking
self._total_tokens = 0
self._total_cost = 0.0
self._last_latency = 0.0
# Status bar updater
self._status_thread = threading.Thread(target=self._status_updater, daemon=True)
self._status_thread.start()
# Face ticker state
self._face_idx = 0
self._face_tick = 0.25 # seconds between face changes
# Thinking content buffer
self._thinking_content = []
self._thinking_active = False
self._tool_trail = [] # [{name, query, status, elapsed, result}]
# Animated Startup
self._show_boot_sequence()
# Check API keys
self._api_key_ready = _api_keys_exist()
if not self._api_key_ready:
self._show_setup_ui()
# Start input reader
self._input_thread = threading.Thread(target=self._input_loop, daemon=True)
self._input_thread.start()
# Start heartbeat
self._heartbeat_thread = threading.Thread(target=self._heartbeat_loop, daemon=True)
self._heartbeat_thread.start()
# Timeline entry
self._timeline.add("system", "RUMI initialized", "Model: Gemini 2.5 Flash")
# ----------------------------------------------------------------
# BOOT SEQUENCE (Hermes Agent style)
# ----------------------------------------------------------------
def _show_boot_sequence(self):
"""Clean boot with ASCII logo and role preview."""
console.clear()
from discovery.llm_client import get_status
status = get_status()
groq_ok = status.get("groq", {}).get("available", False)
gemini_ok = status.get("gemini", {}).get("available", False)
groq_keys = status.get("groq", {}).get("keys", 0)
gemini_keys = status.get("gemini", {}).get("keys", 0)
# ASCII Logo in cyan
console.print()
console.print(Text(RUMI_LOGO, style=f"bold {ACCENT_CYAN}"))
console.print(Text(" Research Unified Machine Intelligence", style=ACCENT_BLUE))
console.print()
# Provider status — one line
line = Text()
line.append(" ●", style=ACCENT_GREEN if groq_ok else ACCENT_RED)
line.append(f" Groq ({groq_keys})", style=TXT_PRIMARY)
line.append(" ", style=TXT_SECOND)
line.append("●", style=ACCENT_GREEN if gemini_ok else ACCENT_RED)
line.append(f" Gemini ({gemini_keys})", style=TXT_PRIMARY)
line.append(" │ ", style=TXT_SECOND)
line.append("17 domains", style=TXT_SECOND)
line.append(" │ ", style=TXT_SECOND)
line.append("48 modules", style=TXT_SECOND)
console.print(line)
console.print()
# Role preview
for role_name, role in ROLES.items():
line = Text()
line.append(f" {role['glyph']} ", style=f"bold {role['color']}")
line.append(f"[{role['label']}]", style=f"bold {role['color']}")
line.append(f" — {role_name} messages", style=TXT_SECOND)
console.print(line)
console.print()
# ----------------------------------------------------------------
# HEADER PANEL (Hermes Agent style)
# ----------------------------------------------------------------
def _show_header_panel(self):
"""Minimal header — just uptime and tokens."""
uptime = self._get_uptime()
line = Text()
line.append("RUMI", style=f"bold {ACCENT_CYAN}")
line.append(f" {uptime}", style=TXT_SECOND)
line.append(f" {self._total_tokens:,} tok", style=TXT_SECOND)
if self._get_mode_str() != "normal":
line.append(f" {self._get_mode_str()}", style=ACCENT_PURPLE)
console.print(line)
def _get_uptime(self) -> str:
elapsed = int(time.time() - self._start_time)
return f"{elapsed // 3600:02d}:{(elapsed % 3600) // 60:02d}:{elapsed % 60:02d}"
def _get_mode_str(self) -> str:
modes = []
if self._think_mode:
modes.append("think")
if self._deep_dive_active:
modes.append("dive")
return " ".join(modes) if modes else "normal"
# ----------------------------------------------------------------
# ACTIVITY FEED (Hermes Agent style)
# ----------------------------------------------------------------
def _show_activity_feed(self):
"""Compact event stream."""
events = self._activity_feed.get_recent(6)
if not events:
return
for ev in events:
line = Text()
line.append(f" {ev['time']} ", style=TXT_SECOND)
line.append(ev["msg"], style=ev["color"])
console.print(line)
# ----------------------------------------------------------------
# DISCOVERY DASHBOARD (Hermes Agent style)
# ----------------------------------------------------------------
def _show_discovery_dashboard(self, topic: str = ""):
"""Discovery checklist."""
pct = self._pipeline.get_progress_pct()
bar = _make_progress_bar(pct, 10)
console.print()
console.print(Text(f"[DISCOVERY] {topic[:60]}", style=ACCENT_CYAN))
line = Text()
line.append(f" {bar} ", style=TXT_SECOND)
line.append(f"{self._graph_metrics.papers} papers", style=TXT_SECOND)
line.append(f" {self._graph_metrics.entities} entities", style=TXT_SECOND)
line.append(f" {self._graph_metrics.edges} edges", style=TXT_SECOND)
console.print(line)
# ----------------------------------------------------------------
# THINKING ANIMATION (Hermes Agent style)
# ----------------------------------------------------------------
def _show_thinking_animation(self, message: str = ""):
"""Tree-style thinking indicator."""
verb = message or "thinking"
console.print(Text(f" ├─ {verb}…", style=ACCENT_CYAN))
# ----------------------------------------------------------------
# INPUT BOX (Hermes Agent style)
# ----------------------------------------------------------------
def _show_input_box(self):
"""Minimal — no input hint."""
pass
# ----------------------------------------------------------------
# PANELS (Hermes Agent style)
# ----------------------------------------------------------------
def _show_panel(self, title: str, content: str, color: str = BORDER_NORMAL):
"""Minimal panel."""
console.print(Text(f"{title}: {content}", style=TXT_SECOND))
def _show_dream_panel(self):
"""No dream panel noise."""
pass
def _show_sidebar(self):
"""No sidebar noise."""
pass
# ----------------------------------------------------------------
# STATUS UPDATER
# ----------------------------------------------------------------
def _status_updater(self):
"""Status updater with spinner rotation and face ticker."""
verb_idx = 0
indicator = INDICATOR_STYLES[INDICATOR_STYLE]