-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathframework.py
More file actions
1848 lines (1580 loc) · 70.9 KB
/
Copy pathframework.py
File metadata and controls
1848 lines (1580 loc) · 70.9 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/python3
import platform
import os
import importlib
import re
from colorama import Fore, Style, init
import time
import sys
from eula import check_eula
from prompts import get_prompt, prompt_selector, STYLES, load_prompt_style
from prompt_colors import get_kali_prompt, color_selector, COLOR_SCHEMES
from config import config_selector, load_config, get_config, _init_colors, _C_ACCENT, _C_WHITE, _C_GREEN, _C_RED, _C_DIM, _C_GRAY, _C_BORDER, _C_SECTION, _C_CYAN
import getpass
# Initialize colorama for cross-platform ANSI support
init()
# Syntax highlighting + fast history + completion via prompt_toolkit
try:
from prompt_toolkit import PromptSession
from prompt_toolkit.lexers import Lexer
from prompt_toolkit.history import FileHistory
from prompt_toolkit.formatted_text import ANSI
from prompt_toolkit.styles import Style as PTStyle
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.shortcuts import CompleteStyle
from prompt_toolkit.filters import Condition
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.keys import Keys
HAS_PROMPT_TOOLKIT = True
except ImportError:
HAS_PROMPT_TOOLKIT = False
# readline fallback for history (no syntax highlighting)
try:
import readline
HAS_READLINE = True
except ImportError:
HAS_READLINE = False
# variables de formateo y colores
subrayado = '\033[4m'
morado = '\033[38;5;135m'
# sistema operativo y arquitectura
sistema = platform.system()
arquitectura = platform.architecture()[0]
# variables de estética
usuario = getpass.getuser()
# Navigation path (list of segments, e.g. ["pentesting", "red", "dos"])
nav_path = []
# variable de bucle principal
is_running = True
# Command history
HISTORY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config", "cmd_history.txt")
MAX_HISTORY = 200
# =================== CATEGORY TREE ===================
CATEGORY_TREE = {
"pentesting": {
"_desc": "Herramientas de seguridad ofensiva",
"_help": "Suite de herramientas de seguridad ofensiva para pruebas de penetración. Incluye módulos para ataques de red, WiFi, web y Active Directory.",
"red": {
"_desc": "Ataques de red",
"_help": "Herramientas para ataques a nivel de red local: denegación de servicio, man-in-the-middle, escaneo de puertos y captura de tráfico.",
"dos": {
"_desc": "Denegacion de servicio",
"_help": "Herramientas de denegación de servicio que permiten bloquear o interrumpir la conectividad de objetivos en la red.",
"internetblocker": {
"_desc": "Bloquea el acceso a internet de uno o más objetivos",
"_tool": "pentesting.red.dos.internetblocker",
},
},
"mitm": {"_desc": "Man in the middle"},
"scan": {"_desc": "Escaneo de red"},
"sniff": {"_desc": "Captura de trafico"},
},
"wifi": {
"_desc": "Ataques inalambricos",
"_help": "Suite para ataques orientados a redes inalámbricas: desautenticación, captura de handshakes y auditoría de redes WiFi.",
"deauth": {
"_desc": "Desautenticacion",
"_help": "Ataques de desautenticación WiFi para desconectar clientes de puntos de acceso.",
"deauther": {
"_desc": "Desconecta a uno o varios clientes de la red wifi seleccionada",
"_tool": "pentesting.wifi.deauth.deauther",
},
},
},
"web": {"_desc": "Pentesting web"},
"ad": {"_desc": "Active Directory"},
},
"osint": {"_desc": "Inteligencia de fuentes abiertas"},
}
def get_node(path_list):
"""Traverse the tree and return the node at the given path."""
node = CATEGORY_TREE
for segment in path_list:
if segment in node and isinstance(node[segment], dict):
node = node[segment]
else:
return None
return node
def get_children(path_list):
"""Return a dict of {name: node} for children of the current path, excluding _keys."""
node = get_node(path_list)
if node is None:
return {}
return {k: v for k, v in node.items() if not k.startswith("_") and isinstance(v, dict)}
def is_tool_node(node):
"""Check if a node is a tool (has _tool key)."""
return node is not None and "_tool" in node
# =================== VALID COMMANDS ===================
BASE_COMMANDS = {'help', 'clear', 'set-style', 'set-prompt', 'config', 'ai', 'salir', 'exit', 'ls', 'cd', 'run', 'x'}
def _get_valid_commands():
"""Return the set of valid commands at the current tree position."""
return BASE_COMMANDS.copy()
def _is_valid_command(text):
"""Check if text starts with a valid framework command."""
stripped = text.strip()
if not stripped:
return False
first_word = stripped.split()[0]
if first_word in BASE_COMMANDS:
return True
return False
# =================== PATH RESOLUTION ===================
def _resolve_path(path_str):
"""Resolve a path string to a nav_path list. Returns (path_list, error_msg)."""
if not path_str or path_str == '/':
return [], None
if path_str.startswith('/'):
parts = [p for p in path_str.split('/') if p]
else:
parts = list(nav_path)
for segment in path_str.split('/'):
if segment == '..':
if parts:
parts.pop()
else:
return None, "Ya estás en el directorio raíz"
elif segment and segment != '.':
parts.append(segment)
node = get_node(parts)
if node is None:
return None, f"La ruta '/{'/'.join(parts)}' no existe"
if is_tool_node(node):
return None, f"'{'/'.join(parts)}' es una herramienta, no una categoría (usa 'run')"
return parts, None
def _collect_tools_at_path(path_list):
"""Recursively collect all tool names accessible from path_list."""
result = {}
children = get_children(path_list)
for name, child in children.items():
if is_tool_node(child):
result[name] = child.get("_desc", "tool")
else:
result.update(_collect_tools_at_path(path_list + [name]))
return result
def _collect_direct_tools(path_list):
"""Collect only tools that are direct children of the current path."""
result = {}
children = get_children(path_list)
for name, child in children.items():
if is_tool_node(child):
result[name] = child.get("_desc", "tool")
return result
# =================== PROMPT_TOOLKIT SETUP ===================
_pt_session = None
if HAS_PROMPT_TOOLKIT:
class FrameworkLexer(Lexer):
def lex_document(self, document):
def get_line(lineno):
text = document.lines[lineno]
stripped = text.lstrip()
if not stripped:
return [('', text)]
tokens = []
leading = text[:len(text) - len(stripped)]
if leading:
tokens.append(('', leading))
cmd_class = 'class:command' if get_config("command_highlight") != "off" else ''
first_space = stripped.find(' ')
if first_space == -1:
if stripped in BASE_COMMANDS:
tokens.append((cmd_class, stripped))
elif any(cmd.startswith(stripped) for cmd in BASE_COMMANDS):
tokens.append(('class:partial', stripped))
else:
tokens.append(('', stripped))
else:
cmd = stripped[:first_space]
args = stripped[first_space + 1:]
if cmd in BASE_COMMANDS:
tokens.append((cmd_class, cmd))
elif any(c.startswith(cmd) for c in BASE_COMMANDS):
tokens.append(('class:partial', cmd))
else:
tokens.append(('', cmd))
tokens.append(('', ' '))
if cmd == 'cd':
tokens.extend(self._lex_cd_path(args))
elif cmd == 'run':
tokens.extend(self._lex_run_arg(args))
elif cmd == 'help':
tokens.extend(self._lex_help_arg(args))
elif cmd == 'ai':
# AI prompt — just show as dim text
tokens.append(('class:partial', args))
else:
tokens.append(('', args))
return tokens
return get_line
def _lex_help_arg(self, arg):
"""Tokenize a help argument (module path or tool name)."""
tokens = []
if not arg:
return tokens
# Check if it's a path with /
if '/' in arg:
parts = arg.split('/')
for i, part in enumerate(parts):
test_path = parts[:i + 1]
node = get_node(test_path)
if node and not is_tool_node(node):
tokens.append(('class:path-segment', part))
elif node and is_tool_node(node):
tokens.append(('class:tool-name', part))
else:
tokens.append(('class:partial', part))
if i < len(parts) - 1:
tokens.append(('class:path-segment', '/'))
else:
# Single word — could be a module or tool at current path
tools = _collect_tools_at_path(nav_path)
if arg in tools:
tokens.append(('class:tool-name', arg))
else:
children = get_children(nav_path)
top_children = get_children([])
found = False
for name in children:
if name == arg and not is_tool_node(children[name]):
tokens.append(('class:path-segment', arg))
found = True
break
if not found:
for name in top_children:
if name == arg and not is_tool_node(top_children[name]):
tokens.append(('class:path-segment', arg))
found = True
break
if not found and any(name.startswith(arg) for name in tools):
tokens.append(('class:partial', arg))
elif not found:
tokens.append(('', arg))
return tokens
def _lex_cd_path(self, path_str):
"""Tokenize a cd path argument with per-segment validation."""
tokens = []
if not path_str:
return tokens
if path_str.startswith('/'):
current_path = []
else:
current_path = list(nav_path)
parts = path_str.split('/')
for i, part in enumerate(parts):
is_last = (i == len(parts) - 1)
if not part:
if i == 0:
tokens.append(('class:path-segment', '/'))
elif not is_last:
if len(current_path) > 0 and get_node(current_path) is not None:
tokens.append(('class:path-segment', '/'))
else:
tokens.append(('', '/'))
continue
if part == '..':
tokens.append((cmd_class, part))
if current_path:
current_path.pop()
elif part == '.':
tokens.append(('', part))
else:
test_path = current_path + [part]
node = get_node(test_path)
if node is not None and not is_tool_node(node):
tokens.append(('class:path-segment', part))
current_path.append(part)
elif node is not None and is_tool_node(node):
tokens.append(('class:partial', part))
else:
tokens.append(('class:partial', part))
if not is_last:
if len(current_path) > 0 and get_node(current_path) is not None:
tokens.append(('class:path-segment', '/'))
else:
tokens.append(('', '/'))
return tokens
def _lex_run_arg(self, tool_arg):
"""Tokenize a run tool-name or path argument."""
tokens = []
if not tool_arg:
return tokens
direct_tools = _collect_direct_tools(nav_path)
# Split path part from flag/arg part at first space
first_space = tool_arg.find(' ')
if first_space != -1:
path_part = tool_arg[:first_space]
rest_part = tool_arg[first_space:]
else:
path_part = tool_arg
rest_part = ""
# Path-based: tokenize segment by segment
if '/' in path_part:
if path_part.startswith('/'):
current_path = []
else:
current_path = list(nav_path)
parts = path_part.split('/')
for i, part in enumerate(parts):
is_last = (i == len(parts) - 1)
if not part:
if i == 0:
tokens.append(('class:path-segment', '/'))
elif not is_last:
if len(current_path) > 0 and get_node(current_path) is not None:
tokens.append(('class:path-segment', '/'))
else:
tokens.append(('', '/'))
continue
test_path = current_path + [part]
node = get_node(test_path)
if node is not None and is_tool_node(node):
tokens.append(('class:tool-name', part))
current_path.append(part)
elif node is not None and not is_tool_node(node):
tokens.append(('class:path-segment', part))
current_path.append(part)
else:
tokens.append(('class:partial', part))
if not is_last:
if len(current_path) > 0 and get_node(current_path) is not None:
tokens.append(('class:path-segment', '/'))
else:
tokens.append(('', '/'))
elif path_part in direct_tools:
tokens.append(('class:tool-name', path_part))
elif any(name.startswith(path_part) for name in direct_tools):
tokens.append(('class:partial', path_part))
elif path_part:
tokens.append(('', path_part))
# Flags/args after the path
if rest_part:
i = 0
while i < len(rest_part):
if rest_part[i] == ' ':
j = i
while j < len(rest_part) and rest_part[j] == ' ':
j += 1
tokens.append(('', rest_part[i:j]))
i = j
elif rest_part[i] == '-':
j = i
while j < len(rest_part) and rest_part[j] != ' ':
j += 1
tokens.append(('', rest_part[i:j]))
i = j
else:
j = i
while j < len(rest_part) and rest_part[j] != ' ':
j += 1
tokens.append(('', rest_part[i:j]))
i = j
return tokens
_PT_STYLE = PTStyle.from_dict({
'command': 'ansiblue bold',
'path-segment': 'ansiwhite bold',
'partial': '',
'tool-name': 'ansigreen bold',
})
class FrameworkCompleter(Completer):
def get_completions(self, document, complete_event):
text = document.text_before_cursor
stripped = text.lstrip()
if not stripped:
for cmd in sorted(BASE_COMMANDS):
yield Completion(cmd, start_position=0, display_meta="command")
return
first_space = stripped.find(' ')
if first_space == -1:
partial = stripped
for cmd in sorted(BASE_COMMANDS):
if cmd.startswith(partial) and cmd != partial:
yield Completion(cmd, start_position=-len(partial), display_meta="command")
return
cmd = stripped[:first_space]
arg_part = stripped[first_space + 1:]
if cmd == 'cd':
yield from self._complete_cd_path(arg_part)
elif cmd == 'run':
yield from self._complete_run_tool(arg_part)
elif cmd == 'help':
yield from self._complete_help(arg_part)
def _complete_cd_path(self, arg_part):
"""Complete cd argument with category paths."""
if arg_part.startswith('/'):
current_path = []
remaining = arg_part[1:]
else:
current_path = list(nav_path)
remaining = arg_part
segments = [s for s in remaining.split('/') if s]
trailing_slash = remaining.endswith('/')
if segments:
for seg in segments[:-1] if not trailing_slash else segments:
if seg == '..':
if current_path:
current_path.pop()
elif seg and seg != '.':
current_path.append(seg)
node = get_node(current_path)
if node is None or is_tool_node(node):
return
if trailing_slash:
partial = ''
else:
partial = segments[-1]
if partial == '..':
yield Completion('..', start_position=-len(partial), display_meta="parent")
return
children = get_children(current_path)
for name, child in sorted(children.items()):
if name.startswith(partial) and not is_tool_node(child):
yield Completion(
name + '/',
start_position=-len(partial),
display_meta=child.get("_desc", "category")
)
else:
children = get_children(current_path)
for name, child in sorted(children.items()):
if not is_tool_node(child):
yield Completion(
name + '/',
start_position=0,
display_meta=child.get("_desc", "category")
)
def _complete_run_tool(self, arg_part):
"""Complete run argument with tool names and paths."""
partial = arg_part.lstrip()
# If arg contains /, complete as a path
if '/' in partial:
if partial.startswith('/'):
current_path = []
remaining = partial[1:]
else:
current_path = list(nav_path)
remaining = partial
segments = [s for s in remaining.split('/') if s]
trailing_slash = remaining.endswith('/')
if segments:
for seg in segments[:-1] if not trailing_slash else segments:
if seg and seg != '.':
current_path.append(seg)
node = get_node(current_path)
if node is None or is_tool_node(node):
return
if trailing_slash:
last_partial = ''
else:
last_partial = segments[-1]
children = get_children(current_path)
for name, child in sorted(children.items()):
if name.startswith(last_partial):
if is_tool_node(child):
yield Completion(
name,
start_position=-len(last_partial),
display_meta=f"tool: {child.get('_desc', '')}"
)
else:
yield Completion(
name + '/',
start_position=-len(last_partial),
display_meta=child.get("_desc", "category")
)
else:
# Just "/" typed — complete from root
children = get_children([])
for name, child in sorted(children.items()):
if not is_tool_node(child):
yield Completion(
name + '/',
start_position=0,
display_meta=child.get("_desc", "category")
)
return
# No / — complete with direct tools in current dir
tools = _collect_direct_tools(nav_path)
for name, desc in sorted(tools.items()):
if name.startswith(partial) and name != partial:
yield Completion(name, start_position=-len(partial), display_meta=desc)
def _complete_help(self, arg_part):
"""Complete help argument with module paths and tool names."""
partial = arg_part.lstrip()
if not partial:
# Show both modules and tools at current path
children = get_children(nav_path)
for name, child in sorted(children.items()):
if is_tool_node(child):
yield Completion(name, start_position=0, display_meta=f"tool: {child.get('_desc', '')}")
else:
yield Completion(name + '/', start_position=0, display_meta=child.get("_desc", "category"))
# Also show top-level modules
top_children = get_children([])
for name, child in sorted(top_children.items()):
if not is_tool_node(child):
yield Completion(name + '/', start_position=0, display_meta=child.get("_desc", "category"))
else:
# Try to complete as a path
if '/' in partial:
# Path-style completion (e.g., "red/dos")
parts = partial.split('/')
last = parts[-1]
parent = parts[:-1]
test_path, _ = _resolve_path('/'.join(parent)) if parent else (list(nav_path), None)
if test_path is None:
test_path = list(nav_path)
node = get_node(test_path)
if node and not is_tool_node(node):
children = get_children(test_path)
for name, child in sorted(children.items()):
if name.startswith(last):
if is_tool_node(child):
yield Completion(name, start_position=-len(last), display_meta=f"tool: {child.get('_desc', '')}")
else:
yield Completion(name + '/', start_position=-len(last), display_meta=child.get("_desc", "category"))
else:
# Single segment: match modules and tools at current path
children = get_children(nav_path)
for name, child in sorted(children.items()):
if name.startswith(partial) and name != partial:
if is_tool_node(child):
yield Completion(name, start_position=-len(partial), display_meta=f"tool: {child.get('_desc', '')}")
else:
yield Completion(name + '/', start_position=-len(partial), display_meta=child.get("_desc", "category"))
# Also match top-level modules
top_children = get_children([])
for name, child in sorted(top_children.items()):
if name.startswith(partial) and name != partial and not is_tool_node(child):
yield Completion(name + '/', start_position=-len(partial), display_meta=child.get("_desc", "category"))
class MinimalCompleter(Completer):
"""Tab completes like bash: prefix then list below, no dropdown menu."""
def get_completions(self, document, complete_event):
text = document.text_before_cursor
stripped = text.lstrip()
if not stripped:
return
first_space = stripped.find(' ')
if first_space == -1:
partial = stripped
for cmd in sorted(BASE_COMMANDS):
if cmd.startswith(partial) and cmd != partial:
yield Completion(cmd, start_position=-len(partial))
return
cmd = stripped[:first_space]
arg_part = stripped[first_space + 1:]
if cmd == 'cd':
for c in FrameworkCompleter()._complete_cd_path(arg_part):
yield Completion(c.text, start_position=c.start_position)
elif cmd == 'run':
for c in FrameworkCompleter()._complete_run_tool(arg_part):
yield Completion(c.text, start_position=c.start_position)
elif cmd == 'help':
for c in FrameworkCompleter()._complete_help(arg_part):
yield Completion(c.text, start_position=c.start_position)
def _get_prompt_session():
global _pt_session
if _pt_session is None:
autocompletion = get_config("autocompletion")
completer = None
if autocompletion == "full":
completer = FrameworkCompleter()
elif autocompletion == "minimal":
completer = MinimalCompleter()
# Key bindings for spotlight (Ctrl+Space)
kb = KeyBindings()
@kb.add(Keys.ControlSpace)
def _spotlight_handler(event):
"""Save state and exit prompt so main loop can open spotlight."""
global _spotlight_pending, _spotlight_saved_text
_spotlight_pending = True
_spotlight_saved_text = event.app.current_buffer.text
event.app.exit()
# Minimal mode: block Tab when completions visible (prevent cycling)
if autocompletion == "minimal":
def _completions_visible():
try:
from prompt_toolkit import get_app
return get_app().current_buffer.complete_state is not None
except Exception:
return False
@kb.add(Keys.Tab, filter=Condition(_completions_visible))
def _minimal_tab_block(event):
pass # Prevent cycling through completions
cwt = autocompletion == "full"
cstyle = CompleteStyle.READLINE_LIKE if autocompletion == "minimal" else CompleteStyle.COLUMN
_pt_session = PromptSession(
history=FileHistory(HISTORY_FILE),
style=_PT_STYLE,
lexer=FrameworkLexer(),
completer=completer,
complete_while_typing=cwt,
complete_style=cstyle,
key_bindings=kb,
)
return _pt_session
def _reset_prompt_session():
"""Force recreation of the prompt session (e.g. after config change)."""
global _pt_session
_pt_session = None
# =================== SPOTLIGHT (Ctrl+Space) ===================
def _collect_all_items():
"""Collect all tools and directories from CATEGORY_TREE for spotlight search."""
items = []
_walk_collect(CATEGORY_TREE, [], items)
return items
def _walk_collect(node, path, items):
"""Recursively collect all tools and directories."""
for key, val in node.items():
if key.startswith("_"):
continue
if isinstance(val, dict):
current_path = path + [key]
path_str = "/".join(current_path)
desc = val.get("_desc", "")
if "_tool" in val:
items.append({
"name": key,
"path": path_str,
"type": "tool",
"desc": desc,
})
else:
items.append({
"name": key,
"path": path_str,
"type": "dir",
"desc": desc,
})
_walk_collect(val, current_path, items)
_ALL_SPOTLIGHT_ITEMS = None
def _get_spotlight_items():
"""Get cached spotlight items."""
global _ALL_SPOTLIGHT_ITEMS
if _ALL_SPOTLIGHT_ITEMS is None:
_ALL_SPOTLIGHT_ITEMS = _collect_all_items()
return _ALL_SPOTLIGHT_ITEMS
def _spotlight_filter(query):
"""Filter spotlight items by query. Returns list of matching items."""
items = _get_spotlight_items()
if not query:
return items[:20]
q = query.lower()
results = []
for item in items:
name = item["name"].lower()
path = item["path"].lower()
if q in name or q in path:
results.append(item)
return results[:20]
def _spotlight_autocomplete(query, items):
"""Get autocomplete suggestion for current query."""
if not query or not items:
return ""
q = query.lower()
for item in items:
name = item["name"]
if name.lower().startswith(q) and name.lower() != q:
return name[len(q):]
return ""
def _show_spotlight(stdscr):
"""Curses-based spotlight search. Returns (path, auto_run) or None.
auto_run is True when the user pressed Ctrl+Enter (execute command directly).
"""
import curses
# Enable modifyOtherKeys mode 2 so Ctrl+Enter sends distinct sequence
sys.stdout.write("\x1b[>4;2m")
sys.stdout.flush()
def _exit(result=None):
"""Disable modifyOtherKeys and return from spotlight."""
curses.curs_set(0)
sys.stdout.write("\x1b[>4;0m")
sys.stdout.flush()
return result
curses.curs_set(2)
_init_colors(stdscr)
items = _get_spotlight_items()
if not items:
return None
input_text = ""
cursor_pos = 0
selected_idx = 0
scroll_offset = 0
ac_suffix = ""
max_results = 10
def _update():
nonlocal selected_idx, scroll_offset, ac_suffix
f = _spotlight_filter(input_text)
selected_idx = min(selected_idx, max(0, len(f) - 1))
ac_suffix = _spotlight_autocomplete(input_text, f)
if selected_idx < scroll_offset:
scroll_offset = selected_idx
elif selected_idx >= scroll_offset + max_results:
scroll_offset = selected_idx - max_results + 1
def _draw():
stdscr.clear()
h, w = stdscr.getmaxyx()
box_w = min(76, w - 4)
filtered = _spotlight_filter(input_text)
result_count = min(len(filtered), max_results)
box_h = 3 + 1 + 1 + max(result_count, 1) + 1 + 2
box_x = max(0, (w - box_w) // 2)
box_y = max(0, (h - box_h) // 2)
# Top border
stdscr.addstr(box_y, box_x, "+" + "-" * (box_w - 2) + "+",
curses.color_pair(_C_BORDER))
# Title
title = " BUSCAR "
tpad = (box_w - 2 - len(title)) // 2
row_y = box_y + 1
stdscr.addstr(row_y, box_x, "|", curses.color_pair(_C_BORDER))
stdscr.addstr(row_y, box_x + 1, " " * (box_w - 2), curses.color_pair(_C_DIM))
stdscr.addstr(row_y, box_x + 1 + tpad, title,
curses.color_pair(_C_ACCENT) | curses.A_BOLD)
stdscr.addstr(row_y, box_x + box_w - 1, "|", curses.color_pair(_C_BORDER))
# Separator
row_y += 1
stdscr.addstr(row_y, box_x, "+" + "-" * (box_w - 2) + "+",
curses.color_pair(_C_BORDER))
# Search field row
row_y += 1
stdscr.addstr(row_y, box_x, "|", curses.color_pair(_C_BORDER))
stdscr.addstr(row_y, box_x + 1, " " * (box_w - 2), curses.color_pair(_C_DIM))
field_w = box_w - 6
display_typed = input_text[:field_w]
if ac_suffix and len(display_typed) + len(ac_suffix) <= field_w:
stdscr.addstr(row_y, box_x + 3, display_typed,
curses.color_pair(_C_WHITE) | curses.A_BOLD)
stdscr.addstr(row_y, box_x + 3 + len(display_typed), ac_suffix,
curses.color_pair(_C_BORDER))
else:
stdscr.addstr(row_y, box_x + 3, display_typed,
curses.color_pair(_C_WHITE) | curses.A_BOLD)
# Cursor
cx = box_x + 3 + min(cursor_pos, field_w)
try:
stdscr.move(row_y, cx)
except curses.error:
pass
stdscr.addstr(row_y, box_x + box_w - 1, "|", curses.color_pair(_C_BORDER))
# Separator
row_y += 1
stdscr.addstr(row_y, box_x, "+" + "-" * (box_w - 2) + "+",
curses.color_pair(_C_BORDER))
# Results
row_y += 1
if not filtered:
stdscr.addstr(row_y, box_x, "|", curses.color_pair(_C_BORDER))
stdscr.addstr(row_y, box_x + 1, " " * (box_w - 2), curses.color_pair(_C_DIM))
stdscr.addstr(row_y, box_x + 3, "Sin resultados",
curses.color_pair(_C_DIM))
stdscr.addstr(row_y, box_x + box_w - 1, "|", curses.color_pair(_C_BORDER))
row_y += 1
else:
visible = filtered[scroll_offset:scroll_offset + max_results]
for i, item in enumerate(visible):
real_idx = scroll_offset + i
is_sel = (real_idx == selected_idx)
itype = item["type"]
stdscr.addstr(row_y, box_x, "|",
curses.color_pair(_C_ACCENT) | curses.A_BOLD if is_sel
else curses.color_pair(_C_BORDER))
stdscr.addstr(row_y, box_x + 1, " " * (box_w - 2),
curses.color_pair(_C_ACCENT) | curses.A_BOLD if is_sel
else curses.color_pair(_C_DIM))
indicator = " >" if itype == "tool" else " /"
name = item["name"]
path = item["path"]
if is_sel:
stdscr.addstr(row_y, box_x + 2, indicator,
curses.color_pair(_C_ACCENT) | curses.A_BOLD)
stdscr.addstr(row_y, box_x + 5, name,
curses.color_pair(_C_WHITE) | curses.A_BOLD)
else:
stdscr.addstr(row_y, box_x + 2, indicator,
curses.color_pair(_C_DIM))
stdscr.addstr(row_y, box_x + 5, name,
curses.color_pair(_C_GREEN if itype == "tool" else _C_GRAY))
# Path on right side
path_display = path
px = box_x + box_w - 2 - len(path_display) - 2
if px > box_x + 5 + len(name):
stdscr.addstr(row_y, px, path_display,
curses.color_pair(_C_CYAN if is_sel else _C_DIM))
stdscr.addstr(row_y, box_x + box_w - 1, "|",
curses.color_pair(_C_ACCENT) | curses.A_BOLD if is_sel
else curses.color_pair(_C_BORDER))
row_y += 1
# Controls + bottom border
stdscr.addstr(row_y, box_x, "+" + "-" * (box_w - 2) + "+",
curses.color_pair(_C_BORDER))
row_y += 1
stdscr.addstr(row_y, box_x, "|", curses.color_pair(_C_BORDER))
stdscr.addstr(row_y, box_x + 1, " " * (box_w - 2), curses.color_pair(_C_BORDER))
ctrl = " Tab:completar Up/Dn:navegar Enter:seleccionar Alt+Enter:ejecutar Esc:cerrar"
stdscr.addstr(row_y, box_x + 1, ctrl, curses.color_pair(_C_DIM))
stdscr.addstr(row_y, box_x + box_w - 1, "|", curses.color_pair(_C_BORDER))
row_y += 1
stdscr.addstr(row_y, box_x, "+" + "-" * (box_w - 2) + "+",
curses.color_pair(_C_BORDER))
stdscr.refresh()
_update()
_draw()
# Disable keypad so curses doesn't consume escape sequences
# We'll parse arrow keys and Ctrl+Enter sequences manually
stdscr.keypad(False)
# CSI sequence patterns we care about
_CSI_UP = [91, 65] # ESC [ A
_CSI_DOWN = [91, 66] # ESC [ B
_CSI_RIGHT = [91, 67] # ESC [ C
_CSI_LEFT = [91, 68] # ESC [ D
_CSI_HOME = [91, 72] # ESC [ H
_CSI_END = [91, 70] # ESC [ F
_CSI_DELETE = [91, 51, 126] # ESC [ 3 ~
_CSI_CTRL_ENTER_U = [91, 49, 51, 59, 53, 117] # CSI 13;5u
_CSI_CTRL_ENTER_T = [91, 50, 55, 59, 53, 59, 49, 51, 126] # CSI 27;5;13~
_CSI_CTRL_C_U = [91, 57, 57, 59, 53, 117] # CSI 99;5u
while True:
try:
key = stdscr.getch()
except KeyboardInterrupt:
key = 3
if key == 27: # Escape or CSI sequence
stdscr.nodelay(True)
seq = []
try:
while True:
ch = stdscr.getch()
if ch == -1:
break
seq.append(ch)
except Exception:
pass
stdscr.nodelay(False)