This repository was archived by the owner on Jan 18, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin_system.py
More file actions
1192 lines (1001 loc) · 46.6 KB
/
Copy pathplugin_system.py
File metadata and controls
1192 lines (1001 loc) · 46.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
import importlib
import importlib.util
import inspect
import logging
import asyncio
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Dict, List, Optional, Type, Callable, Union
import traceback
import json
from enum import Enum
import subprocess
import tempfile
import os
from rich.console import Console
from config_manager import config_manager
GLOBAL_DEBUG = False
logger = logging.getLogger(__name__)
console = Console()
command_registry = {}
def check_js_syntax(js_code: str, plugin_name: str, function_name: str) -> tuple[bool, str]:
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.js', delete=False, encoding='utf-8') as temp_file:
temp_file.write(js_code)
temp_file_path = temp_file.name
try:
result = subprocess.run(
['node', '--check', temp_file_path],
capture_output=True,
text=True,
timeout=5
)
os.unlink(temp_file_path)
if result.returncode == 0:
return True, ""
else:
error_msg = result.stderr.replace(temp_file_path, f"{plugin_name}.{function_name}")
return False, f"JavaScript syntax error: {error_msg.strip()}"
except subprocess.TimeoutExpired:
os.unlink(temp_file_path)
return False, f"JavaScript validation timed out for {plugin_name}.{function_name}"
except FileNotFoundError:
return True, ""
except Exception as e:
try:
os.unlink(temp_file_path)
except:
pass
return False, f"JavaScript validation error: {str(e)}"
except Exception as e:
return False, f"Syntax check error in {plugin_name}.{function_name}: {str(e)}"
class UIElementType(Enum):
TOGGLE = "toggle"
SLIDER = "slider"
BUTTON = "button"
SELECT = "select"
TEXT_INPUT = "text_input"
NUMBER_INPUT = "number_input"
COLOR_PICKER = "color_picker"
FILE_UPLOAD = "file_upload"
INPUT_WITH_BUTTON = "input_with_button"
SEARCH_WITH_RESULTS = "search_with_results"
AUTOCOMPLETE_INPUT = "autocomplete_input"
BANNER = "banner"
def plugin_command(help: str = None, js_export: bool = False, params: List[Dict[str, Any]] = None):
def decorator(func: Callable) -> Callable:
func._plugin_command = True
func._command_help = help or ""
func._js_export = js_export
func._js_params = [p["name"] if isinstance(p, dict) else p for p in (params or [])]
func._command_params = params or []
command_registry[func.__name__] = func
return func
return decorator
def js_export(params: List[str] = None):
def decorator(func: Callable) -> Callable:
func._js_export = True
func._js_params = params or []
return func
return decorator
def ui_element(
element_type: Union[UIElementType, str],
label: str = None,
description: str = None,
config_key: str = None,
default_value: Any = None,
min_value: Union[int, float] = None,
max_value: Union[int, float] = None,
step: Union[int, float] = None,
options: List[Dict[str, Any]] = None,
placeholder: str = None,
required: bool = False,
category: str = "General",
order: int = 0,
**kwargs
):
def decorator(func: Callable) -> Callable:
final_element_type = element_type
if isinstance(element_type, str):
try:
final_element_type = UIElementType(element_type.lower())
except ValueError:
raise ValueError(f"Invalid UI element type: {element_type}")
func._ui_element = True
func._ui_element_type = final_element_type
func._ui_label = label or func.__name__.replace('_', ' ').title()
func._ui_description = description or ""
func._ui_config_key = config_key or func.__name__
func._ui_default_value = default_value
func._ui_min_value = min_value
func._ui_max_value = max_value
func._ui_step = step
func._ui_options = options or []
func._ui_placeholder = placeholder or ""
func._ui_required = required
func._ui_category = category
func._ui_order = order
func._ui_properties = kwargs
return func
return decorator
def ui_toggle(label: str = None, description: str = None, config_key: str = None,
default_value: bool = False, category: str = "General", order: int = 0):
return ui_element(
UIElementType.TOGGLE,
label=label,
description=description,
config_key=config_key,
default_value=default_value,
category=category,
order=order
)
def ui_slider(label: str = None, description: str = None, config_key: str = None,
default_value: Union[int, float] = 0, min_value: Union[int, float] = 0,
max_value: Union[int, float] = 100, step: Union[int, float] = 1,
category: str = "General", order: int = 0):
return ui_element(
UIElementType.SLIDER,
label=label,
description=description,
config_key=config_key,
default_value=default_value,
min_value=min_value,
max_value=max_value,
step=step,
category=category,
order=order
)
def ui_button(label: str = None, description: str = None, category: str = "Actions",
order: int = 0, **kwargs):
return ui_element(
UIElementType.BUTTON,
label=label,
description=description,
category=category,
order=order,
**kwargs
)
def ui_select(label: str = None, description: str = None, config_key: str = None,
options: List[Dict[str, Any]] = None, default_value: Any = None,
category: str = "General", order: int = 0):
return ui_element(
UIElementType.SELECT,
label=label,
description=description,
config_key=config_key,
default_value=default_value,
options=options or [],
category=category,
order=order
)
def ui_text_input(label: str = None, description: str = None, config_key: str = None,
default_value: str = "", placeholder: str = None, required: bool = False,
category: str = "General", order: int = 0):
return ui_element(
UIElementType.TEXT_INPUT,
label=label,
description=description,
config_key=config_key,
default_value=default_value,
placeholder=placeholder or "",
required=required,
category=category,
order=order
)
def ui_number_input(label: str = None, description: str = None, config_key: str = None,
default_value: Union[int, float] = 0, min_value: Union[int, float] = None,
max_value: Union[int, float] = None, step: Union[int, float] = 1,
category: str = "General", order: int = 0):
return ui_element(
UIElementType.NUMBER_INPUT,
label=label,
description=description,
config_key=config_key,
default_value=default_value,
min_value=min_value,
max_value=max_value,
step=step,
category=category,
order=order
)
def ui_input_with_button(label: str = None, description: str = None, button_text: str = "Execute",
placeholder: str = None, category: str = "Actions", order: int = 0):
return ui_element(
UIElementType.INPUT_WITH_BUTTON,
label=label,
description=description,
placeholder=placeholder or "",
category=category,
order=order,
button_text=button_text
)
def ui_search_with_results(label: str = None, description: str = None, button_text: str = "Search",
placeholder: str = None, category: str = "Search", order: int = 0):
return ui_element(
UIElementType.SEARCH_WITH_RESULTS,
label=label,
description=description,
placeholder=placeholder or "",
category=category,
order=order,
button_text=button_text
)
def ui_autocomplete_input(label: str = None, description: str = None, button_text: str = "Execute",
placeholder: str = None, category: str = "Actions", order: int = 0):
return ui_element(
UIElementType.AUTOCOMPLETE_INPUT,
label=label,
description=description,
placeholder=placeholder or "",
category=category,
order=order,
button_text=button_text
)
def ui_banner(label: str = None, description: str = None, banner_type: str = "neutral",
category: str = "Banners", order: int = 0, **kwargs):
return ui_element(
UIElementType.BANNER,
label=label,
description=description,
category=category,
order=order,
banner_type=banner_type,
**kwargs
)
class PluginBase(ABC):
def __init__(self, config: Dict[str, Any]):
self.config = config
self.enabled = True
self.name = self.__class__.__name__
self.version = getattr(self, 'VERSION', '1.0.0')
self.description = getattr(self, 'DESCRIPTION', 'No description provided')
self.dependencies = getattr(self, 'DEPENDENCIES', [])
self.plugin_order = getattr(self, 'PLUGIN_ORDER', 0)
self.injector = None
self.plugin_manager = None
async def initialize(self, injector) -> bool:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Initializing plugin {self.name}")
self.injector = injector
if injector:
self.init_config_in_browser()
return True
@abstractmethod
async def on_game_ready(self) -> None:
pass
@abstractmethod
async def cleanup(self) -> None:
pass
@abstractmethod
async def update(self) -> None:
pass
@abstractmethod
async def on_config_changed(self, config: Dict[str, Any]) -> None:
pass
def get_commands(self) -> Dict[str, Dict[str, Any]]:
commands = {}
for attr_name in dir(self):
attr = getattr(self, attr_name)
if callable(attr) and getattr(attr, "_plugin_command", False):
commands[attr_name] = {
"func": attr,
"help": getattr(attr, "_command_help", ""),
"params": getattr(attr, "_command_params", [])
}
return commands
def get_ui_elements(self) -> Dict[str, List[Dict[str, Any]]]:
elements_by_category = {}
for attr_name in dir(self):
attr = getattr(self, attr_name)
if callable(attr) and getattr(attr, "_ui_element", False):
config_key = getattr(attr, "_ui_config_key", attr_name)
default_value = getattr(attr, "_ui_default_value", None)
current_value = config_manager.get_path(f'plugin_configs.{self.name}.{config_key}', default_value)
element_data = {
"name": attr_name,
"type": getattr(attr, "_ui_element_type", UIElementType.BUTTON).value,
"label": getattr(attr, "_ui_label", attr_name),
"description": getattr(attr, "_ui_description", ""),
"config_key": config_key,
"default_value": default_value,
"current_value": current_value,
"min_value": getattr(attr, "_ui_min_value", None),
"max_value": getattr(attr, "_ui_max_value", None),
"step": getattr(attr, "_ui_step", None),
"options": getattr(attr, "_ui_options", []),
"placeholder": getattr(attr, "_ui_placeholder", ""),
"required": getattr(attr, "_ui_required", False),
"order": getattr(attr, "_ui_order", 0),
"properties": getattr(attr, "_ui_properties", {}),
"func": attr
}
if getattr(attr, "_ui_element_type", None) == UIElementType.BANNER:
element_data["banner_type"] = getattr(attr, "_ui_properties", {}).get("banner_type", "neutral")
element_data["current_value"] = None
category = getattr(attr, "_ui_category", "General")
if category not in elements_by_category:
elements_by_category[category] = []
elements_by_category[category].append(element_data)
for category in elements_by_category:
elements_by_category[category].sort(key=lambda x: x["order"])
return elements_by_category
def get_ui_schema(self) -> Dict[str, Any]:
ui_elements = self.get_ui_elements()
plugin_category = getattr(self, 'CATEGORY', 'General')
schema = {
"plugin_info": {
"name": self.name,
"description": self.description,
"version": self.version,
"category": plugin_category,
"order": self.plugin_order
},
"categories": {}
}
for category, elements in ui_elements.items():
schema["categories"][category] = elements
return schema
def get_web_routes(self) -> List[tuple]:
return []
def get_js_exports(self) -> List[Callable]:
exports = []
for attr_name in dir(self):
attr = getattr(self, attr_name)
if (callable(attr) and
getattr(attr, "_plugin_command", False) and
getattr(attr, "_js_export", False)):
exports.append(attr)
return exports
def run_js_export(self, js_func_name: str, injector, **params) -> Any:
if not injector:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] No injector available for {js_func_name}")
return None
js_func = getattr(self, js_func_name)
js_name = js_func_name[:-3] if js_func_name.endswith('_js') else js_func_name
js_params = getattr(js_func, '_js_params', [])
args = [params.get(p, '') for p in js_params]
js_args = ', '.join(json.dumps(a) for a in args)
plugin_name = getattr(self, 'name', self.__class__.__name__)
check_expr = f"typeof window.{plugin_name}.{js_name} === 'function'"
try:
check_result = injector.evaluate(check_expr)
if not check_result.get('result', {}).get('value', False):
# Track consecutive function not found errors to detect tab reload
if not hasattr(self, '_consecutive_not_found'):
self._consecutive_not_found = 0
self._consecutive_not_found += 1
# If we get multiple consecutive "not found" errors, likely tab was reloaded
if self._consecutive_not_found >= 3:
# Only disconnect once - use a global flag to prevent multiple disconnections
import main
if not hasattr(main, '_tab_reload_disconnected'):
main._tab_reload_disconnected = True
# Debug messages only if debug is enabled
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Tab appears to have been reloaded - functions not found repeatedly")
console.print(f"[DEBUG] Auto-disconnecting injection due to tab reload detection")
# Stop the update loop
if hasattr(main, 'update_loop_stop') and main.update_loop_stop:
main.update_loop_stop.set()
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Update loop stopped due to tab reload")
# Close browser via CDP and clear injector reference
if hasattr(main, 'injector') and main.injector:
try:
# Close browser via CDP like the stop injection button does
main.injector.close_browser()
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Browser closed via CDP due to tab reload")
except Exception as e:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Error closing browser via CDP: {e}")
main.injector = None
# Always show the clean disconnect message with dark orange styling
console.print("[bold dark_orange]Tab disconnected[/bold dark_orange]")
return f"Error: Tab reloaded - injection disconnected"
else:
# Only show debug message if debug is enabled
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Function {plugin_name}.{js_name} not found in window")
return f"Error: Function {plugin_name}.{js_name} not found"
else:
# Reset counter on successful function check
if hasattr(self, '_consecutive_not_found'):
self._consecutive_not_found = 0
except Exception as e:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Error checking function {plugin_name}.{js_name}: {e}")
return f"Error checking function: {e}"
expr = f"window.{plugin_name}.{js_name}({js_args})"
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Executing: {expr}")
try:
result = injector.evaluate(expr, awaitPromise=True)
value = result.get('result', {}).get('value')
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Result: {value}")
return value
except Exception as e:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Error executing {plugin_name}.{js_name}: {e}")
return f"Error executing {plugin_name}.{js_name}: {e}"
def set_config(self, config: Dict[str, Any]) -> None:
if self.injector:
js_config = json.dumps(config)
expr = f"window.pluginConfigs['{self.name}'] = {js_config};"
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Setting config for {self.name}: {expr}")
try:
result = self.injector.evaluate(expr)
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Set config result: {result}")
except Exception as e:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Error setting config: {e}")
def init_config_in_browser(self) -> None:
if not self.injector:
return
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Initializing config for plugin {self.name}")
try:
init_expr = "window.pluginConfigs = window.pluginConfigs || {};"
self.injector.evaluate(init_expr)
current_config = config_manager.get_plugin_config(self.name)
self.set_config(current_config)
except Exception as e:
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Error initializing config: {e}")
def save_to_global_config(self, config: Dict[str, Any] = None) -> None:
plugin_config = config or self.config
config_manager.update_plugin_config(self.name, plugin_config)
self.config = config_manager.get_plugin_config(self.name)
config_manager.reload()
if self.injector:
self.set_config(self.config)
class PluginManager:
def __init__(self, plugin_names: List[str], plugin_dir: str = 'plugins'):
self.plugins: Dict[str, PluginBase] = {}
self.plugin_dir = Path(plugin_dir)
self.plugin_names = plugin_names
self.failed_plugins = set()
async def load_plugins(self, injector, plugin_configs: Dict[str, Any] = None,
global_debug: bool = False) -> None:
config_manager.reload()
if plugin_configs is None:
plugin_configs = config_manager.get_all_plugin_configs()
for plugin_name in self.plugin_names:
try:
if GLOBAL_DEBUG:
console.print(f"Loading plugin: {plugin_name}...")
await self._load_plugin(
plugin_name,
plugin_configs.get(plugin_name, {}),
injector,
global_debug=global_debug
)
if GLOBAL_DEBUG:
console.print(f"Loaded plugin: {plugin_name}")
except Exception as e:
console.print(f"[red]Failed to load plugin '{plugin_name}': {e}[/red]")
logger.error(f"Failed to load plugin '{plugin_name}': {e}")
self.failed_plugins.add(plugin_name)
if GLOBAL_DEBUG:
logger.debug(traceback.format_exc())
async def _load_plugin(self, plugin_name: str, plugin_config: Dict,
injector, global_debug: bool = False) -> None:
plugin_class = await self._load_external_plugin(plugin_name)
if not plugin_class:
raise ImportError(f"Plugin '{plugin_name}' not found in {self.plugin_dir}")
latest_config = config_manager.get_plugin_config(plugin_name)
merged_config = {**latest_config, **plugin_config}
plugin_instance = plugin_class(merged_config)
plugin_instance.plugin_manager = self
plugin_instance.global_debug = global_debug
plugin_instance.config = config_manager.get_plugin_config(plugin_name)
for dependency in getattr(plugin_instance, 'dependencies', []):
if dependency not in self.plugins:
console.print(f"[yellow]Plugin '{plugin_name}' requires '{dependency}' "
f"which is not loaded[/yellow]")
logger.warning(f"Plugin '{plugin_name}' requires '{dependency}' "
f"which is not loaded")
success = await plugin_instance.initialize(injector)
if success:
if GLOBAL_DEBUG:
console.print(f"Initialized plugin: {plugin_name}")
self.plugins[plugin_name] = plugin_instance
logger.info(f"Loaded plugin: {plugin_name}")
else:
raise RuntimeError(f"Failed to initialize plugin: {plugin_name}")
async def _load_external_plugin(self, plugin_name: str) -> Optional[Type[PluginBase]]:
if '.' in plugin_name:
subdir_name, file_name = plugin_name.split('.', 1)
plugin_file = self.plugin_dir / subdir_name / f"{file_name}.py"
else:
plugin_file = self.plugin_dir / f"{plugin_name}.py"
if not plugin_file.exists():
return None
module_name = f"plugins.{plugin_name.replace('.', '_')}"
spec = importlib.util.spec_from_file_location(module_name, plugin_file)
if not spec or not spec.loader:
return None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
for name, obj in inspect.getmembers(module):
if (inspect.isclass(obj) and
issubclass(obj, PluginBase) and
obj != PluginBase):
return obj
return None
async def initialize_all(self, injector, plugin_configs: Dict[str, Any] = None) -> None:
plugin_configs = plugin_configs or {}
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Initializing all plugins with injector")
for plugin_name in self.plugin_names:
try:
if plugin_name in self.plugins:
plugin = self.plugins[plugin_name]
plugin.injector = injector
await plugin.initialize(injector)
if GLOBAL_DEBUG:
console.print(f"Re-initialized plugin: {plugin_name}")
else:
await self._load_plugin(
plugin_name,
plugin_configs.get(plugin_name, {}),
injector
)
except Exception as e:
console.print(f"[red]Failed to initialize plugin '{plugin_name}': {e}[/red]")
logger.error(f"Failed to initialize plugin '{plugin_name}': {e}")
self.failed_plugins.add(plugin_name)
if injector:
for plugin in self.plugins.values():
try:
await plugin.on_game_ready()
if GLOBAL_DEBUG:
console.print(f"Executed on_game_ready for plugin: {plugin.name}")
except Exception as e:
logger.error(f"Error executing on_game_ready for plugin '{plugin.name}': {e}")
if GLOBAL_DEBUG:
console.print(f"[DEBUG] Plugin initialization complete. {len(self.plugins)} plugins initialized, {len(self.failed_plugins)} failed.")
async def cleanup_all(self) -> None:
for plugin_name, plugin in list(self.plugins.items()):
try:
await plugin.cleanup()
logger.info(f"Cleaned up plugin: {plugin_name}")
except Exception as e:
logger.error(f"Error cleaning up plugin '{plugin_name}': {e}")
async def update_all(self) -> None:
for plugin in self.plugins.values():
try:
await plugin.update()
except Exception as e:
logger.error(f"Error updating plugin: {e}")
def get_plugin(self, name: str) -> Optional[PluginBase]:
return self.plugins.get(name)
async def unload_plugin(self, plugin_name: str) -> None:
plugin = self.plugins.get(plugin_name)
if plugin:
try:
await plugin.cleanup()
del self.plugins[plugin_name]
logger.info(f"Unloaded plugin: {plugin_name}")
except Exception as e:
logger.error(f"Error unloading plugin '{plugin_name}': {e}")
else:
logger.warning(f"Plugin '{plugin_name}' not loaded.")
def get_all_commands(self) -> Dict[str, Dict[str, Any]]:
commands = {}
for name, plugin in self.plugins.items():
plugin_cmds = plugin.get_commands()
for cmd, meta in plugin_cmds.items():
namespaced_cmd = f"plugins.{name}.{cmd}"
commands[namespaced_cmd] = {
"func": meta["func"],
"help": meta.get("help", ""),
"params": meta.get("params", []),
"plugin": name
}
return commands
def get_command_help(self, command_name: str) -> str:
cmds = self.get_all_commands()
if command_name in cmds:
return cmds[command_name]["help"]
return "No help available."
def get_web_routes(self) -> List[tuple]:
routes = []
for plugin in self.plugins.values():
routes.extend(plugin.get_web_routes())
return routes
def get_all_ui_elements(self) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
all_ui_elements = {}
for plugin_name, plugin in self.plugins.items():
if plugin_name in self.failed_plugins:
continue
plugin_ui_elements = plugin.get_ui_elements()
if plugin_ui_elements:
plugin_schema = plugin.get_ui_schema()
all_ui_elements[plugin_name] = plugin_schema
return all_ui_elements
def get_ui_schema_for_plugin(self, plugin_name: str) -> Optional[Dict[str, Any]]:
plugin = self.plugins.get(plugin_name)
if plugin:
return plugin.get_ui_schema()
return None
def get_all_ui_schemas(self) -> Dict[str, Dict[str, Any]]:
schemas = {}
for plugin_name, plugin in self.plugins.items():
if plugin_name in self.failed_plugins:
continue
schemas[plugin_name] = plugin.get_ui_schema()
return schemas
async def execute_ui_action(self, plugin_name: str, element_name: str, value: Any = None) -> Any:
plugin = self.plugins.get(plugin_name)
if not plugin:
return {"error": f"Plugin '{plugin_name}' not found"}
ui_elements = plugin.get_ui_elements()
target_func = None
for category_elements in ui_elements.values():
for element in category_elements:
if element["name"] == element_name:
target_func = element["func"]
break
if target_func:
break
if not target_func:
return {"error": f"UI element '{element_name}' not found in plugin '{plugin_name}'"}
try:
sig = inspect.signature(target_func)
params = list(sig.parameters.keys())
if params and params[0] == 'self':
params = params[1:]
if inspect.iscoroutinefunction(target_func):
if params and len(params) > 0:
result = await target_func(value)
else:
result = await target_func()
else:
if params and len(params) > 0:
result = target_func(value)
else:
result = target_func()
if getattr(target_func, "_ui_element_type", None) == UIElementType.BANNER:
return {"success": True, "result": result}
config_key = getattr(target_func, "_ui_config_key", None)
if config_key and value is not None:
plugin.config[config_key] = value
config_manager.update_plugin_config(plugin_name, {config_key: value})
plugin.config = config_manager.get_plugin_config(plugin_name)
if plugin.plugin_manager:
try:
loop = None
try:
loop = asyncio.get_running_loop()
except RuntimeError:
pass
if loop and loop.is_running():
asyncio.create_task(plugin.plugin_manager.notify_config_changed(plugin.config, plugin_name))
else:
asyncio.run(plugin.plugin_manager.notify_config_changed(plugin.config, plugin_name))
except Exception:
pass
return {"success": True, "result": result}
except Exception as e:
return {"error": f"Error executing UI action: {str(e)}"}
async def notify_cheat_executed(self, command: str, result: Any) -> None:
for plugin in self.plugins.values():
try:
await plugin.on_cheat_executed(command, result)
except Exception as e:
logger.error(f"Error notifying plugin of cheat execution: {e}")
async def notify_config_changed(self, config: Dict[str, Any], plugin_name: str = None) -> None:
if plugin_name and plugin_name in self.plugins:
try:
await self.plugins[plugin_name].on_config_changed(config)
except Exception as e:
if GLOBAL_DEBUG:
logger.error(f"Error notifying plugin of config change: {e}")
elif plugin_name is None:
for name, plugin in self.plugins.items():
try:
await plugin.on_config_changed(plugin.config)
except Exception as e:
if GLOBAL_DEBUG:
logger.error(f"Error notifying plugin of config change: {e}")
def collect_all_plugin_js(self) -> str:
js_code, _ = self.collect_all_plugin_js_with_sizes()
return js_code
def collect_all_plugin_js_with_sizes(self) -> tuple[str, dict[str, int]]:
js_code = ""
plugin_sizes = {}
syntax_errors = []
plugin_results = []
debug = any(
hasattr(plugin, 'config') and plugin.config.get('debug', False)
for plugin in self.plugins.values()
)
if debug:
tmp_js_dir = Path(__file__).parent / 'core' / 'tmp_js'
tmp_js_dir.mkdir(exist_ok=True)
compatibility_layer = """
if (!window.__compatibility_layer_initialized__) {
window.__compatibility_layer_initialized__ = true;
const originalWindow = window;
window = new Proxy(window, {
get: function(target, prop) {
if (typeof prop === 'string' && !target.hasOwnProperty(prop)) {
for (const pluginName in target) {
if (target[pluginName] && typeof target[pluginName] === 'object' && target[pluginName][prop]) {
return target[pluginName][prop];
}
}
}
return target[prop];
}
});
}
"""
js_code += compatibility_layer
for plugin in self.plugins.values():
plugin_js = ""
plugin_name = getattr(plugin, 'name', plugin.__class__.__name__)
plugin_has_errors = False
plugin_error_details = []
js_function_count = 0
namespace_init = f"window.{plugin_name} = window.{plugin_name} || {{}};\n"
js_code += namespace_init
plugin_js += namespace_init
for attr_name in dir(plugin):
if attr_name.endswith('_js'):
func = getattr(plugin, attr_name)
if callable(func) and getattr(func, '_js_export', False):
js_params = getattr(func, '_js_params', None)
sig = inspect.signature(func)
if js_params and len(js_params) > 0:
param_list = ", ".join(js_params)
bound_args = []
for p in js_params:
if p in sig.parameters and sig.parameters[p].default != inspect.Parameter.empty:
bound_args.append(sig.parameters[p].default)
else:
bound_args.append('')
js_body = func(*bound_args)
else:
params = list(sig.parameters.keys())[1:]
param_list = ", ".join(params) if params else ""
bound_args = []
for p in params:
param = sig.parameters[p]
if param.default != inspect.Parameter.empty:
bound_args.append(param.default)
else:
bound_args.append('')
js_body = func(*bound_args)
js_name = attr_name[:-3]
is_valid, error_msg = check_js_syntax(js_body, plugin_name, js_name)
if not is_valid:
syntax_errors.append(f"[{plugin_name}.{js_name}] {error_msg}")
plugin_has_errors = True
plugin_error_details.append(f" • {js_name}: {error_msg}")
continue
js_function_count += 1
wrapped_js_body = f"""
try {{
await window.__idleon_wait_for_game_ready();
{js_body}
}} catch (e) {{
console.error('[{js_name}] Error:', e);
return `Error: ${{e.message}}`;
}}
"""
js_func_code = f"window.{plugin_name}.{js_name} = async function({param_list}) {{\n{wrapped_js_body}\n}}\n"
js_code += js_func_code
plugin_js += js_func_code
plugin_sizes[plugin_name] = len(plugin_js)
if debug and plugin_js:
plugin_file = tmp_js_dir / f"{plugin.__class__.__name__}_js_dump.js"
with open(plugin_file, 'w', encoding='utf-8') as f:
f.write(plugin_js)
plugin_results.append({
'name': plugin_name,
'success': not plugin_has_errors,
'error_details': plugin_error_details,
'js_size': len(plugin_js),
'function_count': js_function_count
})
if plugin_has_errors:
self.failed_plugins.add(plugin_name)
console.print(f"[DEBUG] Added {plugin_name} to failed_plugins due to JS syntax errors")
from rich.table import Table
from rich.panel import Panel
summary_table = Table(title="Plugin JavaScript Generation Summary", show_lines=True)
summary_table.add_column("Plugin Name", style="bold green")
summary_table.add_column("Status", style="cyan")
summary_table.add_column("JS Size (KB)", style="magenta")
summary_table.add_column("Functions", style="yellow")
total_size = 0
total_functions = 0
successful_plugins = 0
failed_plugins = 0
for result in plugin_results:
status_icon = "✅" if result['success'] else "❌"
status_text = "Success" if result['success'] else "Failed"
js_size_kb = f"{result['js_size']/1024:.2f}"
func_count = result.get('function_count', 0)
summary_table.add_row(
result['name'],
f"{status_icon} {status_text}",
js_size_kb,
str(func_count)
)
total_size += result['js_size']
total_functions += func_count
if result['success']:
successful_plugins += 1
else:
failed_plugins += 1
summary_table.add_row("", "", "", "")
summary_table.add_row(
"TOTAL",