janito 3.4.0__py3-none-any.whl → 3.5.1__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 (159) hide show
  1. janito/README.md +3 -0
  2. janito/cli/chat_mode/bindings.py +50 -0
  3. janito/cli/chat_mode/session.py +12 -1
  4. janito/cli/chat_mode/shell/commands/multi.py +5 -0
  5. janito/cli/chat_mode/shell/commands/security/allowed_sites.py +47 -33
  6. janito/cli/cli_commands/check_tools.py +212 -0
  7. janito/cli/cli_commands/list_plugins.py +52 -43
  8. janito/cli/core/getters.py +3 -0
  9. janito/cli/core/model_guesser.py +40 -24
  10. janito/cli/main_cli.py +9 -12
  11. janito/cli/prompt_core.py +47 -9
  12. janito/cli/rich_terminal_reporter.py +2 -2
  13. janito/drivers/openai/driver.py +1 -0
  14. janito/drivers/zai/driver.py +1 -0
  15. janito/i18n/it.py +46 -46
  16. janito/llm/agent.py +32 -16
  17. janito/llm/auth_utils.py +14 -5
  18. janito/llm/cancellation_manager.py +63 -0
  19. janito/llm/driver.py +8 -0
  20. janito/llm/enter_cancellation.py +107 -0
  21. janito/plugin_system/__init__.py +10 -0
  22. janito/{plugins → plugin_system}/base.py +5 -2
  23. janito/plugin_system/core_loader.py +217 -0
  24. janito/plugin_system/core_loader_fixed.py +225 -0
  25. janito/plugins/__init__.py +31 -12
  26. janito/plugins/auto_loader.py +12 -11
  27. janito/plugins/auto_loader_fixed.py +12 -11
  28. janito/plugins/builtin.py +15 -1
  29. janito/plugins/core/__init__.py +7 -0
  30. janito/plugins/core/codeanalyzer/__init__.py +43 -0
  31. janito/plugins/core/filemanager/__init__.py +124 -0
  32. janito/plugins/core/filemanager/tools/create_file.py +87 -0
  33. janito/plugins/core/filemanager/tools/replace_text_in_file.py +270 -0
  34. janito/plugins/core/imagedisplay/__init__.py +14 -0
  35. janito/plugins/core/imagedisplay/plugin.py +51 -0
  36. janito/plugins/core/imagedisplay/tools/__init__.py +1 -0
  37. janito/plugins/core/imagedisplay/tools/show_image.py +83 -0
  38. janito/{tools/adapters/local → plugins/core/imagedisplay/tools}/show_image_grid.py +13 -5
  39. janito/plugins/core/system/__init__.py +23 -0
  40. janito/plugins/core/system/tools/run_bash_command.py +204 -0
  41. janito/plugins/core/system/tools/run_powershell_command.py +234 -0
  42. janito/plugins/core_adapter.py +89 -11
  43. janito/plugins/dev/__init__.py +7 -0
  44. janito/plugins/dev/pythondev/__init__.py +37 -0
  45. janito/plugins/dev/visualization/__init__.py +23 -0
  46. janito/plugins/discovery.py +5 -5
  47. janito/plugins/discovery_core.py +14 -9
  48. janito/plugins/example_plugin.py +108 -0
  49. janito/plugins/manager.py +1 -1
  50. janito/plugins/tools/__init__.py +10 -0
  51. janito/{tools/adapters/local → plugins/tools}/ask_user.py +3 -3
  52. janito/plugins/tools/copy_file.py +87 -0
  53. janito/plugins/tools/core_tools_plugin.py +87 -0
  54. janito/plugins/tools/create_directory.py +70 -0
  55. janito/{tools/adapters/local → plugins/tools}/create_file.py +6 -6
  56. janito/plugins/tools/decorators.py +19 -0
  57. janito/plugins/tools/delete_text_in_file.py +134 -0
  58. janito/{tools/adapters/local → plugins/tools}/fetch_url.py +3 -3
  59. janito/plugins/tools/find_files.py +143 -0
  60. janito/plugins/tools/get_file_outline/__init__.py +7 -0
  61. janito/plugins/tools/get_file_outline/core.py +122 -0
  62. janito/plugins/tools/get_file_outline/java_outline.py +47 -0
  63. janito/plugins/tools/get_file_outline/markdown_outline.py +14 -0
  64. janito/plugins/tools/get_file_outline/python_outline.py +303 -0
  65. janito/plugins/tools/get_file_outline/search_outline.py +36 -0
  66. janito/plugins/tools/move_file.py +131 -0
  67. janito/plugins/tools/open_html_in_browser.py +51 -0
  68. janito/plugins/tools/open_url.py +37 -0
  69. janito/{tools/adapters/local → plugins/tools}/python_code_run.py +23 -7
  70. janito/{tools/adapters/local → plugins/tools}/python_command_run.py +21 -5
  71. janito/{tools/adapters/local → plugins/tools}/python_file_run.py +21 -5
  72. janito/plugins/tools/read_chart.py +259 -0
  73. janito/plugins/tools/read_files.py +58 -0
  74. janito/plugins/tools/remove_directory.py +55 -0
  75. janito/plugins/tools/remove_file.py +58 -0
  76. janito/{tools/adapters/local → plugins/tools}/replace_text_in_file.py +4 -4
  77. janito/{tools/adapters/local → plugins/tools}/run_bash_command.py +3 -3
  78. janito/{tools/adapters/local → plugins/tools}/run_powershell_command.py +3 -3
  79. janito/plugins/tools/search_text/__init__.py +7 -0
  80. janito/plugins/tools/search_text/core.py +205 -0
  81. janito/plugins/tools/search_text/match_lines.py +67 -0
  82. janito/plugins/tools/search_text/pattern_utils.py +73 -0
  83. janito/plugins/tools/search_text/traverse_directory.py +145 -0
  84. janito/{tools/adapters/local → plugins/tools}/show_image.py +15 -6
  85. janito/plugins/tools/show_image_grid.py +85 -0
  86. janito/plugins/tools/validate_file_syntax/__init__.py +7 -0
  87. janito/plugins/tools/validate_file_syntax/core.py +114 -0
  88. janito/plugins/tools/validate_file_syntax/css_validator.py +35 -0
  89. janito/plugins/tools/validate_file_syntax/html_validator.py +100 -0
  90. janito/plugins/tools/validate_file_syntax/jinja2_validator.py +50 -0
  91. janito/plugins/tools/validate_file_syntax/js_validator.py +27 -0
  92. janito/plugins/tools/validate_file_syntax/json_validator.py +6 -0
  93. janito/plugins/tools/validate_file_syntax/markdown_validator.py +109 -0
  94. janito/plugins/tools/validate_file_syntax/ps1_validator.py +32 -0
  95. janito/plugins/tools/validate_file_syntax/python_validator.py +5 -0
  96. janito/plugins/tools/validate_file_syntax/xml_validator.py +11 -0
  97. janito/plugins/tools/validate_file_syntax/yaml_validator.py +6 -0
  98. janito/plugins/tools/view_file.py +172 -0
  99. janito/plugins/ui/__init__.py +7 -0
  100. janito/plugins/ui/userinterface/__init__.py +16 -0
  101. janito/plugins/ui/userinterface/tools/ask_user.py +110 -0
  102. janito/plugins/web/__init__.py +7 -0
  103. janito/plugins/web/webtools/__init__.py +33 -0
  104. janito/plugins/web/webtools/tools/fetch_url.py +458 -0
  105. janito/providers/__init__.py +1 -0
  106. janito/providers/together/__init__.py +1 -0
  107. janito/providers/together/model_info.py +69 -0
  108. janito/providers/together/provider.py +108 -0
  109. janito/tools/__init__.py +31 -7
  110. janito/tools/adapters/__init__.py +6 -1
  111. janito/tools/adapters/local/__init__.py +7 -70
  112. janito/tools/cli_initializer.py +88 -0
  113. janito/tools/initialize.py +70 -0
  114. janito/tools/loop_protection_decorator.py +114 -117
  115. janito-3.5.1.dist-info/METADATA +229 -0
  116. {janito-3.4.0.dist-info → janito-3.5.1.dist-info}/RECORD +155 -86
  117. janito/plugins/core_loader.py +0 -120
  118. janito/plugins/core_loader_fixed.py +0 -125
  119. janito/tools/function_adapter.py +0 -65
  120. janito-3.4.0.dist-info/METADATA +0 -84
  121. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/__init__.py +0 -0
  122. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/core.py +0 -0
  123. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/java_outline.py +0 -0
  124. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/markdown_outline.py +0 -0
  125. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/python_outline.py +0 -0
  126. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/search_outline.py +0 -0
  127. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/__init__.py +0 -0
  128. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/core.py +0 -0
  129. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/match_lines.py +0 -0
  130. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/pattern_utils.py +0 -0
  131. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/traverse_directory.py +0 -0
  132. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/copy_file.py +0 -0
  133. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/create_directory.py +0 -0
  134. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/delete_text_in_file.py +0 -0
  135. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/find_files.py +0 -0
  136. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/move_file.py +0 -0
  137. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/read_files.py +0 -0
  138. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_directory.py +0 -0
  139. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_file.py +0 -0
  140. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/__init__.py +0 -0
  141. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/core.py +0 -0
  142. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/css_validator.py +0 -0
  143. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/html_validator.py +0 -0
  144. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/jinja2_validator.py +0 -0
  145. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/js_validator.py +0 -0
  146. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/json_validator.py +0 -0
  147. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/markdown_validator.py +0 -0
  148. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/ps1_validator.py +0 -0
  149. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/python_validator.py +0 -0
  150. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/xml_validator.py +0 -0
  151. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/yaml_validator.py +0 -0
  152. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/view_file.py +0 -0
  153. /janito/{tools/adapters/local → plugins/dev/visualization/tools}/read_chart.py +0 -0
  154. /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_html_in_browser.py +0 -0
  155. /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_url.py +0 -0
  156. {janito-3.4.0.dist-info → janito-3.5.1.dist-info}/WHEEL +0 -0
  157. {janito-3.4.0.dist-info → janito-3.5.1.dist-info}/entry_points.txt +0 -0
  158. {janito-3.4.0.dist-info → janito-3.5.1.dist-info}/licenses/LICENSE +0 -0
  159. {janito-3.4.0.dist-info → janito-3.5.1.dist-info}/top_level.txt +0 -0
@@ -1,12 +1,10 @@
1
1
  from janito.tools.tool_base import ToolBase, ToolPermissions
2
2
  from janito.report_events import ReportAction
3
- from janito.tools.adapters.local.adapter import register_local_tool
4
3
  from janito.i18n import tr
5
4
  from janito.tools.loop_protection_decorator import protect_against_loops
6
5
  from typing import Sequence
7
6
 
8
7
 
9
- @register_local_tool
10
8
  class ShowImageGridTool(ToolBase):
11
9
  """Display multiple images in a grid inline in the terminal using rich.
12
10
 
@@ -50,7 +48,9 @@ class ShowImageGridTool(ToolBase):
50
48
  if not paths:
51
49
  return tr("No images provided")
52
50
 
53
- self.report_action(tr("🖼️ Show image grid ({n} images)", n=len(paths)), ReportAction.READ)
51
+ self.report_action(
52
+ tr("🖼️ Show image grid ({n} images)", n=len(paths)), ReportAction.READ
53
+ )
54
54
 
55
55
  console = Console()
56
56
  images = []
@@ -63,7 +63,9 @@ class ShowImageGridTool(ToolBase):
63
63
  try:
64
64
  img = PILImage.open(fp)
65
65
  title = f"{display_path(fp)} ({img.width}x{img.height})"
66
- images.append(Panel.fit(title, title=display_path(fp), border_style="dim"))
66
+ images.append(
67
+ Panel.fit(title, title=display_path(fp), border_style="dim")
68
+ )
67
69
  shown += 1
68
70
  except Exception as e:
69
71
  self.report_warning(tr("⚠️ Skipped {p}: {e}", p=display_path(fp), e=e))
@@ -71,6 +73,12 @@ class ShowImageGridTool(ToolBase):
71
73
  if not images:
72
74
  return tr("No images could be displayed")
73
75
 
76
+ # Render in columns (grid-like)
74
77
  console.print(Columns(images, equal=True, expand=True, columns=columns))
75
78
  self.report_success(tr("✅ Displayed {n} images", n=shown))
76
- return tr("Displayed {shown}/{total} images in a {cols}x? grid", shown=shown, total=len(paths), cols=columns)
79
+ return tr(
80
+ "Displayed {shown}/{total} images in a {cols}x? grid",
81
+ shown=shown,
82
+ total=len(paths),
83
+ cols=columns,
84
+ )
@@ -0,0 +1,23 @@
1
+ """
2
+ System Tools Plugin
3
+
4
+ System-level operations and shell access.
5
+ """
6
+
7
+ from typing import Optional
8
+
9
+
10
+ def run_powershell_command(
11
+ command: str, timeout: int = 60, require_confirmation: bool = False
12
+ ) -> str:
13
+ """Execute PowerShell commands"""
14
+ return f"run_powershell_command(command='{command[:50]}...', timeout={timeout})"
15
+
16
+
17
+ run_powershell_command.tool_name = "run_powershell_command"
18
+
19
+
20
+ # Plugin metadata
21
+ __plugin_name__ = "core.system"
22
+ __plugin_description__ = "System-level operations and shell access"
23
+ __plugin_tools__ = [run_powershell_command]
@@ -0,0 +1,204 @@
1
+ from janito.tools.tool_base import ToolBase, ToolPermissions
2
+ from janito.report_events import ReportAction
3
+ from janito.tools.adapters.local.adapter import register_local_tool
4
+ from janito.i18n import tr
5
+ import subprocess
6
+ import tempfile
7
+ import sys
8
+ import os
9
+ import threading
10
+
11
+
12
+ @register_local_tool
13
+ class RunBashCommandTool(ToolBase):
14
+ """
15
+ Execute a non-interactive command using the bash shell and capture live output.
16
+ This tool explicitly invokes the 'bash' shell (not just the system default shell), so it requires bash to be installed and available in the system PATH. On Windows, this will only work if bash is available (e.g., via WSL, Git Bash, or similar).
17
+
18
+ Args:
19
+ command (str): The bash command to execute.
20
+ timeout (int): Timeout in seconds for the command. Defaults to 60.
21
+ require_confirmation (bool): If True, require user confirmation before running. Defaults to False.
22
+ requires_user_input (bool): If True, warns that the command may require user input and might hang. Defaults to False. Non-interactive commands are preferred for automation and reliability.
23
+ silent (bool): If True, suppresses progress and status messages. Defaults to False.
24
+
25
+ Returns:
26
+ str: File paths and line counts for stdout and stderr.
27
+ """
28
+
29
+ permissions = ToolPermissions(execute=True)
30
+ tool_name = "run_bash_command"
31
+
32
+ def _stream_output(self, stream, file_obj, report_func, count_func, counter):
33
+ import threading
34
+ for line in stream:
35
+ # Check for cancellation
36
+ if hasattr(self, '_cancel_event') and self._cancel_event.is_set():
37
+ break
38
+ file_obj.write(line)
39
+ file_obj.flush()
40
+ report_func(line.rstrip("\r\n"), ReportAction.EXECUTE)
41
+ if count_func == "stdout":
42
+ counter["stdout"] += 1
43
+ else:
44
+ counter["stderr"] += 1
45
+
46
+ def run(
47
+ self,
48
+ command: str,
49
+ timeout: int = 60,
50
+ require_confirmation: bool = False,
51
+ requires_user_input: bool = False,
52
+ silent: bool = False,
53
+ ) -> str:
54
+ if not command.strip():
55
+ self.report_warning(tr("ℹ️ Empty command provided."), ReportAction.EXECUTE)
56
+ return tr("Warning: Empty command provided. Operation skipped.")
57
+ if not silent:
58
+ self.report_action(
59
+ tr("🖥️ Run bash command: {command} ...\n", command=command),
60
+ ReportAction.EXECUTE,
61
+ )
62
+ else:
63
+ self.report_action(tr("⚡ Executing..."), ReportAction.EXECUTE)
64
+ if requires_user_input and not silent:
65
+ self.report_warning(
66
+ tr(
67
+ "⚠️ Warning: This command might be interactive, require user input, and might hang."
68
+ ),
69
+ ReportAction.EXECUTE,
70
+ )
71
+ sys.stdout.flush()
72
+ try:
73
+ with (
74
+ tempfile.NamedTemporaryFile(
75
+ mode="w+", prefix="run_bash_stdout_", delete=False, encoding="utf-8"
76
+ ) as stdout_file,
77
+ tempfile.NamedTemporaryFile(
78
+ mode="w+", prefix="run_bash_stderr_", delete=False, encoding="utf-8"
79
+ ) as stderr_file,
80
+ ):
81
+ env = os.environ.copy()
82
+ env["PYTHONIOENCODING"] = "utf-8"
83
+ env["LC_ALL"] = "C.UTF-8"
84
+ env["LANG"] = "C.UTF-8"
85
+ process = subprocess.Popen(
86
+ ["bash", "-c", command],
87
+ stdout=subprocess.PIPE,
88
+ stderr=subprocess.PIPE,
89
+ text=True,
90
+ encoding="utf-8",
91
+ bufsize=1,
92
+ env=env,
93
+ )
94
+ # Set up cancellation event
95
+ from janito.llm.cancellation_manager import get_cancellation_manager
96
+ cancel_manager = get_cancellation_manager()
97
+ self._cancel_event = cancel_manager.get_current_cancel_event()
98
+
99
+ counter = {"stdout": 0, "stderr": 0}
100
+ stdout_thread = threading.Thread(
101
+ target=self._stream_output,
102
+ args=(
103
+ process.stdout,
104
+ stdout_file,
105
+ self.report_stdout,
106
+ "stdout",
107
+ counter,
108
+ ),
109
+ )
110
+ stderr_thread = threading.Thread(
111
+ target=self._stream_output,
112
+ args=(
113
+ process.stderr,
114
+ stderr_file,
115
+ self.report_stderr,
116
+ "stderr",
117
+ counter,
118
+ ),
119
+ )
120
+ stdout_thread.start()
121
+ stderr_thread.start()
122
+ try:
123
+ return_code = process.wait(timeout=timeout)
124
+ # Check if cancelled
125
+ if self._cancel_event and self._cancel_event.is_set():
126
+ process.kill()
127
+ self.report_warning(
128
+ tr("Command cancelled by user"),
129
+ ReportAction.EXECUTE,
130
+ )
131
+ return tr("Command cancelled by user")
132
+ except subprocess.TimeoutExpired:
133
+ process.kill()
134
+ self.report_error(
135
+ tr(
136
+ " ❌ Timed out after {timeout} seconds.",
137
+ timeout=timeout,
138
+ ),
139
+ ReportAction.EXECUTE,
140
+ )
141
+ return tr(
142
+ "Command timed out after {timeout} seconds.", timeout=timeout
143
+ )
144
+ finally:
145
+ # Ensure threads are stopped
146
+ if self._cancel_event:
147
+ self._cancel_event.set()
148
+ stdout_thread.join(timeout=0.1)
149
+ stderr_thread.join(timeout=0.1)
150
+ stdout_file.flush()
151
+ stderr_file.flush()
152
+ if not silent:
153
+ self.report_success(
154
+ tr(
155
+ " ✅ return code {return_code}",
156
+ return_code=return_code,
157
+ ),
158
+ ReportAction.EXECUTE,
159
+ )
160
+ max_lines = 100
161
+ # Read back the output for summary
162
+ stdout_file.seek(0)
163
+ stderr_file.seek(0)
164
+ stdout_content = stdout_file.read()
165
+ stderr_content = stderr_file.read()
166
+ stdout_lines = counter["stdout"]
167
+ stderr_lines = counter["stderr"]
168
+ warning_msg = ""
169
+ if requires_user_input:
170
+ warning_msg = tr(
171
+ "⚠️ Warning: This command might be interactive, require user input, and might hang.\n"
172
+ )
173
+ if stdout_lines <= max_lines and stderr_lines <= max_lines:
174
+ result = warning_msg + tr(
175
+ "Return code: {return_code}\n--- STDOUT ---\n{stdout_content}",
176
+ return_code=return_code,
177
+ stdout_content=stdout_content,
178
+ )
179
+ if stderr_content.strip():
180
+ result += tr(
181
+ "\n--- STDERR ---\n{stderr_content}",
182
+ stderr_content=stderr_content,
183
+ )
184
+ return result
185
+ else:
186
+ result = warning_msg + tr(
187
+ "[LARGE OUTPUT]\nstdout_file: {stdout_file} (lines: {stdout_lines})\n",
188
+ stdout_file=stdout_file.name,
189
+ stdout_lines=stdout_lines,
190
+ )
191
+ if stderr_lines > 0:
192
+ result += tr(
193
+ "stderr_file: {stderr_file} (lines: {stderr_lines})\n",
194
+ stderr_file=stderr_file.name,
195
+ stderr_lines=stderr_lines,
196
+ )
197
+ result += tr(
198
+ "returncode: {return_code}\nUse the view_file tool to inspect the contents of these files when needed.",
199
+ return_code=return_code,
200
+ )
201
+ return result
202
+ except Exception as e:
203
+ self.report_error(tr(" ❌ Error: {error}", error=e), ReportAction.EXECUTE)
204
+ return tr("Error running command: {error}", error=e)
@@ -0,0 +1,234 @@
1
+ from janito.tools.tool_base import ToolBase, ToolPermissions
2
+ from janito.report_events import ReportAction
3
+ from janito.tools.adapters.local.adapter import register_local_tool
4
+ from janito.i18n import tr
5
+ import subprocess
6
+ import os
7
+ from janito.tools.path_utils import expand_path
8
+ import tempfile
9
+ import threading
10
+
11
+
12
+ @register_local_tool
13
+ class RunPowershellCommandTool(ToolBase):
14
+ """
15
+ Execute a non-interactive command using the PowerShell shell and capture live output.
16
+ This tool explicitly invokes 'powershell.exe' (on Windows) or 'pwsh' (on other platforms if available).
17
+ All commands are automatically prepended with UTF-8 output encoding:
18
+ $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8;
19
+ For file output, it is recommended to use -Encoding utf8 in your PowerShell commands (e.g., Out-File -Encoding utf8) to ensure correct file encoding.
20
+
21
+ Args:
22
+ command (str): The PowerShell command to execute. This string is passed directly to PowerShell using the --Command argument (not as a script file).
23
+ timeout (int): Timeout in seconds for the command. Defaults to 60.
24
+ require_confirmation (bool): If True, require user confirmation before running. Defaults to False.
25
+ requires_user_input (bool): If True, warns that the command may require user input and might hang. Defaults to False. Non-interactive commands are preferred for automation and reliability.
26
+ silent (bool): If True, suppresses progress and status messages. Defaults to False.
27
+
28
+ Returns:
29
+ str: Output and status message, or file paths/line counts if output is large.
30
+ """
31
+
32
+ permissions = ToolPermissions(execute=True)
33
+ tool_name = "run_powershell_command"
34
+
35
+ def _confirm_and_warn(self, command, require_confirmation, requires_user_input):
36
+ if requires_user_input:
37
+ self.report_warning(
38
+ tr(
39
+ "⚠️ Warning: This command might be interactive, require user input, and might hang."
40
+ ),
41
+ ReportAction.EXECUTE,
42
+ )
43
+ if require_confirmation:
44
+ self.report_warning(
45
+ tr("⚠️ Confirmation requested, but no handler (auto-confirmed)."),
46
+ ReportAction.EXECUTE,
47
+ )
48
+ return True # Auto-confirm for now
49
+ return True
50
+
51
+ def _launch_process(self, shell_exe, command_with_encoding):
52
+ env = os.environ.copy()
53
+ env["PYTHONIOENCODING"] = "utf-8"
54
+ return subprocess.Popen(
55
+ [
56
+ shell_exe,
57
+ "-NoProfile",
58
+ "-ExecutionPolicy",
59
+ "Bypass",
60
+ "-Command",
61
+ command_with_encoding,
62
+ ],
63
+ stdout=subprocess.PIPE,
64
+ stderr=subprocess.PIPE,
65
+ text=True,
66
+ bufsize=1,
67
+ universal_newlines=True,
68
+ encoding="utf-8",
69
+ env=env,
70
+ )
71
+
72
+ def _stream_output(self, stream, file_obj, report_func, count_func, counter):
73
+ for line in stream:
74
+ # Check for cancellation
75
+ if hasattr(self, '_cancel_event') and self._cancel_event.is_set():
76
+ break
77
+ file_obj.write(line)
78
+ file_obj.flush()
79
+ report_func(line.rstrip("\r\n"), ReportAction.EXECUTE)
80
+ if count_func == "stdout":
81
+ counter["stdout"] += 1
82
+ else:
83
+ counter["stderr"] += 1
84
+
85
+ def _format_result(
86
+ self, requires_user_input, return_code, stdout_file, stderr_file, max_lines=100
87
+ ):
88
+ warning_msg = ""
89
+ if requires_user_input:
90
+ warning_msg = tr(
91
+ "⚠️ Warning: This command might be interactive, require user input, and might hang.\n"
92
+ )
93
+ with open(stdout_file.name, "r", encoding="utf-8", errors="replace") as out_f:
94
+ stdout_content = out_f.read()
95
+ with open(stderr_file.name, "r", encoding="utf-8", errors="replace") as err_f:
96
+ stderr_content = err_f.read()
97
+ stdout_lines = stdout_content.count("\n")
98
+ stderr_lines = stderr_content.count("\n")
99
+ if stdout_lines <= max_lines and stderr_lines <= max_lines:
100
+ result = warning_msg + tr(
101
+ "Return code: {return_code}\n--- STDOUT ---\n{stdout_content}",
102
+ return_code=return_code,
103
+ stdout_content=stdout_content,
104
+ )
105
+ if stderr_content.strip():
106
+ result += tr(
107
+ "\n--- STDERR ---\n{stderr_content}",
108
+ stderr_content=stderr_content,
109
+ )
110
+ return result
111
+ else:
112
+ result = warning_msg + tr(
113
+ "stdout_file: {stdout_file} (lines: {stdout_lines})\n",
114
+ stdout_file=stdout_file.name,
115
+ stdout_lines=stdout_lines,
116
+ )
117
+ if stderr_lines > 0 and stderr_content.strip():
118
+ result += tr(
119
+ "stderr_file: {stderr_file} (lines: {stderr_lines})\n",
120
+ stderr_file=stderr_file.name,
121
+ stderr_lines=stderr_lines,
122
+ )
123
+ result += tr(
124
+ "returncode: {return_code}\nUse the view_file tool to inspect the contents of these files when needed.",
125
+ return_code=return_code,
126
+ )
127
+ return result
128
+
129
+ def run(
130
+ self,
131
+ command: str,
132
+ timeout: int = 60,
133
+ require_confirmation: bool = False,
134
+ requires_user_input: bool = False,
135
+ silent: bool = False,
136
+ ) -> str:
137
+ if not command.strip():
138
+ self.report_warning(tr("ℹ️ Empty command provided."), ReportAction.EXECUTE)
139
+ return tr("Warning: Empty command provided. Operation skipped.")
140
+ encoding_prefix = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
141
+ command_with_encoding = encoding_prefix + command
142
+ if not silent:
143
+ self.report_action(
144
+ tr("🖥️ Running PowerShell command: {command} ...\n", command=command),
145
+ ReportAction.EXECUTE,
146
+ )
147
+ else:
148
+ self.report_action(tr("⚡ Executing..."), ReportAction.EXECUTE)
149
+ self._confirm_and_warn(command, require_confirmation, requires_user_input)
150
+ from janito.platform_discovery import PlatformDiscovery
151
+
152
+ pd = PlatformDiscovery()
153
+ shell_exe = "powershell.exe" if pd.is_windows() else "pwsh"
154
+ try:
155
+ with (
156
+ tempfile.NamedTemporaryFile(
157
+ mode="w+",
158
+ prefix="run_powershell_stdout_",
159
+ delete=False,
160
+ encoding="utf-8",
161
+ ) as stdout_file,
162
+ tempfile.NamedTemporaryFile(
163
+ mode="w+",
164
+ prefix="run_powershell_stderr_",
165
+ delete=False,
166
+ encoding="utf-8",
167
+ ) as stderr_file,
168
+ ):
169
+ # Set up cancellation event
170
+ from janito.llm.cancellation_manager import get_cancellation_manager
171
+ cancel_manager = get_cancellation_manager()
172
+ self._cancel_event = cancel_manager.get_current_cancel_event()
173
+
174
+ process = self._launch_process(shell_exe, command_with_encoding)
175
+ counter = {"stdout": 0, "stderr": 0}
176
+ stdout_thread = threading.Thread(
177
+ target=self._stream_output,
178
+ args=(
179
+ process.stdout,
180
+ stdout_file,
181
+ self.report_stdout,
182
+ "stdout",
183
+ counter,
184
+ ),
185
+ )
186
+ stderr_thread = threading.Thread(
187
+ target=self._stream_output,
188
+ args=(
189
+ process.stderr,
190
+ stderr_file,
191
+ self.report_stderr,
192
+ "stderr",
193
+ counter,
194
+ ),
195
+ )
196
+ stdout_thread.start()
197
+ stderr_thread.start()
198
+ try:
199
+ return_code = process.wait(timeout=timeout)
200
+ # Check if cancelled
201
+ if self._cancel_event and self._cancel_event.is_set():
202
+ process.kill()
203
+ self.report_warning(
204
+ tr("Command cancelled by user"),
205
+ ReportAction.EXECUTE,
206
+ )
207
+ return tr("Command cancelled by user")
208
+ except subprocess.TimeoutExpired:
209
+ process.kill()
210
+ self.report_error(
211
+ tr(
212
+ " ❌ Timed out after {timeout} seconds.",
213
+ timeout=timeout,
214
+ ),
215
+ ReportAction.EXECUTE,
216
+ )
217
+ return tr(
218
+ "Command timed out after {timeout} seconds.", timeout=timeout
219
+ )
220
+ stdout_thread.join()
221
+ stderr_thread.join()
222
+ stdout_file.flush()
223
+ stderr_file.flush()
224
+ if not silent:
225
+ self.report_success(
226
+ tr(" ✅ return code {return_code}", return_code=return_code),
227
+ ReportAction.EXECUTE,
228
+ )
229
+ return self._format_result(
230
+ requires_user_input, return_code, stdout_file, stderr_file
231
+ )
232
+ except Exception as e:
233
+ self.report_error(tr(" ❌ Error: {error}", error=e), ReportAction.EXECUTE)
234
+ return tr("Error running command: {error}", error=e)
@@ -5,25 +5,24 @@ This module provides proper Plugin class implementations for core plugins
5
5
  that use the function-based approach instead of class-based.
6
6
  """
7
7
 
8
- from janito.plugins.base import Plugin, PluginMetadata
8
+ from janito.plugin_system.base import Plugin, PluginMetadata
9
9
  from typing import List, Type
10
- from janito.tools.tool_base import ToolBase
11
- from janito.tools.function_adapter import create_function_tool
10
+ from janito.tools.tool_base import ToolBase, ToolPermissions
12
11
 
13
12
 
14
13
  class CorePluginAdapter(Plugin):
15
14
  """Adapter for core plugins using function-based tools."""
16
-
15
+
17
16
  def __init__(self, plugin_name: str, description: str, tools_module):
18
17
  super().__init__()
19
18
  self._plugin_name = plugin_name
20
19
  self._description = description
21
20
  self._tools_module = tools_module
22
21
  self._tool_classes = []
23
-
22
+
24
23
  # Set the metadata attribute that Plugin expects
25
24
  self.metadata = self.get_metadata()
26
-
25
+
27
26
  def get_metadata(self) -> PluginMetadata:
28
27
  return PluginMetadata(
29
28
  name=self._plugin_name,
@@ -32,22 +31,101 @@ class CorePluginAdapter(Plugin):
32
31
  author="Janito",
33
32
  license="MIT",
34
33
  )
35
-
34
+
36
35
  def get_tools(self) -> List[Type[ToolBase]]:
37
36
  return self._tool_classes
37
+
38
+ def _create_tool_class(self, func):
39
+ """Create a ToolBase class from a function."""
40
+ resolved_tool_name = getattr(func, "tool_name", func.__name__)
41
+
42
+ # Create a proper tool class with explicit parameters and documentation
43
+ import inspect
44
+ from typing import get_type_hints
45
+
46
+ func_sig = inspect.signature(func)
47
+ type_hints = get_type_hints(func)
48
+
49
+ # Build parameter definitions for the run method
50
+ param_defs = []
51
+ param_docs = []
52
+ for name, param in func_sig.parameters.items():
53
+ type_hint = type_hints.get(name, str)
54
+ if param.default == inspect.Parameter.empty:
55
+ param_defs.append(f"{name}: {type_hint.__name__}")
56
+ else:
57
+ param_defs.append(f"{name}: {type_hint.__name__} = {repr(param.default)}")
58
+
59
+ # Add parameter documentation
60
+ param_docs.append(f" {name}: {type_hint.__name__} - Parameter {name}")
61
+
62
+ # Get function docstring or create one
63
+ func_doc = func.__doc__ or f"Execute {resolved_tool_name} tool"
64
+
65
+ # Create the tool class with proper signature and documentation
66
+ exec_globals = {
67
+ 'ToolBase': ToolBase,
68
+ 'ToolPermissions': ToolPermissions,
69
+ 'func': func,
70
+ 'inspect': inspect,
71
+ 'str': str,
72
+ 'List': list,
73
+ 'Dict': dict,
74
+ 'Optional': type(None),
75
+ }
76
+
77
+ param_docs_str = '\n'.join(param_docs)
78
+
79
+ class_def = f'''
80
+ class DynamicTool(ToolBase):
81
+ """
82
+ {func_doc}
83
+
84
+ Parameters:
85
+ {param_docs_str}
86
+
87
+ Returns:
88
+ str: Execution result
89
+ """
90
+ tool_name = "{resolved_tool_name}"
91
+ permissions = ToolPermissions(read=True, write=True, execute=True)
38
92
 
93
+ def __init__(self):
94
+ super().__init__()
95
+
96
+ def run(self, {', '.join(param_defs)}) -> str:
97
+ kwargs = locals()
98
+ sig = inspect.signature(func)
99
+
100
+ # Filter kwargs to only include parameters the function accepts
101
+ filtered_kwargs = {{}}
102
+ for name, param in sig.parameters.items():
103
+ if name in kwargs and kwargs[name] is not None:
104
+ filtered_kwargs[name] = kwargs[name]
105
+
106
+ result = func(**filtered_kwargs)
107
+ return str(result) if result is not None else ""
108
+ '''
109
+
110
+ exec(class_def, exec_globals)
111
+ return exec_globals['DynamicTool']
112
+
113
+ return DynamicTool
114
+
39
115
  def initialize(self):
40
116
  """Initialize the plugin by creating tool classes."""
41
117
  # Get tools from the module
42
118
  tools = getattr(self._tools_module, "__plugin_tools__", [])
43
-
119
+
44
120
  self._tool_classes = []
45
121
  for tool_func in tools:
46
122
  if callable(tool_func):
47
- tool_class = create_function_tool(tool_func)
123
+ tool_class = self._create_tool_class(tool_func)
48
124
  self._tool_classes.append(tool_class)
49
125
 
50
126
 
51
- def create_core_plugin(plugin_name: str, description: str, tools_module) -> CorePluginAdapter:
127
+ def create_core_plugin(
128
+ plugin_name: str, description: str, tools_module
129
+ ) -> CorePluginAdapter:
52
130
  """Create a core plugin adapter."""
53
- return CorePluginAdapter(plugin_name, description, tools_module)
131
+ return CorePluginAdapter(plugin_name, description, tools_module)
@@ -0,0 +1,7 @@
1
+ """
2
+ Development Plugin Package
3
+
4
+ Contains development-specific tools and utilities.
5
+ """
6
+
7
+ __all__ = ["pythondev", "visualization"]