janito 3.2.0__py3-none-any.whl → 3.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. janito/README.md +0 -3
  2. janito/cli/chat_mode/bindings.py +0 -26
  3. janito/cli/chat_mode/session.py +1 -12
  4. janito/cli/chat_mode/shell/commands/security/allowed_sites.py +33 -47
  5. janito/cli/cli_commands/list_plugins.py +43 -52
  6. janito/cli/core/getters.py +0 -3
  7. janito/cli/core/model_guesser.py +24 -40
  8. janito/cli/main_cli.py +12 -9
  9. janito/cli/prompt_core.py +9 -20
  10. janito/drivers/openai/driver.py +0 -1
  11. janito/drivers/zai/driver.py +0 -1
  12. janito/hello.txt +0 -0
  13. janito/i18n/it.py +46 -46
  14. janito/llm/agent.py +16 -32
  15. janito/llm/auth_utils.py +5 -14
  16. janito/llm/driver.py +0 -8
  17. janito/plugins/__init__.py +12 -31
  18. janito/plugins/auto_loader.py +11 -12
  19. janito/plugins/auto_loader_fixed.py +11 -12
  20. janito/{plugin_system → plugins}/base.py +2 -5
  21. janito/plugins/builtin.py +1 -15
  22. janito/plugins/core_adapter.py +11 -89
  23. janito/plugins/core_loader.py +120 -0
  24. janito/plugins/core_loader_fixed.py +125 -0
  25. janito/plugins/discovery.py +5 -5
  26. janito/plugins/discovery_core.py +9 -14
  27. janito/plugins/manager.py +1 -1
  28. janito/providers/__init__.py +0 -1
  29. janito/tools/__init__.py +7 -31
  30. janito/tools/adapters/__init__.py +1 -6
  31. janito/tools/adapters/local/__init__.py +70 -7
  32. janito/{plugins/tools → tools/adapters/local}/ask_user.py +3 -3
  33. janito/{plugins/tools → tools/adapters/local}/create_file.py +6 -6
  34. janito/{plugins/tools → tools/adapters/local}/fetch_url.py +3 -3
  35. janito/{plugins/tools → tools/adapters/local}/replace_text_in_file.py +4 -4
  36. janito/{plugins/tools → tools/adapters/local}/show_image.py +6 -15
  37. janito/{plugins/core/imagedisplay/tools → tools/adapters/local}/show_image_grid.py +5 -13
  38. janito/tools/function_adapter.py +65 -0
  39. janito/tools/loop_protection_decorator.py +117 -114
  40. {janito-3.2.0.dist-info → janito-3.4.0.dist-info}/METADATA +2 -1
  41. {janito-3.2.0.dist-info → janito-3.4.0.dist-info}/RECORD +85 -156
  42. janito/cli/cli_commands/check_tools.py +0 -212
  43. janito/llm/cancellation_manager.py +0 -63
  44. janito/llm/enter_cancellation.py +0 -107
  45. janito/plugin_system/__init__.py +0 -10
  46. janito/plugin_system/core_loader.py +0 -217
  47. janito/plugin_system/core_loader_fixed.py +0 -225
  48. janito/plugins/core/__init__.py +0 -7
  49. janito/plugins/core/codeanalyzer/__init__.py +0 -43
  50. janito/plugins/core/filemanager/__init__.py +0 -124
  51. janito/plugins/core/filemanager/tools/create_file.py +0 -87
  52. janito/plugins/core/filemanager/tools/replace_text_in_file.py +0 -270
  53. janito/plugins/core/imagedisplay/__init__.py +0 -14
  54. janito/plugins/core/imagedisplay/plugin.py +0 -51
  55. janito/plugins/core/imagedisplay/tools/__init__.py +0 -1
  56. janito/plugins/core/imagedisplay/tools/show_image.py +0 -83
  57. janito/plugins/core/system/__init__.py +0 -23
  58. janito/plugins/dev/__init__.py +0 -7
  59. janito/plugins/dev/pythondev/__init__.py +0 -37
  60. janito/plugins/dev/visualization/__init__.py +0 -23
  61. janito/plugins/example_plugin.py +0 -108
  62. janito/plugins/tools/__init__.py +0 -10
  63. janito/plugins/tools/copy_file.py +0 -87
  64. janito/plugins/tools/core_tools_plugin.py +0 -87
  65. janito/plugins/tools/create_directory.py +0 -70
  66. janito/plugins/tools/decorators.py +0 -19
  67. janito/plugins/tools/delete_text_in_file.py +0 -134
  68. janito/plugins/tools/find_files.py +0 -143
  69. janito/plugins/tools/get_file_outline/__init__.py +0 -7
  70. janito/plugins/tools/get_file_outline/core.py +0 -122
  71. janito/plugins/tools/get_file_outline/java_outline.py +0 -47
  72. janito/plugins/tools/get_file_outline/markdown_outline.py +0 -14
  73. janito/plugins/tools/get_file_outline/python_outline.py +0 -303
  74. janito/plugins/tools/get_file_outline/search_outline.py +0 -36
  75. janito/plugins/tools/move_file.py +0 -131
  76. janito/plugins/tools/open_html_in_browser.py +0 -51
  77. janito/plugins/tools/open_url.py +0 -37
  78. janito/plugins/tools/python_code_run.py +0 -172
  79. janito/plugins/tools/python_command_run.py +0 -171
  80. janito/plugins/tools/python_file_run.py +0 -172
  81. janito/plugins/tools/read_chart.py +0 -259
  82. janito/plugins/tools/read_files.py +0 -58
  83. janito/plugins/tools/remove_directory.py +0 -55
  84. janito/plugins/tools/remove_file.py +0 -58
  85. janito/plugins/tools/run_bash_command.py +0 -183
  86. janito/plugins/tools/run_powershell_command.py +0 -218
  87. janito/plugins/tools/search_text/__init__.py +0 -7
  88. janito/plugins/tools/search_text/core.py +0 -205
  89. janito/plugins/tools/search_text/match_lines.py +0 -67
  90. janito/plugins/tools/search_text/pattern_utils.py +0 -73
  91. janito/plugins/tools/search_text/traverse_directory.py +0 -145
  92. janito/plugins/tools/show_image_grid.py +0 -85
  93. janito/plugins/tools/validate_file_syntax/__init__.py +0 -7
  94. janito/plugins/tools/validate_file_syntax/core.py +0 -114
  95. janito/plugins/tools/validate_file_syntax/css_validator.py +0 -35
  96. janito/plugins/tools/validate_file_syntax/html_validator.py +0 -100
  97. janito/plugins/tools/validate_file_syntax/jinja2_validator.py +0 -50
  98. janito/plugins/tools/validate_file_syntax/js_validator.py +0 -27
  99. janito/plugins/tools/validate_file_syntax/json_validator.py +0 -6
  100. janito/plugins/tools/validate_file_syntax/markdown_validator.py +0 -109
  101. janito/plugins/tools/validate_file_syntax/ps1_validator.py +0 -32
  102. janito/plugins/tools/validate_file_syntax/python_validator.py +0 -5
  103. janito/plugins/tools/validate_file_syntax/xml_validator.py +0 -11
  104. janito/plugins/tools/validate_file_syntax/yaml_validator.py +0 -6
  105. janito/plugins/tools/view_file.py +0 -172
  106. janito/plugins/ui/__init__.py +0 -7
  107. janito/plugins/ui/userinterface/__init__.py +0 -16
  108. janito/plugins/ui/userinterface/tools/ask_user.py +0 -110
  109. janito/plugins/web/__init__.py +0 -7
  110. janito/plugins/web/webtools/__init__.py +0 -33
  111. janito/plugins/web/webtools/tools/fetch_url.py +0 -458
  112. janito/providers/together/__init__.py +0 -1
  113. janito/providers/together/model_info.py +0 -69
  114. janito/providers/together/provider.py +0 -108
  115. janito/tools/cli_initializer.py +0 -88
  116. janito/tools/initialize.py +0 -70
  117. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/copy_file.py +0 -0
  118. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/create_directory.py +0 -0
  119. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/delete_text_in_file.py +0 -0
  120. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/find_files.py +0 -0
  121. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/get_file_outline/__init__.py +0 -0
  122. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/get_file_outline/core.py +0 -0
  123. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/get_file_outline/java_outline.py +0 -0
  124. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/get_file_outline/markdown_outline.py +0 -0
  125. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/get_file_outline/python_outline.py +0 -0
  126. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/get_file_outline/search_outline.py +0 -0
  127. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/move_file.py +0 -0
  128. /janito/{plugins/web/webtools/tools → tools/adapters/local}/open_html_in_browser.py +0 -0
  129. /janito/{plugins/web/webtools/tools → tools/adapters/local}/open_url.py +0 -0
  130. /janito/{plugins/dev/pythondev/tools → tools/adapters/local}/python_code_run.py +0 -0
  131. /janito/{plugins/dev/pythondev/tools → tools/adapters/local}/python_command_run.py +0 -0
  132. /janito/{plugins/dev/pythondev/tools → tools/adapters/local}/python_file_run.py +0 -0
  133. /janito/{plugins/dev/visualization/tools → tools/adapters/local}/read_chart.py +0 -0
  134. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/read_files.py +0 -0
  135. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/remove_directory.py +0 -0
  136. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/remove_file.py +0 -0
  137. /janito/{plugins/core/system/tools → tools/adapters/local}/run_bash_command.py +0 -0
  138. /janito/{plugins/core/system/tools → tools/adapters/local}/run_powershell_command.py +0 -0
  139. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/search_text/__init__.py +0 -0
  140. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/search_text/core.py +0 -0
  141. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/search_text/match_lines.py +0 -0
  142. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/search_text/pattern_utils.py +0 -0
  143. /janito/{plugins/core/codeanalyzer/tools → tools/adapters/local}/search_text/traverse_directory.py +0 -0
  144. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/__init__.py +0 -0
  145. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/core.py +0 -0
  146. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/css_validator.py +0 -0
  147. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/html_validator.py +0 -0
  148. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/jinja2_validator.py +0 -0
  149. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/js_validator.py +0 -0
  150. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/json_validator.py +0 -0
  151. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/markdown_validator.py +0 -0
  152. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/ps1_validator.py +0 -0
  153. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/python_validator.py +0 -0
  154. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/xml_validator.py +0 -0
  155. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/validate_file_syntax/yaml_validator.py +0 -0
  156. /janito/{plugins/core/filemanager/tools → tools/adapters/local}/view_file.py +0 -0
  157. {janito-3.2.0.dist-info → janito-3.4.0.dist-info}/WHEEL +0 -0
  158. {janito-3.2.0.dist-info → janito-3.4.0.dist-info}/entry_points.txt +0 -0
  159. {janito-3.2.0.dist-info → janito-3.4.0.dist-info}/licenses/LICENSE +0 -0
  160. {janito-3.2.0.dist-info → janito-3.4.0.dist-info}/top_level.txt +0 -0
@@ -1,212 +0,0 @@
1
- """
2
- CLI Command: Check all registered tools for signature validation and availability
3
- """
4
-
5
- import inspect
6
- import sys
7
- from typing import Dict, List, Tuple, Any
8
-
9
-
10
- def _validate_tool_signature(tool_instance) -> Tuple[bool, List[str]]:
11
- """Validate the signature of a tool's run method."""
12
- errors = []
13
-
14
- if not hasattr(tool_instance, "run"):
15
- errors.append("Missing 'run' method")
16
- return False, errors
17
-
18
- try:
19
- sig = inspect.signature(tool_instance.run)
20
- except ValueError as e:
21
- errors.append(f"Invalid signature: {e}")
22
- return False, errors
23
-
24
- # Basic signature validation - just check if it's callable
25
- if not callable(getattr(tool_instance, "run")):
26
- errors.append("'run' method is not callable")
27
-
28
- return len(errors) == 0, errors
29
-
30
-
31
- def _check_tool_availability(tool_instance) -> Tuple[bool, List[str]]:
32
- """Check if a tool is available for use."""
33
- errors = []
34
-
35
- # Check if tool has required attributes
36
- required_attrs = ["tool_name"]
37
- for attr in required_attrs:
38
- if not hasattr(tool_instance, attr):
39
- errors.append(f"Missing required attribute: {attr}")
40
-
41
- # Check description (optional for now)
42
- if not hasattr(tool_instance, "description"):
43
- pass # Allow missing description
44
-
45
- # Check permissions
46
- if not hasattr(tool_instance, "permissions"):
47
- # Function-based tools use permissions from function decorators
48
- pass # Allow missing permissions for function-based tools
49
- else:
50
- perms = tool_instance.permissions
51
- if (
52
- not hasattr(perms, "read")
53
- or not hasattr(perms, "write")
54
- or not hasattr(perms, "execute")
55
- ):
56
- errors.append("Invalid permissions structure")
57
-
58
- return len(errors) == 0, errors
59
-
60
-
61
- def _get_tool_status_summary(
62
- tools: List[Any], disabled_tools: List[str]
63
- ) -> Dict[str, Any]:
64
- """Get a comprehensive status summary for all tools."""
65
- summary = {
66
- "total": len(tools),
67
- "available": 0,
68
- "disabled": 0,
69
- "invalid": 0,
70
- "details": [],
71
- }
72
-
73
- for tool in tools:
74
- tool_name = getattr(tool, "tool_name", str(tool))
75
-
76
- # Check if disabled
77
- is_disabled = tool_name in disabled_tools
78
-
79
- # Validate signature and availability
80
- sig_valid, sig_errors = _validate_tool_signature(tool)
81
- avail_valid, avail_errors = _check_tool_availability(tool)
82
-
83
- status = {
84
- "name": tool_name,
85
- "disabled": is_disabled,
86
- "signature_valid": sig_valid,
87
- "available": avail_valid,
88
- "signature_errors": sig_errors,
89
- "availability_errors": avail_errors,
90
- }
91
-
92
- summary["details"].append(status)
93
-
94
- if is_disabled:
95
- summary["disabled"] += 1
96
- elif not sig_valid or not avail_valid:
97
- summary["invalid"] += 1
98
- else:
99
- summary["available"] += 1
100
-
101
- return summary
102
-
103
-
104
- def _print_check_results(console, summary: Dict[str, Any], verbose: bool = False):
105
- """Print the tool check results in a formatted way."""
106
- from rich.table import Table
107
- from rich.panel import Panel
108
- from rich.text import Text
109
-
110
- # Overall summary
111
- summary_text = Text()
112
- summary_text.append(f"Total tools: {summary['total']}", style="cyan")
113
- summary_text.append(" | ")
114
- summary_text.append(f"Available: {summary['available']}", style="green")
115
- summary_text.append(" | ")
116
- summary_text.append(f"Disabled: {summary['disabled']}", style="yellow")
117
- summary_text.append(" | ")
118
- summary_text.append(f"Invalid: {summary['invalid']}", style="red")
119
-
120
- console.print(Panel(summary_text, title="Tool Check Summary", style="bold"))
121
-
122
- # Always show the table for check-tools
123
- table = Table(title="Tool Details", show_header=True, header_style="bold")
124
- table.add_column("Tool", style="cyan", no_wrap=True)
125
- table.add_column("Status", style="green")
126
- table.add_column("Issues", style="red")
127
-
128
- for detail in summary["details"]:
129
- name = detail["name"]
130
-
131
- if detail["disabled"]:
132
- status = "[yellow]Disabled[/yellow]"
133
- issues = "-"
134
- elif not detail["available"] or not detail["signature_valid"]:
135
- status = "[red]Invalid[/red]"
136
- all_issues = detail["signature_errors"] + detail["availability_errors"]
137
- issues = "\n".join(all_issues)
138
- else:
139
- status = "[green]Available[/green]"
140
- issues = "-"
141
-
142
- table.add_row(name, status, issues)
143
-
144
- console.print(table)
145
-
146
-
147
- def handle_check_tools(args=None):
148
- """Handle the --check-tools CLI command."""
149
- from janito.tools.adapters.local.adapter import LocalToolsAdapter
150
- import janito.tools # Ensure all tools are registered
151
-
152
- # Load disabled tools from config
153
- from janito.tools.disabled_tools import DisabledToolsState
154
- from janito.config import config
155
-
156
- disabled_str = config.get("disabled_tools", "")
157
- if disabled_str:
158
- DisabledToolsState.set_disabled_tools(disabled_str)
159
- disabled_tools = DisabledToolsState.get_disabled_tools()
160
-
161
- # Initialize tools properly using the same approach as list_tools.py
162
- from janito.tools.adapters.local.adapter import LocalToolsAdapter
163
- from janito.tools.tool_base import ToolPermissions
164
- import janito.tools # Ensure all tools are registered
165
-
166
- read = getattr(args, "read", False) if args else False
167
- write = getattr(args, "write", False) if args else False
168
- execute = getattr(args, "exec", False) if args else False
169
- if not (read or write or execute):
170
- read = write = execute = True
171
- from janito.tools.permissions import set_global_allowed_permissions
172
-
173
- set_global_allowed_permissions(
174
- ToolPermissions(read=read, write=write, execute=execute)
175
- )
176
-
177
- # Load disabled tools from config
178
- from janito.tools.disabled_tools import DisabledToolsState
179
- from janito.config import config
180
-
181
- disabled_str = config.get("disabled_tools", "")
182
- if disabled_str:
183
- DisabledToolsState.set_disabled_tools(disabled_str)
184
- disabled_tools = DisabledToolsState.get_disabled_tools()
185
-
186
- # Initialize tools using the same method as list_tools.py
187
- from janito.tools.initialize import initialize_tools
188
-
189
- registry = initialize_tools()
190
-
191
- # Get actual tool instances
192
- tool_instances = []
193
- for name, tool_info in registry._tools.items():
194
- if "instance" in tool_info:
195
- tool_instances.append(tool_info["instance"])
196
-
197
- if not tool_instances:
198
- print("No tools registered.")
199
- return
200
-
201
- from rich.console import Console
202
-
203
- console = Console()
204
-
205
- verbose = getattr(args, "verbose", False) if args else False
206
-
207
- summary = _get_tool_status_summary(tool_instances, disabled_tools)
208
- _print_check_results(console, summary, verbose=verbose)
209
-
210
- # Exit with error code if there are invalid tools
211
- if summary["invalid"] > 0:
212
- sys.exit(1)
@@ -1,63 +0,0 @@
1
- """
2
- Global cancellation manager for LLM requests.
3
- Provides a centralized way to cancel ongoing requests.
4
- """
5
-
6
- import threading
7
- from typing import Optional
8
-
9
-
10
- class CancellationManager:
11
- """Manages cancellation of LLM requests across the application."""
12
-
13
- def __init__(self):
14
- self._current_cancel_event: Optional[threading.Event] = None
15
- self._lock = threading.Lock()
16
- self._keyboard_cancellation = None
17
-
18
- def start_new_request(self) -> threading.Event:
19
- """Start a new request and return its cancellation event."""
20
- with self._lock:
21
- # Create new cancellation event for this request
22
- self._current_cancel_event = threading.Event()
23
-
24
- # Start keyboard monitoring
25
- from janito.llm.enter_cancellation import get_enter_cancellation
26
-
27
- self._keyboard_cancellation = get_enter_cancellation()
28
- self._keyboard_cancellation.start_monitoring(self._current_cancel_event)
29
-
30
- return self._current_cancel_event
31
-
32
- def cancel_current_request(self) -> bool:
33
- """Cancel the current request if one is active."""
34
- with self._lock:
35
- if self._current_cancel_event is not None:
36
- self._current_cancel_event.set()
37
- return True
38
- return False
39
-
40
- def get_current_cancel_event(self) -> Optional[threading.Event]:
41
- """Get the current cancellation event."""
42
- with self._lock:
43
- return self._current_cancel_event
44
-
45
- def clear_current_request(self):
46
- """Clear the current request cancellation event."""
47
- with self._lock:
48
- if self._keyboard_cancellation:
49
- self._keyboard_cancellation.stop_monitoring()
50
- self._keyboard_cancellation = None
51
- self._current_cancel_event = None
52
-
53
-
54
- # Global cancellation manager instance
55
- _global_manager = None
56
-
57
-
58
- def get_cancellation_manager() -> CancellationManager:
59
- """Get the global cancellation manager instance."""
60
- global _global_manager
61
- if _global_manager is None:
62
- _global_manager = CancellationManager()
63
- return _global_manager
@@ -1,107 +0,0 @@
1
- """
2
- Enter key cancellation for LLM requests.
3
- Allows pressing Enter to cancel ongoing requests.
4
- """
5
-
6
- import threading
7
- import sys
8
- import time
9
- from typing import Optional
10
-
11
-
12
- class EnterCancellation:
13
- """Handles Enter key cancellation of LLM requests."""
14
-
15
- def __init__(self):
16
- self._cancel_event: Optional[threading.Event] = None
17
- self._listener_thread: Optional[threading.Thread] = None
18
- self._listening = False
19
-
20
- def start_monitoring(self, cancel_event: threading.Event):
21
- """Start monitoring for Enter key to cancel the request."""
22
- if self._listening:
23
- return
24
-
25
- self._cancel_event = cancel_event
26
- self._listening = True
27
-
28
- self._listener_thread = threading.Thread(
29
- target=self._monitor_enter_key, daemon=True
30
- )
31
- self._listener_thread.start()
32
-
33
- def stop_monitoring(self):
34
- """Stop monitoring for keyboard input."""
35
- self._listening = False
36
- if self._listener_thread and self._listener_thread.is_alive():
37
- self._listener_thread.join(timeout=0.1)
38
-
39
- def _monitor_enter_key(self):
40
- """Monitor for Enter key press."""
41
- try:
42
- self._handle_key_monitoring()
43
- except Exception:
44
- # Silently handle any errors
45
- pass
46
-
47
- def _handle_key_monitoring(self):
48
- """Handle the actual key monitoring logic."""
49
- import sys
50
- import select
51
-
52
- try:
53
- import msvcrt # Windows-specific keyboard input
54
-
55
- self._monitor_windows_keys()
56
- except ImportError:
57
- self._monitor_unix_keys()
58
-
59
- def _monitor_windows_keys(self):
60
- """Monitor keys on Windows systems."""
61
- import msvcrt
62
-
63
- while (
64
- self._listening and self._cancel_event and not self._cancel_event.is_set()
65
- ):
66
- try:
67
- if msvcrt.kbhit():
68
- char = msvcrt.getch()
69
- if char in [b"\r", b"\n"]:
70
- if self._cancel_event:
71
- self._cancel_event.set()
72
- break
73
- else:
74
- time.sleep(0.05)
75
- except (IOError, OSError):
76
- break
77
-
78
- def _monitor_unix_keys(self):
79
- """Monitor keys on Unix-like systems."""
80
- import sys
81
- import select
82
-
83
- while (
84
- self._listening and self._cancel_event and not self._cancel_event.is_set()
85
- ):
86
- try:
87
- if sys.stdin in select.select([sys.stdin], [], [], 0.05)[0]:
88
- char = sys.stdin.read(1)
89
- if char in ["\r", "\n"]:
90
- if self._cancel_event:
91
- self._cancel_event.set()
92
- break
93
- time.sleep(0.05)
94
- except:
95
- time.sleep(0.05)
96
-
97
-
98
- # Global instance
99
- _global_enter_cancellation = None
100
-
101
-
102
- def get_enter_cancellation() -> EnterCancellation:
103
- """Get the global Enter cancellation instance."""
104
- global _global_enter_cancellation
105
- if _global_enter_cancellation is None:
106
- _global_enter_cancellation = EnterCancellation()
107
- return _global_enter_cancellation
@@ -1,10 +0,0 @@
1
- """
2
- Plugin System Core Package
3
-
4
- This package provides the foundational plugin system architecture.
5
- It should not depend on any specific plugin implementations.
6
- """
7
-
8
- from .base import Plugin, PluginMetadata, PluginResource
9
-
10
- __all__ = ["Plugin", "PluginMetadata", "PluginResource"]
@@ -1,217 +0,0 @@
1
- """
2
- Fixed core plugin loader.
3
-
4
- This module provides a working implementation to load core plugins
5
- by directly using the Plugin base class properly.
6
- """
7
-
8
- import importlib
9
- import importlib.util
10
- import sys
11
- from pathlib import Path
12
- from typing import Optional, List, Type
13
-
14
- from janito.plugin_system.base import Plugin, PluginMetadata
15
- from janito.tools.tool_base import ToolBase, ToolPermissions
16
-
17
-
18
- class CorePlugin(Plugin):
19
- """Working core plugin implementation."""
20
-
21
- def __init__(self, name: str, description: str, tools: list):
22
- self._plugin_name = name
23
- self._description = description
24
- self._tools = tools
25
- self._tool_classes = []
26
- super().__init__() # Call super after setting attributes
27
-
28
- def get_metadata(self) -> PluginMetadata:
29
- return PluginMetadata(
30
- name=self._plugin_name,
31
- version="1.0.0",
32
- description=self._description,
33
- author="Janito",
34
- license="MIT",
35
- )
36
-
37
- def get_tools(self) -> List[Type[ToolBase]]:
38
- return self._tool_classes
39
-
40
- def _create_tool_class(self, func):
41
- """Create a ToolBase class from a function."""
42
- resolved_tool_name = getattr(func, "tool_name", func.__name__)
43
-
44
- # Create a proper tool class with explicit parameters and documentation
45
- import inspect
46
- from typing import get_type_hints
47
-
48
- func_sig = inspect.signature(func)
49
- type_hints = get_type_hints(func)
50
-
51
- # Build parameter definitions for the run method
52
- param_defs = []
53
- param_docs = []
54
- for name, param in func_sig.parameters.items():
55
- type_hint = type_hints.get(name, str)
56
- if param.default == inspect.Parameter.empty:
57
- param_defs.append(f"{name}: {type_hint.__name__}")
58
- else:
59
- param_defs.append(f"{name}: {type_hint.__name__} = {repr(param.default)}")
60
-
61
- # Add parameter documentation
62
- param_docs.append(f" {name}: {type_hint.__name__} - Parameter {name}")
63
-
64
- # Get function docstring or create one
65
- func_doc = func.__doc__ or f"Execute {resolved_tool_name} tool"
66
-
67
- # Create the tool class with proper signature and documentation
68
- exec_globals = {
69
- 'ToolBase': ToolBase,
70
- 'ToolPermissions': ToolPermissions,
71
- 'func': func,
72
- 'inspect': inspect,
73
- 'str': str,
74
- }
75
-
76
- param_docs_str = '\n'.join(param_docs)
77
-
78
- class_def = f'''
79
- class DynamicTool(ToolBase):
80
- """
81
- {func_doc}
82
-
83
- Parameters:
84
- {param_docs_str}
85
-
86
- Returns:
87
- str: Execution result
88
- """
89
- tool_name = "{resolved_tool_name}"
90
- permissions = ToolPermissions(read=True, write=True, execute=True)
91
-
92
- def __init__(self):
93
- super().__init__()
94
-
95
- def run(self, {', '.join(param_defs)}) -> str:
96
- kwargs = locals()
97
- sig = inspect.signature(func)
98
-
99
- # Filter kwargs to only include parameters the function accepts
100
- filtered_kwargs = {{}}
101
- for name, param in sig.parameters.items():
102
- if name in kwargs and kwargs[name] is not None:
103
- filtered_kwargs[name] = kwargs[name]
104
-
105
- result = func(**filtered_kwargs)
106
- return str(result) if result is not None else ""
107
- '''
108
-
109
- exec(class_def, exec_globals)
110
- return exec_globals['DynamicTool']
111
-
112
- return DynamicTool
113
-
114
- def initialize(self):
115
- """Initialize by creating tool classes."""
116
- self._tool_classes = []
117
- for tool_func in self._tools:
118
- if callable(tool_func):
119
- tool_class = self._create_tool_class(tool_func)
120
- self._tool_classes.append(tool_class)
121
-
122
-
123
- def load_core_plugin(plugin_name: str) -> Optional[Plugin]:
124
- """
125
- Load a core plugin by name.
126
-
127
- Args:
128
- plugin_name: Name of the plugin (e.g., 'core.filemanager')
129
-
130
- Returns:
131
- Plugin instance if loaded successfully
132
- """
133
- try:
134
- # Parse plugin name
135
- if "." not in plugin_name:
136
- return None
137
-
138
- parts = plugin_name.split(".")
139
- if len(parts) != 2:
140
- return None
141
-
142
- package_name, submodule_name = parts
143
-
144
- # Handle imagedisplay specially
145
- if plugin_name == "core.imagedisplay":
146
- # Import the actual plugin class
147
- try:
148
- # Use dynamic import to avoid circular dependency
149
- plugin_module = importlib.import_module(
150
- "janito.plugins.core.imagedisplay.plugin"
151
- )
152
- return plugin_module.ImageDisplayPlugin()
153
- except ImportError as e:
154
- print(f"Failed to load imagedisplay: {e}")
155
- return None
156
-
157
- # Build path to plugin
158
- plugin_path = (
159
- Path("janito/plugins") / package_name / submodule_name / "__init__.py"
160
- )
161
- if not plugin_path.exists():
162
- return None
163
-
164
- # Load the module
165
- spec = importlib.util.spec_from_file_location(plugin_name, plugin_path)
166
- if spec is None or spec.loader is None:
167
- return None
168
-
169
- module = importlib.util.module_from_spec(spec)
170
- spec.loader.exec_module(module)
171
-
172
- # Get plugin info
173
- name = getattr(module, "__plugin_name__", plugin_name)
174
- description = getattr(
175
- module, "__plugin_description__", f"Core plugin: {plugin_name}"
176
- )
177
- tools = getattr(module, "__plugin_tools__", [])
178
-
179
- if not tools:
180
- return None
181
-
182
- # Filter out None values and ensure all tools have tool_name
183
- valid_tools = []
184
- for tool in tools:
185
- if tool is not None:
186
- if not hasattr(tool, "tool_name"):
187
- tool.tool_name = tool.__name__
188
- valid_tools.append(tool)
189
-
190
- if not valid_tools:
191
- return None
192
-
193
- # Create plugin
194
- plugin = CorePlugin(name, description, valid_tools)
195
- plugin.initialize()
196
- return plugin
197
-
198
- except Exception as e:
199
- print(f"Error loading core plugin {plugin_name}: {e}")
200
- return None
201
-
202
-
203
- def get_core_plugins() -> list:
204
- """Get list of all available core plugins."""
205
- core_plugins = [
206
- "core.filemanager",
207
- "core.codeanalyzer",
208
- "core.system",
209
- "core.imagedisplay",
210
- "dev.pythondev",
211
- "dev.visualization",
212
- "ui.userinterface",
213
- "web.webtools",
214
- ]
215
-
216
- # All core plugins are always available
217
- return core_plugins