-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaliasOS_tui.py
More file actions
1232 lines (1104 loc) · 41.5 KB
/
aliasOS_tui.py
File metadata and controls
1232 lines (1104 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
aliasOS TUI — bad_banana operator profile manager
Textual-based full CRUD alias manager + ecosystem map + live shell
"""
from __future__ import annotations
import os
import re
import shlex
import subprocess
import tempfile
from pathlib import Path
from dataclasses import dataclass, field
from typing import ClassVar
from textual import on, work
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.color import Color
from textual.containers import Container, Horizontal, Vertical, ScrollableContainer
from textual.css.query import NoMatches
from textual.reactive import reactive
from textual.screen import ModalScreen, Screen
from textual.widgets import (
Button,
DataTable,
Footer,
Header,
Input,
Label,
ListItem,
ListView,
RichLog,
Select,
Static,
Switch,
TabbedContent,
TabPane,
TextArea,
Tree,
)
from textual.widgets.tree import TreeNode
from rich.text import Text
from rich.syntax import Syntax
from rich.table import Table
from rich import box
# ─────────────────────────────────────────────
# DATA LAYER
# ─────────────────────────────────────────────
ALIAS_DIR = Path.home() / ".aliases.d"
BASHRC = Path.home() / ".bashrc"
# Ecosystem BANANA_TREE layer definitions
ECOSYSTEM = {
"OBSERVE": {
"color": "cyan",
"icon": "◉",
"tools": {
"LANimals Nexus": {
"root": "LANI_ROOT",
"desc": "Adaptive deception intelligence platform",
"aliases": ["nxcd"],
"status_cmd": "mon status 2>/dev/null || echo 'offline'",
},
"OpenSight": {
"root": "OPENSIGHT_ROOT",
"desc": "Investigative intelligence + knowledge graphs",
"aliases": ["oscd", "oi", "oadd", "ols", "opivot", "ostats", "odom"],
"status_cmd": "echo 'local'",
},
"TERRAIN": {
"root": "TERRAIN_ROOT",
"desc": "Local OSINT platform (SearxNG backend)",
"aliases": ["trcd", "rc", "rcrun", "rcstat"],
"status_cmd": "echo 'local'",
},
},
},
"SIMULATE": {
"color": "yellow",
"icon": "◈",
"tools": {
"Lune": {
"root": "LUNE_ROOT",
"desc": "Modular operator framework (60+ modules)",
"aliases": ["lucd", "mnew", "medit", "mreload"],
"status_cmd": "echo 'local'",
},
"Decoy-Hunter": {
"root": "",
"desc": "Deception detection engine",
"aliases": [],
"status_cmd": "echo 'local'",
},
},
},
"EXECUTE": {
"color": "red",
"icon": "◆",
"tools": {
"zer0DAYSlater": {
"root": "",
"desc": "Exploit framework",
"aliases": ["plb64", "plchain", "plhex", "plls", "plrs", "plurl"],
"status_cmd": "echo 'local'",
},
"Blackglass Suite": {
"root": "",
"desc": "Offensive tooling suite",
"aliases": [],
"status_cmd": "echo 'local'",
},
},
},
"ADAPT": {
"color": "green",
"icon": "◎",
"tools": {
"drift_orchestrator": {
"root": "DRIFT_ROOT",
"desc": "Runtime drift control + hallucination verification",
"aliases": ["driftcd", "driftlog", "driftsess"],
"status_cmd": "drift status 2>/dev/null || echo 'offline'",
},
"badBANANA zine": {
"root": "",
"desc": "Security research publishing (GnomeMan4201)",
"aliases": ["binbox", "bls", "bnew", "bstats", "dtls", "dtnew", "dtopen", "dtstats"],
"status_cmd": "echo 'active'",
},
"reflexive-identity": {
"root": "",
"desc": "Stylometric drift + identity framework",
"aliases": [],
"status_cmd": "echo 'local'",
},
},
},
}
# Gap analysis data — high priority missing aliases
GAPS = [
("Docker", "dps", "docker ps", "high"),
("Docker", "dpsa", "docker ps -a", "high"),
("Docker", "dlog", "docker logs -f", "high"),
("Docker", "dex", "docker exec -it", "high"),
("Docker", "dup", "docker-compose up -d", "high"),
("Docker", "ddown", "docker-compose down", "high"),
("Python venv", "ve", "python3 -m venv .venv", "high"),
("Python venv", "va", "source .venv/bin/activate", "high"),
("Python venv", "vd", "deactivate", "high"),
("Python venv", "pipi", "pip install", "high"),
("Python venv", "pipf", "pip freeze > requirements.txt", "high"),
("Testing", "pt", "pytest", "high"),
("Testing", "ptv", "pytest -v", "high"),
("Testing", "cov", "pytest --cov=. --cov-report=term-missing", "high"),
("Linting", "lint", "ruff check .", "high"),
("Linting", "fmt", "black .", "high"),
("Linting", "types", "mypy .", "high"),
("Drift", "driftv", "drift verify", "high"),
("Drift", "driftsnap", "drift snapshot", "high"),
("Drift", "driftrpt", "drift report", "high"),
("Drift", "driftreset", "drift reset", "high"),
("SSH/GPG", "sshkeys", "ls -la ~/.ssh/", "medium"),
("SSH/GPG", "gpgenc", "gpg --encrypt --armor -r", "medium"),
("SSH/GPG", "gpgdec", "gpg --decrypt", "medium"),
("Ollama", "ollpull", "ollama pull", "medium"),
("Ollama", "ollrun", "ollama run", "medium"),
("Ollama", "ollrm", "ollama rm", "medium"),
("Firewall", "fwstatus", "sudo ufw status verbose", "medium"),
("Firewall", "fwallow", "sudo ufw allow", "medium"),
("Firewall", "fwdeny", "sudo ufw deny", "medium"),
("Tmux", "tma", "tmux attach -t", "medium"),
("Tmux", "tmls", "tmux ls", "medium"),
("Tmux", "tmkill", "tmux kill-session -t", "medium"),
("Archive", "untar", "tar -xzvf", "medium"),
("Archive", "tarball", "tar -czf", "medium"),
("Clipboard", "clip", "xclip -selection clipboard", "medium"),
("Recon", "rls", "recon ls", "medium"),
("Recon", "rnew", "recon new", "medium"),
("OSINT", "oexp", "osint export", "medium"),
("OSINT", "orpt", "osint report", "medium"),
("Monitoring", "monstart", "mon start", "medium"),
("Monitoring", "monrestart", "mon restart", "medium"),
]
@dataclass
class AliasEntry:
name: str
command: str
source_file: Path
line_number: int = 0
category: str = "uncategorized"
def detect_category(name: str, command: str) -> str:
"""Infer category from alias name/command."""
rules = [
(r"^g(?!rep|pu)[a-z]{1,4}$", "git"),
(r"^(cpu|gpu|mem|disk|df|du|free|top|ps|kill|port|net|iface|local|wanip|my|dmesg|syslog|authlog|jl)", "system"),
(r"^(dns|cert|curl|http|hget|hpost|hput|hdel|hhead|hhist|hcoll|hfuzz|hrep|arp|ping|rtrace|bwtest|vpn|leak|ip)", "network"),
(r"^(oi|oadd|odom|ols|opivot|ostats|rc|recon|ia|il|iscan|iexp|istat|itop|ttp|tmat|tobs|trpt|tsearch|tcl|tcn|tioc|tsum|aiosint)", "osint"),
(r"^ai", "ai/llm"),
(r"^drift", "drift"),
(r"^(lucd|nxcd|oscd|trcd|ecos)", "ecosystem"),
(r"^(sn|sls|sl|sf|sclose|sexp|stl|mux|tts|ttl|ttnote|ttr|ttst)", "sessions"),
(r"^(api|csearch|pyc|pydep|ingest|run|semver|clog|relcut|rells|secrets|hash|jq|json|jwt|csv|hexdump|xxd|rg|strings)", "dev"),
(r"^(sc[a-z]|mnew|medit|mreload|regen)", "scaffold"),
(r"^(als|aliases|reload|ctx|refresh|cmd)", "aliasos"),
(r"^(bin|bls|bnew|bstats|dt)", "banana/devto"),
(r"^(pl[a-z])", "payload"),
(r"^(dash|dw[a-z]|mon|ca|cl|cpivot|cr)", "dashboard"),
(r"^(notes|todo|sc|nl|nq|ns|nshow|nstats|ndaily)", "notes"),
(r"^(update|install|remove|purge|search|show|autoremove)", "apt"),
]
for pattern, cat in rules:
if re.match(pattern, name):
return cat
return "utility"
def parse_alias_line(line: str) -> tuple[str, str] | None:
"""Parse 'alias name='command'' or 'alias name="command"'"""
m = re.match(r"^\s*alias\s+([^=\s]+)=['\"]?(.*?)['\"]?\s*$", line)
if not m:
return None
name = m.group(1)
cmd = m.group(2).strip("'\"")
return name, cmd
def load_aliases() -> list[AliasEntry]:
"""Load all aliases from ~/.aliases.d/ and ~/.bashrc"""
entries: list[AliasEntry] = []
seen: set[str] = set()
sources: list[Path] = []
if ALIAS_DIR.exists():
sources.extend(sorted(ALIAS_DIR.rglob("*.sh")))
sources.extend(sorted(ALIAS_DIR.rglob("*.bash")))
sources.extend(sorted(ALIAS_DIR.rglob("aliases")))
sources.extend([p for p in sorted(ALIAS_DIR.iterdir()) if p.is_file() and p.suffix not in (".md", ".py", ".txt")])
if BASHRC.exists():
sources.append(BASHRC)
# deduplicate sources
seen_paths: set[Path] = set()
unique_sources = []
for s in sources:
if s not in seen_paths:
seen_paths.add(s)
unique_sources.append(s)
for src in unique_sources:
try:
lines = src.read_text(errors="replace").splitlines()
except Exception:
continue
for i, line in enumerate(lines):
parsed = parse_alias_line(line)
if not parsed:
continue
name, cmd = parsed
if name in seen:
continue
seen.add(name)
cat = detect_category(name, cmd)
entries.append(AliasEntry(
name=name,
command=cmd,
source_file=src,
line_number=i + 1,
category=cat,
))
# If no files found (demo mode), load from shell
if not entries:
entries = _load_from_shell()
return sorted(entries, key=lambda e: e.name)
def _load_from_shell() -> list[AliasEntry]:
"""Fallback: parse `alias` output from current shell."""
entries = []
seen: set[str] = set()
try:
result = subprocess.run(
["bash", "-i", "-c", "alias"],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.splitlines():
parsed = parse_alias_line(line.replace("alias ", "", 1) if line.startswith("alias ") else line)
if not parsed:
# try format: name='cmd'
m = re.match(r"^([^=\s]+)=['\"]?(.*?)['\"]?\s*$", line.strip())
if m:
parsed = (m.group(1), m.group(2).strip("'\""))
if parsed:
name, cmd = parsed
if name not in seen:
seen.add(name)
entries.append(AliasEntry(
name=name,
command=cmd,
source_file=BASHRC,
category=detect_category(name, cmd),
))
except Exception:
pass
return entries
def write_alias(entry: AliasEntry) -> bool:
"""Write/update a single alias in its source file."""
try:
path = entry.source_file
if not path.exists():
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
lines = path.read_text(errors="replace").splitlines(keepends=True)
new_line = f"alias {entry.name}='{entry.command}'\n"
# try to update in place
if entry.line_number > 0 and entry.line_number <= len(lines):
old = lines[entry.line_number - 1]
if f"alias {entry.name}=" in old:
lines[entry.line_number - 1] = new_line
path.write_text("".join(lines))
return True
# search by name
for i, line in enumerate(lines):
if re.match(rf"^\s*alias\s+{re.escape(entry.name)}\s*=", line):
lines[i] = new_line
path.write_text("".join(lines))
return True
# append
content = path.read_text(errors="replace")
if not content.endswith("\n"):
content += "\n"
path.write_text(content + new_line)
return True
except Exception as e:
return False
def delete_alias(entry: AliasEntry) -> bool:
"""Remove alias line from source file."""
try:
path = entry.source_file
lines = path.read_text(errors="replace").splitlines(keepends=True)
new_lines = [
l for l in lines
if not re.match(rf"^\s*alias\s+{re.escape(entry.name)}\s*=", l)
]
path.write_text("".join(new_lines))
return True
except Exception:
return False
# ─────────────────────────────────────────────
# MODAL SCREENS
# ─────────────────────────────────────────────
class AliasEditModal(ModalScreen):
"""Modal for creating or editing an alias."""
BINDINGS = [("escape", "dismiss", "cancel")]
CSS = """
AliasEditModal {
align: center middle;
}
#modal-container {
width: 70;
height: auto;
background: $surface;
border: thick $primary;
padding: 1 2;
}
#modal-title {
text-align: center;
text-style: bold;
color: $accent;
margin-bottom: 1;
}
.field-label {
color: $text-muted;
margin-top: 1;
}
#modal-buttons {
margin-top: 1;
align: right middle;
height: 3;
}
"""
def __init__(self, entry: AliasEntry | None = None, alias_files: list[Path] | None = None):
super().__init__()
self.entry = entry
self.alias_files = alias_files or ([ALIAS_DIR / "custom.sh"] if ALIAS_DIR.exists() else [BASHRC])
self.is_new = entry is None
def compose(self) -> ComposeResult:
title = "new alias" if self.is_new else f"edit — {self.entry.name}"
with Container(id="modal-container"):
yield Label(title, id="modal-title")
yield Label("name", classes="field-label")
yield Input(
value="" if self.is_new else self.entry.name,
placeholder="alias name (e.g. driftv)",
id="input-name",
)
yield Label("command", classes="field-label")
yield Input(
value="" if self.is_new else self.entry.command,
placeholder="command (e.g. drift verify)",
id="input-cmd",
)
yield Label("save to file", classes="field-label")
options = [(str(f.name), str(f)) for f in self.alias_files]
default = str(self.entry.source_file) if self.entry else str(self.alias_files[0])
yield Select(options, value=default, id="input-file")
with Horizontal(id="modal-buttons"):
yield Button("cancel", variant="default", id="btn-cancel")
yield Button("save", variant="primary", id="btn-save")
@on(Button.Pressed, "#btn-cancel")
def cancel(self) -> None:
self.dismiss(None)
@on(Button.Pressed, "#btn-save")
def save(self) -> None:
name = self.query_one("#input-name", Input).value.strip()
cmd = self.query_one("#input-cmd", Input).value.strip()
file_str = self.query_one("#input-file", Select).value
if not name or not cmd:
return
target_file = Path(file_str) if file_str else self.alias_files[0]
entry = AliasEntry(
name=name,
command=cmd,
source_file=target_file,
line_number=self.entry.line_number if self.entry else 0,
category=detect_category(name, cmd),
)
self.dismiss(entry)
class ConfirmModal(ModalScreen):
BINDINGS = [("escape", "dismiss", "no")]
CSS = """
ConfirmModal { align: center middle; }
#confirm-box {
width: 50; height: auto;
background: $surface;
border: thick $error;
padding: 1 2;
align: center middle;
}
#confirm-msg { text-align: center; margin-bottom: 1; }
#confirm-btns { align: center middle; height: 3; }
"""
def __init__(self, message: str):
super().__init__()
self.message = message
def compose(self) -> ComposeResult:
with Container(id="confirm-box"):
yield Label(self.message, id="confirm-msg")
with Horizontal(id="confirm-btns"):
yield Button("cancel", variant="default", id="no")
yield Button("delete", variant="error", id="yes")
@on(Button.Pressed, "#yes")
def yes(self): self.dismiss(True)
@on(Button.Pressed, "#no")
def no(self): self.dismiss(False)
class GapApplyModal(ModalScreen):
"""Preview and apply a gap suggestion."""
BINDINGS = [("escape", "dismiss", "cancel")]
CSS = """
GapApplyModal { align: center middle; }
#gap-box {
width: 70; height: auto;
background: $surface;
border: thick $warning;
padding: 1 2;
}
#gap-title { color: $warning; text-style: bold; margin-bottom: 1; }
.gap-preview {
background: $background;
border: solid $primary-darken-2;
padding: 0 1;
margin-bottom: 1;
color: $text;
}
#gap-btns { align: right middle; height: 3; margin-top: 1; }
"""
def __init__(self, category: str, name: str, cmd: str):
super().__init__()
self.category = category
self.alias_name = name
self.alias_cmd = cmd
def compose(self) -> ComposeResult:
with Container(id="gap-box"):
yield Label(f"apply gap suggestion — {self.category}", id="gap-title")
yield Label(f"alias {self.alias_name}='{self.alias_cmd}'", classes="gap-preview")
yield Label("save to file", classes="field-label")
files = list(ALIAS_DIR.glob("*.sh")) if ALIAS_DIR.exists() else [BASHRC]
opts = [(f.name, str(f)) for f in files]
if opts:
yield Select(opts, id="gap-file")
else:
yield Label(str(BASHRC))
with Horizontal(id="gap-btns"):
yield Button("cancel", variant="default", id="gap-cancel")
yield Button("apply", variant="warning", id="gap-apply")
@on(Button.Pressed, "#gap-cancel")
def cancel(self): self.dismiss(None)
@on(Button.Pressed, "#gap-apply")
def apply(self):
try:
sel = self.query_one("#gap-file", Select)
val = sel.value
target = Path(val) if (val and isinstance(val, str) and val.startswith("/")) else (self._files[0] if hasattr(self, "_files") and self._files else BASHRC)
except Exception:
target = BASHRC
entry = AliasEntry(
name=self.alias_name,
command=self.alias_cmd,
source_file=target,
category=detect_category(self.alias_name, self.alias_cmd),
)
self.dismiss(entry)
# ─────────────────────────────────────────────
# MAIN APP
# ─────────────────────────────────────────────
CSS = """
Screen {
layers: base overlay;
}
/* ── Header / Footer ── */
Header {
background: $primary-darken-3;
color: $accent;
text-style: bold;
}
Footer {
background: $primary-darken-3;
}
/* ── Tab bar ── */
TabbedContent > TabPane {
padding: 0;
}
/* ── Alias Browser ── */
#alias-outer {
layout: horizontal;
height: 100%;
}
#cat-list {
width: 18;
border-right: solid $primary-darken-2;
background: $surface-darken-1;
}
#cat-list > ListItem {
padding: 0 1;
}
#cat-list > ListItem.--highlight {
background: $primary-darken-1;
color: $accent;
}
#alias-right {
width: 1fr;
height: 100%;
layout: vertical;
}
#search-input {
margin: 0 1;
height: 3;
}
#alias-table {
height: 1fr;
}
#alias-actions {
height: 3;
align: right middle;
padding: 0 1;
border-top: solid $primary-darken-2;
}
#alias-actions Button {
margin-left: 1;
}
#alias-detail {
height: 5;
border-top: solid $primary-darken-2;
padding: 0 1;
background: $surface-darken-1;
color: $text-muted;
overflow-y: auto;
}
/* ── Ecosystem Map ── */
#eco-outer {
layout: horizontal;
height: 100%;
}
#eco-tree {
width: 30;
border-right: solid $primary-darken-2;
}
#eco-detail {
width: 1fr;
padding: 1 2;
overflow-y: auto;
}
.eco-layer-observe { color: cyan; text-style: bold; }
.eco-layer-simulate { color: yellow; text-style: bold; }
.eco-layer-execute { color: red; text-style: bold; }
.eco-layer-adapt { color: green; text-style: bold; }
.eco-tool-name { color: $accent; text-style: bold; }
.eco-desc { color: $text-muted; }
.eco-aliases { color: $success; }
.eco-status-online { color: $success; }
.eco-status-offline { color: $error; }
/* ── Shell ── */
#shell-outer {
layout: vertical;
height: 100%;
}
#shell-log {
height: 1fr;
border-bottom: solid $primary-darken-2;
background: $background;
}
#shell-input-row {
height: 3;
layout: horizontal;
align: left middle;
padding: 0 1;
background: $surface-darken-1;
}
#shell-prompt-label {
color: $success;
margin-right: 1;
width: auto;
}
#shell-input {
width: 1fr;
}
#shell-run-btn {
width: auto;
margin-left: 1;
}
#shell-clear-btn {
width: auto;
margin-left: 1;
}
/* ── Gap Analysis ── */
#gap-outer {
layout: vertical;
height: 100%;
}
#gap-filter-row {
height: 3;
layout: horizontal;
align: left middle;
padding: 0 1;
border-bottom: solid $primary-darken-2;
}
#gap-priority-sel {
width: 20;
margin-left: 1;
}
#gap-table {
height: 1fr;
}
#gap-actions {
height: 3;
align: right middle;
padding: 0 1;
border-top: solid $primary-darken-2;
}
/* ── Misc ── */
.section-header {
color: $accent;
text-style: bold;
padding: 0 0 1 0;
}
.muted { color: $text-muted; }
"""
class AliasBrowserTab(Container):
"""Tab: full alias browser with search, CRUD, category filter."""
aliases: reactive[list[AliasEntry]] = reactive([], layout=True)
selected_category: reactive[str] = reactive("all")
search_term: reactive[str] = reactive("")
def __init__(self):
super().__init__(id="alias-browser-tab")
self._all_aliases: list[AliasEntry] = []
self._alias_files: list[Path] = []
def compose(self) -> ComposeResult:
with Horizontal(id="alias-outer"):
with ScrollableContainer(id="cat-list"):
yield ListView(id="cat-listview")
with Vertical(id="alias-right"):
yield Input(placeholder="search aliases...", id="search-input")
yield DataTable(id="alias-table", zebra_stripes=True, cursor_type="row")
with Horizontal(id="alias-actions"):
yield Button("+ new", variant="primary", id="btn-new")
yield Button("edit", variant="default", id="btn-edit")
yield Button("delete", variant="error", id="btn-del")
yield Static("", id="alias-detail")
def on_mount(self) -> None:
table = self.query_one("#alias-table", DataTable)
table.add_columns("alias", "command", "category", "source")
self.reload()
def reload(self) -> None:
self._all_aliases = load_aliases()
self._alias_files = list({e.source_file for e in self._all_aliases})
# collect alias files from disk too
if ALIAS_DIR.exists():
self._alias_files = list(set(self._alias_files) | set(ALIAS_DIR.glob("*.sh")))
self._refresh_categories()
self._refresh_table()
def _refresh_categories(self) -> None:
cats = sorted(set(e.category for e in self._all_aliases))
lv = self.query_one("#cat-listview", ListView)
lv.clear()
item = ListItem(Label("all"))
item._cat = "all"
lv.append(item)
for cat in cats:
count = sum(1 for e in self._all_aliases if e.category == cat)
item = ListItem(Label(f"{cat} ({count})"))
item._cat = cat
lv.append(item)
def _filtered(self) -> list[AliasEntry]:
entries = self._all_aliases
if self.selected_category != "all":
entries = [e for e in entries if e.category == self.selected_category]
if self.search_term:
q = self.search_term.lower()
entries = [e for e in entries if q in e.name.lower() or q in e.command.lower()]
return entries
def _refresh_table(self) -> None:
table = self.query_one("#alias-table", DataTable)
table.clear()
for entry in self._filtered():
src = entry.source_file.name if entry.source_file else "?"
table.add_row(
Text(entry.name, style="bold cyan"),
Text(entry.command[:60] + ("…" if len(entry.command) > 60 else ""), style="white"),
Text(entry.category, style="yellow"),
Text(src, style="dim"),
key=entry.name,
)
@on(ListView.Selected, "#cat-listview")
def category_selected(self, event: ListView.Selected) -> None:
cat = getattr(event.item, "_cat", "all")
self.selected_category = cat
self._refresh_table()
@on(Input.Changed, "#search-input")
def search_changed(self, event: Input.Changed) -> None:
self.search_term = event.value
self._refresh_table()
@on(DataTable.RowHighlighted, "#alias-table")
def row_highlighted(self, event: DataTable.RowHighlighted) -> None:
if event.row_key:
entry = next((e for e in self._all_aliases if e.name == str(event.row_key.value)), None)
if entry:
detail = self.query_one("#alias-detail", Static)
detail.update(
f"[bold cyan]{entry.name}[/] = [white]{entry.command}[/]\n"
f"[dim]file:[/] {entry.source_file} [dim]line:[/] {entry.line_number} [dim]cat:[/] {entry.category}\n"
f"[dim]enter / double-click to run in shell[/]"
)
@on(DataTable.RowSelected, "#alias-table")
def row_selected(self, event: DataTable.RowSelected) -> None:
if event.row_key:
entry = next((e for e in self._all_aliases if e.name == str(event.row_key.value)), None)
if entry:
self._run_entry(entry)
def on_data_table_cell_selected(self, event: DataTable.CellSelected) -> None:
if event.row_key:
entry = next((e for e in self._all_aliases if e.name == str(event.row_key.value)), None)
if entry:
self._run_entry(entry)
def _run_entry(self, entry) -> None:
try:
from textual.widgets import TabbedContent, Input
self.app.query_one(TabbedContent).active = "shell"
shell = self.app.query_one(ShellTab)
shell.query_one("#shell-input", Input).value = entry.command
shell._execute(entry.command)
ShellTab.HISTORY.append(entry.command)
self.app.notify(f"running: {entry.name}", severity="information")
except Exception:
pass
def _selected_entry(self) -> AliasEntry | None:
table = self.query_one("#alias-table", DataTable)
if table.cursor_row < 0:
return None
filtered = self._filtered()
if table.cursor_row >= len(filtered):
return None
return filtered[table.cursor_row]
@on(Button.Pressed, "#btn-new")
def new_alias(self) -> None:
self.app.push_screen(
AliasEditModal(alias_files=self._alias_files),
callback=self._on_edit_result,
)
@on(Button.Pressed, "#btn-edit")
def edit_alias(self) -> None:
entry = self._selected_entry()
if not entry:
return
self.app.push_screen(
AliasEditModal(entry=entry, alias_files=self._alias_files),
callback=self._on_edit_result,
)
def _on_edit_result(self, result: AliasEntry | None) -> None:
if result:
write_alias(result)
self.reload()
self.app.notify(f"saved: {result.name}", severity="information")
@on(Button.Pressed, "#btn-del")
def delete_alias(self) -> None:
entry = self._selected_entry()
if not entry:
return
self.app.push_screen(
ConfirmModal(f"delete alias '{entry.name}'?"),
callback=lambda result: self._on_delete_result(result, entry),
)
def _on_delete_result(self, confirmed: bool | None, entry: AliasEntry) -> None:
if confirmed:
delete_alias(entry)
self.reload()
self.app.notify(f"deleted: {entry.name}", severity="warning")
class EcosystemTab(Container):
"""Tab: BANANA_TREE ecosystem map with live status probes."""
def compose(self) -> ComposeResult:
with Horizontal(id="eco-outer"):
yield Tree("BANANA_TREE", id="eco-tree")
yield ScrollableContainer(Static("", id="eco-detail"))
def on_mount(self) -> None:
tree = self.query_one("#eco-tree", Tree)
tree.root.expand()
for layer, data in ECOSYSTEM.items():
icon = data["icon"]
node = tree.root.add(f"{icon} {layer}", expand=True)
for tool_name in data["tools"]:
node.add_leaf(tool_name)
self._show_overview()
def _show_overview(self) -> None:
lines = []
lines.append("[bold cyan]BANANA_TREE ecosystem[/]\n")
for layer, data in ECOSYSTEM.items():
color = data["color"]
icon = data["icon"]
lines.append(f"[bold {color}]{icon} {layer}[/]")
for tool_name, tool in data["tools"].items():
lines.append(f" [bold]{tool_name}[/]")
lines.append(f" [dim]{tool['desc']}[/]")
if tool["aliases"]:
als = " ".join(tool["aliases"])
lines.append(f" [green]{als}[/]")
lines.append("")
self.query_one("#eco-detail", Static).update("\n".join(lines))
@on(Tree.NodeSelected, "#eco-tree")
def node_selected(self, event: Tree.NodeSelected) -> None:
label = str(event.node.label)
# check if it's a layer
for layer, data in ECOSYSTEM.items():
if label.endswith(layer):
self._show_layer(layer, data)
return
# check if it's a tool
for layer, data in ECOSYSTEM.items():
if label in data["tools"]:
self._show_tool(layer, label, data["tools"][label])
return
self._show_overview()
def _show_layer(self, layer: str, data: dict) -> None:
color = data["color"]
icon = data["icon"]
lines = [f"[bold {color}]{icon} {layer}[/]\n"]
for tool_name, tool in data["tools"].items():
lines.append(f"[bold cyan]{tool_name}[/]")
lines.append(f" {tool['desc']}")
root = os.environ.get(tool.get("root", ""), "")
if root:
lines.append(f" [dim]root:[/] {root}")
if tool["aliases"]:
lines.append(f" [green]aliases:[/] {', '.join(tool['aliases'])}")
lines.append("")
self.query_one("#eco-detail", Static).update("\n".join(lines))
@work(thread=True)
def _show_tool(self, layer: str, tool_name: str, tool: dict) -> None:
color = ECOSYSTEM[layer]["color"]
root_var = tool.get("root", "")
root_path = os.environ.get(root_var, f"${root_var} not set") if root_var else "n/a"
# probe status
status_cmd = tool.get("status_cmd", "echo 'unknown'")
try:
result = subprocess.run(
status_cmd, shell=True, capture_output=True, text=True, timeout=3
)
status = result.stdout.strip() or result.stderr.strip() or "unknown"
except Exception:
status = "timeout"
status_color = "green" if any(w in status.lower() for w in ["active", "running", "online", "local"]) else "red"
lines = [
f"[bold {color}]{tool_name}[/]\n",
f"[dim]layer:[/] {layer}",
f"[dim]desc:[/] {tool['desc']}",
f"[dim]root:[/] {root_path}",
f"[dim]status:[/] [{status_color}]{status}[/]",
"",
]
if tool["aliases"]:
lines.append("[dim]aliases:[/]")
for a in tool["aliases"]:
lines.append(f" [green]{a}[/]")
else:
lines.append("[dim]no aliases registered[/]")
self.app.call_from_thread(
self.query_one("#eco-detail", Static).update,
"\n".join(lines)
)
class ShellTab(Container):
"""Tab: live shell execution with output log."""
HISTORY: ClassVar[list[str]] = []
_hist_idx: int = -1
def compose(self) -> ComposeResult:
with Vertical(id="shell-outer"):