janito 3.3.0__py3-none-any.whl → 3.5.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 (170) 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/list_plugins.py +13 -8
  7. janito/cli/core/model_guesser.py +40 -24
  8. janito/cli/prompt_core.py +47 -9
  9. janito/cli/rich_terminal_reporter.py +2 -2
  10. janito/hello.txt +0 -0
  11. janito/i18n/it.py +46 -46
  12. janito/llm/agent.py +32 -16
  13. janito/llm/cancellation_manager.py +63 -0
  14. janito/llm/driver.py +8 -0
  15. janito/llm/enter_cancellation.py +107 -0
  16. janito/{plugin_system_backup_20250825_070018 → plugin_system}/core_loader.py +76 -3
  17. janito/{plugin_system_backup_20250825_070018 → plugin_system}/core_loader_fixed.py +79 -3
  18. janito/plugins/__init__.py +29 -21
  19. janito/{plugins_backup_20250825_070018 → plugins}/auto_loader.py +12 -11
  20. janito/plugins/builtin.py +1 -1
  21. janito/plugins/core/filemanager/tools/copy_file.py +1 -25
  22. janito/plugins/core/filemanager/tools/create_directory.py +1 -28
  23. janito/plugins/core/filemanager/tools/create_file.py +3 -27
  24. janito/plugins/core/filemanager/tools/delete_text_in_file.py +0 -1
  25. janito/plugins/core/imagedisplay/plugin.py +1 -1
  26. janito/plugins/core_adapter.py +131 -0
  27. janito/plugins/discovery.py +3 -3
  28. janito/{plugins_backup_20250825_070018 → plugins}/discovery_core.py +14 -9
  29. janito/plugins/example_plugin.py +1 -1
  30. janito/plugins/manager.py +1 -1
  31. janito/{plugins_backup_20250825_070018 → plugins}/tools/core_tools_plugin.py +9 -10
  32. janito/{plugins_backup_20250825_070018 → plugins}/tools/create_file.py +2 -2
  33. janito/{plugins_backup_20250825_070018 → plugins}/tools/delete_text_in_file.py +0 -1
  34. janito/providers/__init__.py +1 -0
  35. janito/providers/together/__init__.py +1 -0
  36. janito/providers/together/model_info.py +69 -0
  37. janito/providers/together/provider.py +108 -0
  38. janito/tools/base.py +1 -31
  39. janito/tools/cli_initializer.py +1 -1
  40. janito/tools/initialize.py +1 -1
  41. janito/tools/loop_protection_decorator.py +114 -117
  42. janito/tools/tool_base.py +114 -142
  43. janito/tools/tools_schema.py +6 -12
  44. janito-3.5.0.dist-info/METADATA +229 -0
  45. {janito-3.3.0.dist-info → janito-3.5.0.dist-info}/RECORD +98 -162
  46. janito/plugins/__main__.py +0 -85
  47. janito/plugins/base.py +0 -57
  48. janito/plugins/core_loader.py +0 -144
  49. janito/plugins_backup_20250825_070018/__init__.py +0 -36
  50. janito/plugins_backup_20250825_070018/builtin.py +0 -102
  51. janito/plugins_backup_20250825_070018/config.py +0 -84
  52. janito/plugins_backup_20250825_070018/core/__init__.py +0 -7
  53. janito/plugins_backup_20250825_070018/core/codeanalyzer/__init__.py +0 -43
  54. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/get_file_outline/__init__.py +0 -1
  55. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/get_file_outline/core.py +0 -122
  56. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/search_text/__init__.py +0 -1
  57. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/search_text/core.py +0 -205
  58. janito/plugins_backup_20250825_070018/core/filemanager/__init__.py +0 -124
  59. janito/plugins_backup_20250825_070018/core/filemanager/tools/copy_file.py +0 -87
  60. janito/plugins_backup_20250825_070018/core/filemanager/tools/create_directory.py +0 -70
  61. janito/plugins_backup_20250825_070018/core/filemanager/tools/create_file.py +0 -87
  62. janito/plugins_backup_20250825_070018/core/filemanager/tools/delete_text_in_file.py +0 -135
  63. janito/plugins_backup_20250825_070018/core/filemanager/tools/find_files.py +0 -143
  64. janito/plugins_backup_20250825_070018/core/filemanager/tools/move_file.py +0 -131
  65. janito/plugins_backup_20250825_070018/core/filemanager/tools/read_files.py +0 -58
  66. janito/plugins_backup_20250825_070018/core/filemanager/tools/remove_directory.py +0 -55
  67. janito/plugins_backup_20250825_070018/core/filemanager/tools/remove_file.py +0 -58
  68. janito/plugins_backup_20250825_070018/core/filemanager/tools/replace_text_in_file.py +0 -270
  69. janito/plugins_backup_20250825_070018/core/filemanager/tools/validate_file_syntax/__init__.py +0 -1
  70. janito/plugins_backup_20250825_070018/core/filemanager/tools/validate_file_syntax/core.py +0 -114
  71. janito/plugins_backup_20250825_070018/core/filemanager/tools/view_file.py +0 -172
  72. janito/plugins_backup_20250825_070018/core/imagedisplay/__init__.py +0 -14
  73. janito/plugins_backup_20250825_070018/core/imagedisplay/plugin.py +0 -51
  74. janito/plugins_backup_20250825_070018/core/imagedisplay/tools/__init__.py +0 -1
  75. janito/plugins_backup_20250825_070018/core/imagedisplay/tools/show_image.py +0 -83
  76. janito/plugins_backup_20250825_070018/core/imagedisplay/tools/show_image_grid.py +0 -84
  77. janito/plugins_backup_20250825_070018/core/system/__init__.py +0 -23
  78. janito/plugins_backup_20250825_070018/core/system/tools/run_bash_command.py +0 -183
  79. janito/plugins_backup_20250825_070018/core/system/tools/run_powershell_command.py +0 -218
  80. janito/plugins_backup_20250825_070018/core_adapter.py +0 -55
  81. janito/plugins_backup_20250825_070018/dev/__init__.py +0 -7
  82. janito/plugins_backup_20250825_070018/dev/pythondev/__init__.py +0 -37
  83. janito/plugins_backup_20250825_070018/dev/pythondev/tools/python_code_run.py +0 -172
  84. janito/plugins_backup_20250825_070018/dev/pythondev/tools/python_command_run.py +0 -171
  85. janito/plugins_backup_20250825_070018/dev/pythondev/tools/python_file_run.py +0 -172
  86. janito/plugins_backup_20250825_070018/dev/visualization/__init__.py +0 -23
  87. janito/plugins_backup_20250825_070018/dev/visualization/tools/read_chart.py +0 -259
  88. janito/plugins_backup_20250825_070018/discovery.py +0 -289
  89. janito/plugins_backup_20250825_070018/example_plugin.py +0 -108
  90. janito/plugins_backup_20250825_070018/manager.py +0 -243
  91. janito/plugins_backup_20250825_070018/tools/get_file_outline/java_outline.py +0 -47
  92. janito/plugins_backup_20250825_070018/tools/get_file_outline/markdown_outline.py +0 -14
  93. janito/plugins_backup_20250825_070018/tools/get_file_outline/python_outline.py +0 -303
  94. janito/plugins_backup_20250825_070018/tools/get_file_outline/search_outline.py +0 -36
  95. janito/plugins_backup_20250825_070018/tools/search_text/match_lines.py +0 -67
  96. janito/plugins_backup_20250825_070018/tools/search_text/pattern_utils.py +0 -73
  97. janito/plugins_backup_20250825_070018/tools/search_text/traverse_directory.py +0 -145
  98. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/css_validator.py +0 -35
  99. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/html_validator.py +0 -100
  100. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/jinja2_validator.py +0 -50
  101. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/js_validator.py +0 -27
  102. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/json_validator.py +0 -6
  103. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/markdown_validator.py +0 -109
  104. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/ps1_validator.py +0 -32
  105. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/python_validator.py +0 -5
  106. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/xml_validator.py +0 -11
  107. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/yaml_validator.py +0 -6
  108. janito/plugins_backup_20250825_070018/ui/__init__.py +0 -7
  109. janito/plugins_backup_20250825_070018/ui/userinterface/__init__.py +0 -16
  110. janito/plugins_backup_20250825_070018/ui/userinterface/tools/ask_user.py +0 -110
  111. janito/plugins_backup_20250825_070018/web/__init__.py +0 -7
  112. janito/plugins_backup_20250825_070018/web/webtools/__init__.py +0 -33
  113. janito/plugins_backup_20250825_070018/web/webtools/tools/fetch_url.py +0 -458
  114. janito/plugins_backup_20250825_070018/web/webtools/tools/open_html_in_browser.py +0 -51
  115. janito/plugins_backup_20250825_070018/web/webtools/tools/open_url.py +0 -37
  116. janito/tools/function_adapter.py +0 -176
  117. janito-3.3.0.dist-info/METADATA +0 -83
  118. /janito/{plugin_system_backup_20250825_070018 → plugin_system}/__init__.py +0 -0
  119. /janito/{plugin_system_backup_20250825_070018 → plugin_system}/base.py +0 -0
  120. /janito/{plugins_backup_20250825_070018 → plugins}/auto_loader_fixed.py +0 -0
  121. /janito/{plugins_backup_20250825_070018 → plugins}/tools/__init__.py +0 -0
  122. /janito/{plugins_backup_20250825_070018 → plugins}/tools/ask_user.py +0 -0
  123. /janito/{plugins_backup_20250825_070018 → plugins}/tools/copy_file.py +0 -0
  124. /janito/{plugins_backup_20250825_070018 → plugins}/tools/create_directory.py +0 -0
  125. /janito/{plugins_backup_20250825_070018 → plugins}/tools/decorators.py +0 -0
  126. /janito/{plugins_backup_20250825_070018 → plugins}/tools/fetch_url.py +0 -0
  127. /janito/{plugins_backup_20250825_070018 → plugins}/tools/find_files.py +0 -0
  128. /janito/{plugins_backup_20250825_070018 → plugins}/tools/get_file_outline/__init__.py +0 -0
  129. /janito/{plugins_backup_20250825_070018 → plugins}/tools/get_file_outline/core.py +0 -0
  130. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/get_file_outline/java_outline.py +0 -0
  131. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/get_file_outline/markdown_outline.py +0 -0
  132. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/get_file_outline/python_outline.py +0 -0
  133. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/get_file_outline/search_outline.py +0 -0
  134. /janito/{plugins_backup_20250825_070018 → plugins}/tools/move_file.py +0 -0
  135. /janito/{plugins_backup_20250825_070018 → plugins}/tools/open_html_in_browser.py +0 -0
  136. /janito/{plugins_backup_20250825_070018 → plugins}/tools/open_url.py +0 -0
  137. /janito/{plugins_backup_20250825_070018 → plugins}/tools/python_code_run.py +0 -0
  138. /janito/{plugins_backup_20250825_070018 → plugins}/tools/python_command_run.py +0 -0
  139. /janito/{plugins_backup_20250825_070018 → plugins}/tools/python_file_run.py +0 -0
  140. /janito/{plugins_backup_20250825_070018 → plugins}/tools/read_chart.py +0 -0
  141. /janito/{plugins_backup_20250825_070018 → plugins}/tools/read_files.py +0 -0
  142. /janito/{plugins_backup_20250825_070018 → plugins}/tools/remove_directory.py +0 -0
  143. /janito/{plugins_backup_20250825_070018 → plugins}/tools/remove_file.py +0 -0
  144. /janito/{plugins_backup_20250825_070018 → plugins}/tools/replace_text_in_file.py +0 -0
  145. /janito/{plugins_backup_20250825_070018 → plugins}/tools/run_bash_command.py +0 -0
  146. /janito/{plugins_backup_20250825_070018 → plugins}/tools/run_powershell_command.py +0 -0
  147. /janito/{plugins_backup_20250825_070018 → plugins}/tools/search_text/__init__.py +0 -0
  148. /janito/{plugins_backup_20250825_070018 → plugins}/tools/search_text/core.py +0 -0
  149. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/search_text/match_lines.py +0 -0
  150. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/search_text/pattern_utils.py +0 -0
  151. /janito/{plugins_backup_20250825_070018/core/codeanalyzer → plugins}/tools/search_text/traverse_directory.py +0 -0
  152. /janito/{plugins_backup_20250825_070018 → plugins}/tools/show_image.py +0 -0
  153. /janito/{plugins_backup_20250825_070018 → plugins}/tools/show_image_grid.py +0 -0
  154. /janito/{plugins_backup_20250825_070018 → plugins}/tools/validate_file_syntax/__init__.py +0 -0
  155. /janito/{plugins_backup_20250825_070018 → plugins}/tools/validate_file_syntax/core.py +0 -0
  156. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/css_validator.py +0 -0
  157. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/html_validator.py +0 -0
  158. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/jinja2_validator.py +0 -0
  159. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/js_validator.py +0 -0
  160. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/json_validator.py +0 -0
  161. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/markdown_validator.py +0 -0
  162. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/ps1_validator.py +0 -0
  163. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/python_validator.py +0 -0
  164. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/xml_validator.py +0 -0
  165. /janito/{plugins_backup_20250825_070018/core/filemanager → plugins}/tools/validate_file_syntax/yaml_validator.py +0 -0
  166. /janito/{plugins_backup_20250825_070018 → plugins}/tools/view_file.py +0 -0
  167. {janito-3.3.0.dist-info → janito-3.5.0.dist-info}/WHEEL +0 -0
  168. {janito-3.3.0.dist-info → janito-3.5.0.dist-info}/entry_points.txt +0 -0
  169. {janito-3.3.0.dist-info → janito-3.5.0.dist-info}/licenses/LICENSE +0 -0
  170. {janito-3.3.0.dist-info → janito-3.5.0.dist-info}/top_level.txt +0 -0
@@ -1,259 +0,0 @@
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.tools.tool_utils import display_path
5
- from janito.i18n import tr
6
- import json
7
- import os
8
- from janito.tools.loop_protection_decorator import protect_against_loops
9
-
10
-
11
- @register_local_tool
12
- class ReadChartTool(ToolBase):
13
- """
14
- Display charts and data visualizations in the terminal using rich.
15
-
16
- Args:
17
- data (dict): Chart data in JSON format. Should contain 'type' (bar, line, pie, table) and 'data' keys.
18
- title (str, optional): Chart title. Defaults to "Chart".
19
- width (int, optional): Chart width. Defaults to 80.
20
- height (int, optional): Chart height. Defaults to 20.
21
-
22
- Returns:
23
- str: Formatted chart display in terminal or error message.
24
- """
25
-
26
- permissions = ToolPermissions(read=True)
27
- tool_name = "read_chart"
28
-
29
- @protect_against_loops(max_calls=5, time_window=10.0, key_field="data")
30
- def run(
31
- self, data: dict, title: str = "Chart", width: int = 80, height: int = 20
32
- ) -> str:
33
- try:
34
- from rich.console import Console
35
- from rich.table import Table
36
- from rich.text import Text
37
- from rich.layout import Layout
38
- from rich.panel import Panel
39
- from rich.columns import Columns
40
- from rich import box
41
-
42
- console = Console(width=width)
43
-
44
- if not isinstance(data, dict):
45
- return "❌ Error: Data must be a dictionary"
46
-
47
- chart_type = data.get("type", "table").lower()
48
- chart_data = data.get("data", [])
49
-
50
- if not chart_data:
51
- return "⚠️ Warning: No data provided for chart"
52
-
53
- self.report_action(
54
- tr(
55
- "📊 Displaying {chart_type} chart: {title}",
56
- chart_type=chart_type,
57
- title=title,
58
- ),
59
- ReportAction.READ,
60
- )
61
-
62
- if chart_type == "table":
63
- return self._display_table(console, chart_data, title, width)
64
- elif chart_type == "bar":
65
- return self._display_bar(console, chart_data, title, width, height)
66
- elif chart_type == "line":
67
- return self._display_line(console, chart_data, title, width, height)
68
- elif chart_type == "pie":
69
- return self._display_pie(console, chart_data, title, width)
70
- else:
71
- return f"❌ Error: Unsupported chart type '{chart_type}'. Use: table, bar, line, pie"
72
-
73
- except ImportError:
74
- return "❌ Error: rich library not available for chart display"
75
- except Exception as e:
76
- return f"❌ Error displaying chart: {e}"
77
-
78
- def _display_table(self, console, data, title, width):
79
- """Display data as a rich table."""
80
- from rich.table import Table
81
-
82
- if not data:
83
- return "No data to display"
84
-
85
- table = Table(title=title, show_header=True, header_style="bold magenta")
86
-
87
- # Handle different data formats
88
- if isinstance(data, dict):
89
- # Dictionary format: key-value pairs
90
- table.add_column("Key", style="cyan")
91
- table.add_column("Value", style="green")
92
- for key, value in data.items():
93
- table.add_row(str(key), str(value))
94
- elif isinstance(data, list):
95
- if data and isinstance(data[0], dict):
96
- # List of dictionaries (records)
97
- headers = list(data[0].keys()) if data else []
98
- for header in headers:
99
- table.add_column(str(header).title(), style="cyan")
100
- for row in data:
101
- table.add_row(*[str(row.get(h, "")) for h in headers])
102
- else:
103
- # Simple list
104
- table.add_column("Items", style="cyan")
105
- for item in data:
106
- table.add_row(str(item))
107
-
108
- console.print(table)
109
- return f"✅ Table chart displayed: {title}"
110
-
111
- def _display_bar(self, console, data, title, width, height):
112
- """Display data as a simple bar chart using unicode blocks."""
113
- try:
114
- if isinstance(data, dict):
115
- items = list(data.items())
116
- elif isinstance(data, list) and data and isinstance(data[0], dict):
117
- # Assume first two keys are labels and values
118
- keys = list(data[0].keys())
119
- if len(keys) >= 2:
120
- label_key, value_key = keys[0], keys[1]
121
- items = [(item[label_key], item[value_key]) for item in data]
122
- else:
123
- items = [(str(i), v) for i, v in enumerate(data)]
124
- else:
125
- items = [(str(i), v) for i, v in enumerate(data)]
126
-
127
- if not items:
128
- return "No data to display"
129
-
130
- # Convert values to numbers
131
- numeric_items = []
132
- for label, value in items:
133
- try:
134
- numeric_items.append((str(label), float(value)))
135
- except (ValueError, TypeError):
136
- numeric_items.append((str(label), 0.0))
137
-
138
- if not numeric_items:
139
- return "No valid numeric data to display"
140
-
141
- max_val = max(val for _, val in numeric_items) if numeric_items else 1
142
-
143
- console.print(f"\n[bold]{title}[/bold]")
144
- console.print("=" * min(len(title), width))
145
-
146
- for label, value in numeric_items:
147
- bar_length = int((value / max_val) * (width - 20)) if max_val > 0 else 0
148
- bar = "█" * bar_length
149
- console.print(f"{label:<15} {bar} {value:.1f}")
150
-
151
- return f"✅ Bar chart displayed: {title}"
152
-
153
- except Exception as e:
154
- return f"❌ Error displaying bar chart: {e}"
155
-
156
- def _display_line(self, console, data, title, width, height):
157
- """Display data as a simple line chart using unicode characters."""
158
- try:
159
- if isinstance(data, dict):
160
- items = list(data.items())
161
- elif isinstance(data, list):
162
- if data and isinstance(data[0], dict):
163
- keys = list(data[0].keys())
164
- if len(keys) >= 2:
165
- label_key, value_key = keys[0], keys[1]
166
- items = [(item[label_key], item[value_key]) for item in data]
167
- else:
168
- items = [(str(i), v) for i, v in enumerate(data)]
169
- else:
170
- items = [(str(i), v) for i, v in enumerate(data)]
171
- else:
172
- return "Unsupported data format"
173
-
174
- # Convert to numeric values
175
- points = []
176
- for x, y in items:
177
- try:
178
- points.append((float(x), float(y)))
179
- except (ValueError, TypeError):
180
- continue
181
-
182
- if len(points) < 2:
183
- return "Need at least 2 data points for line chart"
184
-
185
- points.sort(key=lambda p: p[0])
186
-
187
- # Simple ASCII line chart
188
- min_x, max_x = min(p[0] for p in points), max(p[0] for p in points)
189
- min_y, max_y = min(p[1] for p in points), max(p[1] for p in points)
190
-
191
- if max_x == min_x or max_y == min_y:
192
- return "Cannot display line chart: all values are the same"
193
-
194
- console.print(f"\n[bold]{title}[/bold]")
195
- console.print("=" * min(len(title), width))
196
-
197
- # Simple representation
198
- for x, y in points:
199
- x_norm = int(((x - min_x) / (max_x - min_x)) * (width - 20))
200
- y_norm = int(((y - min_y) / (max_y - min_y)) * 10)
201
- line = " " * x_norm + "●" + " " * (width - 20 - x_norm)
202
- console.print(f"{x:>8.1f}: {line} {y:.1f}")
203
-
204
- return f"✅ Line chart displayed: {title}"
205
-
206
- except Exception as e:
207
- return f"❌ Error displaying line chart: {e}"
208
-
209
- def _display_pie(self, console, data, title, width):
210
- """Display data as a simple pie chart representation."""
211
- try:
212
- if isinstance(data, dict):
213
- items = list(data.items())
214
- elif isinstance(data, list) and data and isinstance(data[0], dict):
215
- keys = list(data[0].keys())
216
- if len(keys) >= 2:
217
- label_key, value_key = keys[0], keys[1]
218
- items = [(item[label_key], item[value_key]) for item in data]
219
- else:
220
- items = [(str(i), v) for i, v in enumerate(data)]
221
- else:
222
- items = [(str(i), v) for i, v in enumerate(data)]
223
-
224
- # Convert to numeric values
225
- values = []
226
- for label, value in items:
227
- try:
228
- values.append((str(label), float(value)))
229
- except (ValueError, TypeError):
230
- continue
231
-
232
- if not values:
233
- return "No valid numeric data to display"
234
-
235
- total = sum(val for _, val in values)
236
- if total == 0:
237
- return "Cannot display pie chart: total is zero"
238
-
239
- console.print(f"\n[bold]{title}[/bold]")
240
- console.print("=" * min(len(title), width))
241
-
242
- # Unicode pie chart segments
243
- segments = ["🟦", "🟥", "🟩", "🟨", "🟪", "🟧", "⬛", "⬜"]
244
-
245
- for i, (label, value) in enumerate(values):
246
- percentage = (value / total) * 100
247
- segment = segments[i % len(segments)]
248
- bar_length = int((value / total) * (width - 30))
249
- bar = "█" * bar_length
250
- console.print(
251
- f"{segment} {label:<15} {bar} {percentage:5.1f}% ({value})"
252
- )
253
-
254
- console.print(f"\n[dim]Total: {total}[/dim]")
255
-
256
- return f"✅ Pie chart displayed: {title}"
257
-
258
- except Exception as e:
259
- return f"❌ Error displaying pie chart: {e}"
@@ -1,289 +0,0 @@
1
- """
2
- Plugin discovery utilities.
3
-
4
- Plugins can be provided in several formats:
5
-
6
- 1. Single Python file: A .py file containing a Plugin class
7
- Example: plugins/my_plugin.py
8
-
9
- 2. Python package directory: A directory with __init__.py or plugin.py
10
- Example: plugins/my_plugin/__init__.py
11
- Example: plugins/my_plugin/plugin.py
12
-
13
- 3. Installed Python package: An installed package with a Plugin class
14
- Example: pip install janito-plugin-example
15
-
16
- 4. ZIP file: A .zip file containing a Python package structure
17
- Example: plugins/my_plugin.zip (containing package structure)
18
-
19
- The plugin discovery system searches these locations in order:
20
- - Current working directory/plugins/
21
- - ~/.janito/plugins/
22
- - Python installation share/janito/plugins/
23
- - Any additional paths specified via configuration
24
- """
25
-
26
- import os
27
- import sys
28
- import importlib
29
- import importlib.util
30
- from pathlib import Path
31
- from typing import Optional, List
32
- import logging
33
-
34
- from janito.plugin_system.base import Plugin
35
- from .builtin import load_builtin_plugin, BuiltinPluginRegistry
36
- from janito.plugin_system.core_loader import load_core_plugin
37
-
38
- logger = logging.getLogger(__name__)
39
-
40
-
41
- def discover_plugins(
42
- plugin_name: str, search_paths: List[Path] = None
43
- ) -> Optional[Plugin]:
44
- """
45
- Discover and load a plugin by name.
46
-
47
- Supports multiple plugin formats:
48
- - Single .py files
49
- - Python package directories
50
- - Package-based plugins (e.g., core.filemanager)
51
- - Installed Python packages
52
- - ZIP files containing packages
53
-
54
- Args:
55
- plugin_name: Name of the plugin to discover
56
- search_paths: List of directories to search for plugins
57
-
58
- Returns:
59
- Plugin instance if found, None otherwise
60
- """
61
- if search_paths is None:
62
- search_paths = []
63
-
64
- # Add default search paths
65
- default_paths = [
66
- Path.cwd() / "plugins",
67
- Path.home() / ".janito" / "plugins",
68
- Path(sys.prefix) / "share" / "janito" / "plugins",
69
- ]
70
-
71
- all_paths = search_paths + default_paths
72
-
73
- # Handle package-based plugins (e.g., core.filemanager)
74
- if "." in plugin_name:
75
- parts = plugin_name.split(".")
76
- if len(parts) == 2:
77
- package_name, submodule_name = parts
78
-
79
- # Handle core plugins with dedicated loader
80
- if plugin_name.startswith(("core.", "dev.", "ui.", "web.")):
81
- plugin = load_core_plugin(plugin_name)
82
- if plugin:
83
- return plugin
84
-
85
- for base_path in all_paths:
86
- package_path = base_path / package_name / submodule_name / "__init__.py"
87
- if package_path.exists():
88
- return _load_plugin_from_file(package_path, plugin_name=plugin_name)
89
-
90
- plugin_path = base_path / package_name / submodule_name / "plugin.py"
91
- if plugin_path.exists():
92
- return _load_plugin_from_file(plugin_path, plugin_name=plugin_name)
93
-
94
- # Try to find plugin in search paths
95
- for base_path in all_paths:
96
- plugin_path = base_path / plugin_name
97
- if plugin_path.exists():
98
- return _load_plugin_from_directory(plugin_path)
99
-
100
- # Try as Python module
101
- module_path = base_path / f"{plugin_name}.py"
102
- if module_path.exists():
103
- return _load_plugin_from_file(module_path)
104
-
105
- # Check for builtin plugins
106
- builtin_plugin = load_builtin_plugin(plugin_name)
107
- if builtin_plugin:
108
- return builtin_plugin
109
-
110
- # Try importing as installed package
111
- try:
112
- return _load_plugin_from_package(plugin_name)
113
- except ImportError:
114
- pass
115
-
116
- return None
117
-
118
-
119
- def _load_plugin_from_directory(plugin_path: Path) -> Optional[Plugin]:
120
- """Load a plugin from a directory."""
121
- try:
122
- # Look for __init__.py or plugin.py
123
- init_file = plugin_path / "__init__.py"
124
- plugin_file = plugin_path / "plugin.py"
125
-
126
- if init_file.exists():
127
- return _load_plugin_from_file(init_file, plugin_name=plugin_path.name)
128
- elif plugin_file.exists():
129
- return _load_plugin_from_file(plugin_file, plugin_name=plugin_path.name)
130
-
131
- except Exception as e:
132
- logger.error(f"Failed to load plugin from directory {plugin_path}: {e}")
133
-
134
- return None
135
-
136
-
137
- def _load_plugin_from_file(
138
- file_path: Path, plugin_name: str = None
139
- ) -> Optional[Plugin]:
140
- """Load a plugin from a Python file."""
141
- try:
142
- if plugin_name is None:
143
- plugin_name = file_path.stem
144
-
145
- spec = importlib.util.spec_from_file_location(plugin_name, file_path)
146
- if spec is None or spec.loader is None:
147
- return None
148
-
149
- module = importlib.util.module_from_spec(spec)
150
- spec.loader.exec_module(module)
151
-
152
- # Look for Plugin class
153
- for attr_name in dir(module):
154
- attr = getattr(module, attr_name)
155
- if isinstance(attr, type) and issubclass(attr, Plugin) and attr != Plugin:
156
- return attr()
157
-
158
- # Check for package-based plugin with __plugin_name__ metadata
159
- if hasattr(module, "__plugin_name__"):
160
- from janito.plugin_system.base import PluginMetadata
161
-
162
- # Create a dynamic plugin class
163
- class PackagePlugin(Plugin):
164
- def __init__(self):
165
- super().__init__()
166
- self._module = module
167
-
168
- def get_metadata(self) -> PluginMetadata:
169
- return PluginMetadata(
170
- name=getattr(module, "__plugin_name__", plugin_name),
171
- version=getattr(module, "__plugin_version__", "1.0.0"),
172
- description=getattr(
173
- module,
174
- "__plugin_description__",
175
- f"Package plugin: {plugin_name}",
176
- ),
177
- author=getattr(module, "__plugin_author__", "Unknown"),
178
- license=getattr(module, "__plugin_license__", "MIT"),
179
- )
180
-
181
- def get_tools(self):
182
- return getattr(module, "__plugin_tools__", [])
183
-
184
- def initialize(self):
185
- if hasattr(module, "initialize"):
186
- module.initialize()
187
-
188
- def cleanup(self):
189
- if hasattr(module, "cleanup"):
190
- module.cleanup()
191
-
192
- return PackagePlugin()
193
-
194
- except Exception as e:
195
- logger.error(f"Failed to load plugin from file {file_path}: {e}")
196
-
197
- return None
198
-
199
-
200
- def _load_plugin_from_package(package_name: str) -> Optional[Plugin]:
201
- """Load a plugin from an installed package."""
202
- try:
203
- module = importlib.import_module(package_name)
204
-
205
- # Look for Plugin class
206
- for attr_name in dir(module):
207
- attr = getattr(module, attr_name)
208
- if isinstance(attr, type) and issubclass(attr, Plugin) and attr != Plugin:
209
- return attr()
210
-
211
- except ImportError as e:
212
- logger.debug(f"Could not import package {package_name}: {e}")
213
-
214
- return None
215
-
216
-
217
- def list_available_plugins(search_paths: List[Path] = None) -> List[str]:
218
- """
219
- List all available plugins in search paths.
220
-
221
- Scans for plugins in multiple formats:
222
- - .py files (excluding __init__.py)
223
- - Directories with __init__.py or plugin.py
224
- - Package directories with plugin metadata (__plugin_name__)
225
- - Any valid plugin structure in search paths
226
-
227
- Args:
228
- search_paths: List of directories to search for plugins
229
-
230
- Returns:
231
- List of plugin names found
232
- """
233
- if search_paths is None:
234
- search_paths = []
235
-
236
- # Add default search paths
237
- default_paths = [
238
- Path.cwd() / "plugins",
239
- Path.home() / ".janito" / "plugins",
240
- Path(sys.prefix) / "share" / "janito" / "plugins",
241
- ]
242
-
243
- all_paths = search_paths + default_paths
244
- plugins = []
245
-
246
- for base_path in all_paths:
247
- if not base_path.exists():
248
- continue
249
-
250
- # Look for directories with __init__.py or plugin.py
251
- for item in base_path.iterdir():
252
- if item.is_dir():
253
- # Check for package-based plugins (subdirectories with __init__.py)
254
- if (item / "__init__.py").exists():
255
- # Check subdirectories for plugin metadata
256
- for subitem in item.iterdir():
257
- if subitem.is_dir() and (subitem / "__init__.py").exists():
258
- try:
259
- import importlib.util
260
-
261
- spec = importlib.util.spec_from_file_location(
262
- f"{item.name}.{subitem.name}",
263
- subitem / "__init__.py",
264
- )
265
- if spec and spec.loader:
266
- module = importlib.util.module_from_spec(spec)
267
- spec.loader.exec_module(module)
268
-
269
- # Check for plugin metadata
270
- if hasattr(module, "__plugin_name__"):
271
- plugins.append(
272
- getattr(module, "__plugin_name__")
273
- )
274
- except Exception:
275
- pass
276
-
277
- # Also check for plugin.py files
278
- plugin_file = item / "plugin.py"
279
- if plugin_file.exists():
280
- plugins.append(item.name)
281
-
282
- elif item.suffix == ".py" and item.stem != "__init__":
283
- plugins.append(item.stem)
284
-
285
- # Add builtin plugins
286
- builtin_plugins = BuiltinPluginRegistry.list_builtin_plugins()
287
- plugins.extend(builtin_plugins)
288
-
289
- return sorted(set(plugins))
@@ -1,108 +0,0 @@
1
- """
2
- Example plugin demonstrating the plugin system.
3
- """
4
-
5
- from janito.plugin_system.base import Plugin, PluginMetadata, PluginResource
6
- from janito.tools.tool_base import ToolBase, ToolPermissions
7
- from typing import Dict, Any
8
-
9
-
10
- class HelloWorldTool(ToolBase):
11
- """A simple tool that says hello."""
12
-
13
- tool_name = "hello_world"
14
- permissions = ToolPermissions(read=True, write=False, execute=True)
15
-
16
- def run(self, name: str = "World") -> str:
17
- """
18
- Say hello to someone.
19
-
20
- Args:
21
- name: Name of the person to greet
22
-
23
- Returns:
24
- Greeting message
25
- """
26
- self.report_action(f"Saying hello to {name}", "greet")
27
- return f"Hello, {name}!"
28
-
29
-
30
- class CalculatorTool(ToolBase):
31
- """A simple calculator tool."""
32
-
33
- tool_name = "calculator"
34
- permissions = ToolPermissions(read=True, write=False, execute=True)
35
-
36
- def run(self, operation: str, a: float, b: float) -> str:
37
- """
38
- Perform basic calculations.
39
-
40
- Args:
41
- operation: Operation to perform (add, subtract, multiply, divide)
42
- a: First number
43
- b: Second number
44
-
45
- Returns:
46
- Result as string
47
- """
48
- self.report_action(f"Calculating {a} {operation} {b}", "calculate")
49
-
50
- if operation == "add":
51
- result = a + b
52
- elif operation == "subtract":
53
- result = a - b
54
- elif operation == "multiply":
55
- result = a * b
56
- elif operation == "divide":
57
- if b == 0:
58
- return "Error: Division by zero"
59
- result = a / b
60
- else:
61
- return f"Error: Unknown operation '{operation}'"
62
-
63
- return str(result)
64
-
65
-
66
- class ExamplePlugin(Plugin):
67
- """Example plugin providing basic tools."""
68
-
69
- def get_metadata(self) -> PluginMetadata:
70
- return PluginMetadata(
71
- name="example",
72
- version="1.0.0",
73
- description="Example plugin with basic tools",
74
- author="Janito Team",
75
- license="MIT",
76
- homepage="https://github.com/janito/example-plugin",
77
- )
78
-
79
- def get_tools(self):
80
- return [HelloWorldTool, CalculatorTool]
81
-
82
- def initialize(self):
83
- print("Example plugin initialized!")
84
-
85
- def cleanup(self):
86
- print("Example plugin cleaned up!")
87
-
88
- def get_config_schema(self) -> Dict[str, Any]:
89
- """Return JSON schema for plugin configuration."""
90
- return {
91
- "type": "object",
92
- "properties": {
93
- "greeting_prefix": {
94
- "type": "string",
95
- "description": "Custom greeting prefix for hello_world tool",
96
- "default": "Hello",
97
- },
98
- "max_calculation": {
99
- "type": "number",
100
- "description": "Maximum allowed calculation result",
101
- "default": 1000000,
102
- },
103
- },
104
- }
105
-
106
-
107
- # This makes the plugin discoverable
108
- PLUGIN_CLASS = ExamplePlugin