janito 2.32.0__py3-none-any.whl → 3.0.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 (145) hide show
  1. janito/agent/setup_agent.py +26 -0
  2. janito/agent/templates/profiles/system_prompt_template_Developer_with_Python_Tools.txt.j2 +2 -0
  3. janito/agent/templates/profiles/system_prompt_template_developer.txt.j2 +2 -0
  4. janito/agent/templates/profiles/system_prompt_template_market_analyst.txt.j2 +2 -0
  5. janito/agent/templates/profiles/system_prompt_template_model_conversation_without_tools_or_context.txt.j2 +2 -0
  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/main_cli.py +9 -12
  10. janito/drivers/openai/driver.py +1 -0
  11. janito/drivers/zai/driver.py +1 -0
  12. janito/llm/auth_utils.py +14 -5
  13. janito/plugin_system/__init__.py +10 -0
  14. janito/{plugins → plugin_system}/base.py +5 -2
  15. janito/{plugins/core_loader_fixed.py → plugin_system/core_loader.py} +45 -26
  16. janito/plugin_system/core_loader_fixed.py +149 -0
  17. janito/plugins/__init__.py +31 -12
  18. janito/plugins/auto_loader_fixed.py +12 -11
  19. janito/plugins/builtin.py +15 -1
  20. janito/plugins/core/__init__.py +7 -0
  21. janito/plugins/core/codeanalyzer/__init__.py +43 -0
  22. janito/plugins/core/filemanager/__init__.py +124 -0
  23. janito/plugins/core/filemanager/tools/create_file.py +87 -0
  24. janito/plugins/core/filemanager/tools/replace_text_in_file.py +270 -0
  25. janito/plugins/core/imagedisplay/__init__.py +14 -0
  26. janito/plugins/core/imagedisplay/plugin.py +51 -0
  27. janito/plugins/core/imagedisplay/tools/__init__.py +1 -0
  28. janito/plugins/core/imagedisplay/tools/show_image.py +83 -0
  29. janito/{tools/adapters/local → plugins/core/imagedisplay/tools}/show_image_grid.py +13 -5
  30. janito/plugins/core/system/__init__.py +23 -0
  31. janito/plugins/core_adapter.py +11 -9
  32. janito/plugins/dev/__init__.py +7 -0
  33. janito/plugins/dev/pythondev/__init__.py +37 -0
  34. janito/plugins/dev/visualization/__init__.py +23 -0
  35. janito/plugins/discovery.py +5 -5
  36. janito/plugins/example_plugin.py +108 -0
  37. janito/plugins/manager.py +1 -1
  38. janito/plugins/tools/__init__.py +10 -0
  39. janito/{tools/adapters/local → plugins/tools}/ask_user.py +3 -3
  40. janito/plugins/tools/copy_file.py +87 -0
  41. janito/plugins/tools/core_tools_plugin.py +88 -0
  42. janito/plugins/tools/create_directory.py +70 -0
  43. janito/{tools/adapters/local → plugins/tools}/create_file.py +4 -4
  44. janito/plugins/tools/decorators.py +19 -0
  45. janito/plugins/tools/delete_text_in_file.py +134 -0
  46. janito/plugins/tools/fetch_url.py +466 -0
  47. janito/plugins/tools/find_files.py +143 -0
  48. janito/plugins/tools/get_file_outline/__init__.py +7 -0
  49. janito/plugins/tools/get_file_outline/core.py +122 -0
  50. janito/plugins/tools/get_file_outline/java_outline.py +47 -0
  51. janito/plugins/tools/get_file_outline/markdown_outline.py +14 -0
  52. janito/plugins/tools/get_file_outline/python_outline.py +303 -0
  53. janito/plugins/tools/get_file_outline/search_outline.py +36 -0
  54. janito/plugins/tools/move_file.py +131 -0
  55. janito/plugins/tools/open_html_in_browser.py +51 -0
  56. janito/plugins/tools/open_url.py +37 -0
  57. janito/plugins/tools/python_code_run.py +172 -0
  58. janito/plugins/tools/python_command_run.py +171 -0
  59. janito/plugins/tools/python_file_run.py +172 -0
  60. janito/plugins/tools/read_chart.py +259 -0
  61. janito/plugins/tools/read_files.py +58 -0
  62. janito/plugins/tools/remove_directory.py +55 -0
  63. janito/plugins/tools/remove_file.py +58 -0
  64. janito/{tools/adapters/local → plugins/tools}/replace_text_in_file.py +4 -4
  65. janito/plugins/tools/run_bash_command.py +183 -0
  66. janito/plugins/tools/run_powershell_command.py +218 -0
  67. janito/plugins/tools/search_text/__init__.py +7 -0
  68. janito/plugins/tools/search_text/core.py +205 -0
  69. janito/plugins/tools/search_text/match_lines.py +67 -0
  70. janito/plugins/tools/search_text/pattern_utils.py +73 -0
  71. janito/plugins/tools/search_text/traverse_directory.py +145 -0
  72. janito/{tools/adapters/local → plugins/tools}/show_image.py +15 -6
  73. janito/plugins/tools/show_image_grid.py +85 -0
  74. janito/plugins/tools/validate_file_syntax/__init__.py +7 -0
  75. janito/plugins/tools/validate_file_syntax/core.py +114 -0
  76. janito/plugins/tools/validate_file_syntax/css_validator.py +35 -0
  77. janito/plugins/tools/validate_file_syntax/html_validator.py +100 -0
  78. janito/plugins/tools/validate_file_syntax/jinja2_validator.py +50 -0
  79. janito/plugins/tools/validate_file_syntax/js_validator.py +27 -0
  80. janito/plugins/tools/validate_file_syntax/json_validator.py +6 -0
  81. janito/plugins/tools/validate_file_syntax/markdown_validator.py +109 -0
  82. janito/plugins/tools/validate_file_syntax/ps1_validator.py +32 -0
  83. janito/plugins/tools/validate_file_syntax/python_validator.py +5 -0
  84. janito/plugins/tools/validate_file_syntax/xml_validator.py +11 -0
  85. janito/plugins/tools/validate_file_syntax/yaml_validator.py +6 -0
  86. janito/plugins/tools/view_file.py +172 -0
  87. janito/plugins/ui/__init__.py +7 -0
  88. janito/plugins/ui/userinterface/__init__.py +16 -0
  89. janito/plugins/ui/userinterface/tools/ask_user.py +110 -0
  90. janito/plugins/web/__init__.py +7 -0
  91. janito/plugins/web/webtools/__init__.py +33 -0
  92. janito/{tools/adapters/local → plugins/web/webtools/tools}/fetch_url.py +37 -27
  93. janito/tools/__init__.py +31 -7
  94. janito/tools/adapters/__init__.py +6 -1
  95. janito/tools/adapters/local/__init__.py +7 -70
  96. janito/tools/cli_initializer.py +88 -0
  97. janito/tools/function_adapter.py +93 -16
  98. janito/tools/initialize.py +70 -0
  99. {janito-2.32.0.dist-info → janito-3.0.0.dist-info}/METADATA +1 -2
  100. {janito-2.32.0.dist-info → janito-3.0.0.dist-info}/RECORD +144 -76
  101. janito/plugins/core_loader.py +0 -120
  102. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/__init__.py +0 -0
  103. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/core.py +0 -0
  104. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/java_outline.py +0 -0
  105. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/markdown_outline.py +0 -0
  106. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/python_outline.py +0 -0
  107. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/search_outline.py +0 -0
  108. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/__init__.py +0 -0
  109. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/core.py +0 -0
  110. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/match_lines.py +0 -0
  111. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/pattern_utils.py +0 -0
  112. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/traverse_directory.py +0 -0
  113. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/copy_file.py +0 -0
  114. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/create_directory.py +0 -0
  115. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/delete_text_in_file.py +0 -0
  116. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/find_files.py +0 -0
  117. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/move_file.py +0 -0
  118. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/read_files.py +0 -0
  119. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_directory.py +0 -0
  120. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_file.py +0 -0
  121. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/__init__.py +0 -0
  122. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/core.py +0 -0
  123. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/css_validator.py +0 -0
  124. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/html_validator.py +0 -0
  125. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/jinja2_validator.py +0 -0
  126. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/js_validator.py +0 -0
  127. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/json_validator.py +0 -0
  128. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/markdown_validator.py +0 -0
  129. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/ps1_validator.py +0 -0
  130. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/python_validator.py +0 -0
  131. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/xml_validator.py +0 -0
  132. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/yaml_validator.py +0 -0
  133. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/view_file.py +0 -0
  134. /janito/{tools/adapters/local → plugins/core/system/tools}/run_bash_command.py +0 -0
  135. /janito/{tools/adapters/local → plugins/core/system/tools}/run_powershell_command.py +0 -0
  136. /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_code_run.py +0 -0
  137. /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_command_run.py +0 -0
  138. /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_file_run.py +0 -0
  139. /janito/{tools/adapters/local → plugins/dev/visualization/tools}/read_chart.py +0 -0
  140. /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_html_in_browser.py +0 -0
  141. /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_url.py +0 -0
  142. {janito-2.32.0.dist-info → janito-3.0.0.dist-info}/WHEEL +0 -0
  143. {janito-2.32.0.dist-info → janito-3.0.0.dist-info}/entry_points.txt +0 -0
  144. {janito-2.32.0.dist-info → janito-3.0.0.dist-info}/licenses/LICENSE +0 -0
  145. {janito-2.32.0.dist-info → janito-3.0.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,466 @@
1
+ import requests
2
+ import time
3
+ import os
4
+ import json
5
+ from pathlib import Path
6
+ from bs4 import BeautifulSoup
7
+ from typing import Dict, Any, Optional
8
+ from janito.plugins.tools.decorators import register_core_tool
9
+ from janito.tools.tool_base import ToolBase, ToolPermissions
10
+ from janito.report_events import ReportAction
11
+ from janito.i18n import tr
12
+ from janito.tools.tool_utils import pluralize
13
+ from janito.tools.loop_protection_decorator import protect_against_loops
14
+
15
+
16
+ @register_core_tool
17
+ class FetchUrl(ToolBase):
18
+ """
19
+ Fetch the content of a web page and extract its text.
20
+
21
+ This tool implements a **session-based caching mechanism** that provides
22
+ **in-memory caching** for the lifetime of the tool instance. URLs are cached
23
+ in RAM during the session, providing instant access to previously fetched
24
+ content without making additional HTTP requests.
25
+
26
+ **Session Cache Behavior:**
27
+ - **Lifetime**: Cache exists for the lifetime of the FetchUrlTool instance
28
+ - **Scope**: In-memory (RAM) cache, not persisted to disk
29
+ - **Storage**: Successful responses are cached as raw HTML content
30
+ - **Key**: Cache key is the exact URL string
31
+ - **Invalidation**: Cache is automatically cleared when the tool instance is destroyed
32
+ - **Performance**: Subsequent requests for the same URL return instantly
33
+
34
+ **Error Cache Behavior:**
35
+ - HTTP 403 errors: Cached for 24 hours (more permanent)
36
+ - HTTP 404 errors: Cached for 1 hour (temporary)
37
+ - Other 4xx errors: Cached for 30 minutes
38
+ - 5xx errors: Not cached (retried on each request)
39
+
40
+ Args:
41
+ url (str): The URL of the web page to fetch.
42
+ search_strings (list[str], optional): Strings to search for in the page content.
43
+ max_length (int, optional): Maximum number of characters to return. Defaults to 5000.
44
+ max_lines (int, optional): Maximum number of lines to return. Defaults to 200.
45
+ context_chars (int, optional): Characters of context around search matches. Defaults to 400.
46
+ timeout (int, optional): Timeout in seconds for the HTTP request. Defaults to 10.
47
+ save_to_file (str, optional): File path to save the full resource content. If provided,
48
+ the complete response will be saved to this file instead of being processed.
49
+ headers (Dict[str, str], optional): Custom HTTP headers to send with the request.
50
+ cookies (Dict[str, str], optional): Custom cookies to send with the request.
51
+ follow_redirects (bool, optional): Whether to follow HTTP redirects. Defaults to True.
52
+ Returns:
53
+ str: Extracted text content from the web page, or a warning message. Example:
54
+ - "<main text content...>"
55
+ - "No lines found for the provided search strings."
56
+ - "Warning: Empty URL provided. Operation skipped."
57
+ """
58
+
59
+ permissions = ToolPermissions(read=True)
60
+ tool_name = "fetch_url"
61
+
62
+ def __init__(self):
63
+ super().__init__()
64
+ self.cache_dir = Path.home() / ".janito" / "cache" / "fetch_url"
65
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
66
+ self.cache_file = self.cache_dir / "error_cache.json"
67
+ self.session_cache = (
68
+ {}
69
+ ) # In-memory session cache - lifetime matches tool instance
70
+ self._load_cache()
71
+
72
+ # Browser-like session with cookies and headers
73
+ self.session = requests.Session()
74
+ self.session.headers.update(
75
+ {
76
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
77
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
78
+ "Accept-Language": "en-US,en;q=0.5",
79
+ "Accept-Encoding": "gzip, deflate, br",
80
+ "DNT": "1",
81
+ "Connection": "keep-alive",
82
+ "Upgrade-Insecure-Requests": "1",
83
+ }
84
+ )
85
+
86
+ # Load cookies from disk if they exist
87
+ self.cookies_file = self.cache_dir / "cookies.json"
88
+ self._load_cookies()
89
+
90
+ def _load_cache(self):
91
+ """Load error cache from disk."""
92
+ if self.cache_file.exists():
93
+ try:
94
+ with open(self.cache_file, "r", encoding="utf-8") as f:
95
+ self.error_cache = json.load(f)
96
+ except (json.JSONDecodeError, IOError):
97
+ self.error_cache = {}
98
+ else:
99
+ self.error_cache = {}
100
+
101
+ def _save_cache(self):
102
+ """Save error cache to disk."""
103
+ try:
104
+ with open(self.cache_file, "w", encoding="utf-8") as f:
105
+ json.dump(self.error_cache, f, indent=2)
106
+ except IOError:
107
+ pass # Silently fail if we can't write cache
108
+
109
+ def _load_cookies(self):
110
+ """Load cookies from disk into session."""
111
+ if self.cookies_file.exists():
112
+ try:
113
+ with open(self.cookies_file, "r", encoding="utf-8") as f:
114
+ cookies_data = json.load(f)
115
+ for cookie in cookies_data:
116
+ self.session.cookies.set(**cookie)
117
+ except (json.JSONDecodeError, IOError):
118
+ pass # Silently fail if we can't load cookies
119
+
120
+ def _save_cookies(self):
121
+ """Save session cookies to disk."""
122
+ try:
123
+ cookies_data = []
124
+ for cookie in self.session.cookies:
125
+ cookies_data.append(
126
+ {
127
+ "name": cookie.name,
128
+ "value": cookie.value,
129
+ "domain": cookie.domain,
130
+ "path": cookie.path,
131
+ }
132
+ )
133
+ with open(self.cookies_file, "w", encoding="utf-8") as f:
134
+ json.dump(cookies_data, f, indent=2)
135
+ except IOError:
136
+ pass # Silently fail if we can't write cookies
137
+
138
+ def _get_cached_error(self, url: str) -> tuple[str, bool]:
139
+ """
140
+ Check if we have a cached error for this URL.
141
+ Returns (error_message, is_cached) tuple.
142
+ """
143
+ if url not in self.error_cache:
144
+ return None, False
145
+
146
+ entry = self.error_cache[url]
147
+ current_time = time.time()
148
+
149
+ # Different expiration times for different status codes
150
+ if entry["status_code"] == 403:
151
+ # Cache 403 errors for 24 hours (more permanent)
152
+ expiration_time = 24 * 3600
153
+ elif entry["status_code"] == 404:
154
+ # Cache 404 errors for 1 hour (more temporary)
155
+ expiration_time = 3600
156
+ else:
157
+ # Cache other 4xx errors for 30 minutes
158
+ expiration_time = 1800
159
+
160
+ if current_time - entry["timestamp"] > expiration_time:
161
+ # Cache expired, remove it
162
+ del self.error_cache[url]
163
+ self._save_cache()
164
+ return None, False
165
+
166
+ return entry["message"], True
167
+
168
+ def _cache_error(self, url: str, status_code: int, message: str):
169
+ """Cache an HTTP error response."""
170
+ self.error_cache[url] = {
171
+ "status_code": status_code,
172
+ "message": message,
173
+ "timestamp": time.time(),
174
+ }
175
+ self._save_cache()
176
+
177
+ def _fetch_url_content(
178
+ self,
179
+ url: str,
180
+ timeout: int = 10,
181
+ headers: Optional[Dict[str, str]] = None,
182
+ cookies: Optional[Dict[str, str]] = None,
183
+ follow_redirects: bool = True,
184
+ ) -> str:
185
+ """Fetch URL content and handle HTTP errors.
186
+
187
+ Implements two-tier caching:
188
+ 1. Session cache: In-memory cache for successful responses (lifetime = tool instance)
189
+ 2. Error cache: Persistent disk cache for HTTP errors with different expiration times
190
+
191
+ Also implements URL whitelist checking and browser-like behavior.
192
+ """
193
+ # Check URL whitelist
194
+ from janito.tools.url_whitelist import get_url_whitelist_manager
195
+
196
+ whitelist_manager = get_url_whitelist_manager()
197
+
198
+ if not whitelist_manager.is_url_allowed(url):
199
+ error_message = tr("Blocked")
200
+ self.report_error(
201
+ tr("❗ Blocked"),
202
+ ReportAction.READ,
203
+ )
204
+ return error_message
205
+
206
+ # Check session cache first
207
+ if url in self.session_cache:
208
+ return self.session_cache[url]
209
+
210
+ # Check persistent cache for known errors
211
+ cached_error, is_cached = self._get_cached_error(url)
212
+ if cached_error:
213
+ self.report_warning(
214
+ tr(
215
+ "ℹ️ Using cached HTTP error for URL: {url}",
216
+ url=url,
217
+ ),
218
+ ReportAction.READ,
219
+ )
220
+ return cached_error
221
+
222
+ try:
223
+ # Merge custom headers with default ones
224
+ request_headers = self.session.headers.copy()
225
+ if headers:
226
+ request_headers.update(headers)
227
+
228
+ # Merge custom cookies
229
+ if cookies:
230
+ self.session.cookies.update(cookies)
231
+
232
+ response = self.session.get(
233
+ url,
234
+ timeout=timeout,
235
+ headers=request_headers,
236
+ allow_redirects=follow_redirects,
237
+ )
238
+ response.raise_for_status()
239
+ content = response.text
240
+
241
+ # Save cookies after successful request
242
+ self._save_cookies()
243
+
244
+ # Cache successful responses in session cache
245
+ self.session_cache[url] = content
246
+ return content
247
+ except requests.exceptions.HTTPError as http_err:
248
+ status_code = http_err.response.status_code if http_err.response else None
249
+
250
+ # Map status codes to descriptions
251
+ status_descriptions = {
252
+ 400: "Bad Request",
253
+ 401: "Unauthorized",
254
+ 403: "Forbidden",
255
+ 404: "Not Found",
256
+ 405: "Method Not Allowed",
257
+ 408: "Request Timeout",
258
+ 409: "Conflict",
259
+ 410: "Gone",
260
+ 413: "Payload Too Large",
261
+ 414: "URI Too Long",
262
+ 415: "Unsupported Media Type",
263
+ 429: "Too Many Requests",
264
+ 500: "Internal Server Error",
265
+ 501: "Not Implemented",
266
+ 502: "Bad Gateway",
267
+ 503: "Service Unavailable",
268
+ 504: "Gateway Timeout",
269
+ 505: "HTTP Version Not Supported",
270
+ }
271
+
272
+ if status_code and 400 <= status_code < 500:
273
+ description = status_descriptions.get(status_code, "Client Error")
274
+ error_message = f"HTTP {status_code} {description}"
275
+ # Cache 403 and 404 errors
276
+ if status_code in [403, 404]:
277
+ self._cache_error(url, status_code, error_message)
278
+
279
+ self.report_error(
280
+ f"❗ HTTP {status_code} {description}",
281
+ ReportAction.READ,
282
+ )
283
+ return error_message
284
+ elif status_code and 500 <= status_code < 600:
285
+ description = status_descriptions.get(status_code, "Server Error")
286
+ error_message = f"HTTP {status_code} {description}"
287
+ self.report_error(
288
+ f"❗ HTTP {status_code} {description}",
289
+ ReportAction.READ,
290
+ )
291
+ return error_message
292
+ else:
293
+ status_code_str = str(status_code) if status_code else "Error"
294
+ description = status_descriptions.get(
295
+ status_code,
296
+ (
297
+ "Server Error"
298
+ if status_code and status_code >= 500
299
+ else "Client Error"
300
+ ),
301
+ )
302
+ self.report_error(
303
+ f"❗ HTTP {status_code_str} {description}",
304
+ ReportAction.READ,
305
+ )
306
+ return f"HTTP {status_code_str} {description}"
307
+ except requests.exceptions.ConnectionError as conn_err:
308
+ self.report_error(
309
+ "❗ Network Error",
310
+ ReportAction.READ,
311
+ )
312
+ return f"Network Error: Failed to connect to {url}"
313
+ except requests.exceptions.Timeout as timeout_err:
314
+ self.report_error(
315
+ "❗ Timeout Error",
316
+ ReportAction.READ,
317
+ )
318
+ return f"Timeout Error: Request timed out after {timeout} seconds"
319
+ except requests.exceptions.RequestException as req_err:
320
+ self.report_error(
321
+ "❗ Request Error",
322
+ ReportAction.READ,
323
+ )
324
+ return f"Request Error: {str(req_err)}"
325
+ except Exception as err:
326
+ self.report_error(
327
+ "❗ Error fetching URL",
328
+ ReportAction.READ,
329
+ )
330
+ return f"Error: {str(err)}"
331
+
332
+ def _extract_and_clean_text(self, html_content: str) -> str:
333
+ """Extract and clean text from HTML content."""
334
+ soup = BeautifulSoup(html_content, "html.parser")
335
+ text = soup.get_text(separator="\n")
336
+
337
+ # Clean up excessive whitespace
338
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
339
+ return "\n".join(lines)
340
+
341
+ def _filter_by_search_strings(
342
+ self, text: str, search_strings: list[str], context_chars: int
343
+ ) -> str:
344
+ """Filter text by search strings with context."""
345
+ filtered = []
346
+ for s in search_strings:
347
+ idx = text.find(s)
348
+ if idx != -1:
349
+ start = max(0, idx - context_chars)
350
+ end = min(len(text), idx + len(s) + context_chars)
351
+ snippet = text[start:end]
352
+ filtered.append(snippet)
353
+
354
+ if filtered:
355
+ return "\n...\n".join(filtered)
356
+ else:
357
+ return tr("No lines found for the provided search strings.")
358
+
359
+ def _apply_limits(self, text: str, max_length: int, max_lines: int) -> str:
360
+ """Apply length and line limits to text."""
361
+ # Apply length limit
362
+ if len(text) > max_length:
363
+ text = text[:max_length] + "\n... (content truncated due to length limit)"
364
+
365
+ # Apply line limit
366
+ lines = text.splitlines()
367
+ if len(lines) > max_lines:
368
+ text = (
369
+ "\n".join(lines[:max_lines])
370
+ + "\n... (content truncated due to line limit)"
371
+ )
372
+
373
+ return text
374
+
375
+ @protect_against_loops(max_calls=5, time_window=10.0, key_field="url")
376
+ def run(
377
+ self,
378
+ url: str,
379
+ search_strings: list[str] = None,
380
+ max_length: int = 5000,
381
+ max_lines: int = 200,
382
+ context_chars: int = 400,
383
+ timeout: int = 10,
384
+ save_to_file: str = None,
385
+ headers: Dict[str, str] = None,
386
+ cookies: Dict[str, str] = None,
387
+ follow_redirects: bool = True,
388
+ ) -> str:
389
+ if not url.strip():
390
+ self.report_warning(tr("ℹ️ Empty URL provided."), ReportAction.READ)
391
+ return tr("Warning: Empty URL provided. Operation skipped.")
392
+
393
+ self.report_action(tr("🌐 Fetch URL '{url}' ...", url=url), ReportAction.READ)
394
+
395
+ # Check if we should save to file
396
+ if save_to_file:
397
+ html_content = self._fetch_url_content(
398
+ url,
399
+ timeout=timeout,
400
+ headers=headers,
401
+ cookies=cookies,
402
+ follow_redirects=follow_redirects,
403
+ )
404
+ if (
405
+ html_content.startswith("HTTP Error ")
406
+ or html_content == "Error"
407
+ or html_content == "Blocked"
408
+ ):
409
+ return html_content
410
+
411
+ try:
412
+ with open(save_to_file, "w", encoding="utf-8") as f:
413
+ f.write(html_content)
414
+ file_size = len(html_content)
415
+ self.report_success(
416
+ tr(
417
+ "✅ Saved {size} bytes to {file}",
418
+ size=file_size,
419
+ file=save_to_file,
420
+ ),
421
+ ReportAction.READ,
422
+ )
423
+ return tr("Successfully saved content to: {file}", file=save_to_file)
424
+ except IOError as e:
425
+ error_msg = tr("Error saving to file: {error}", error=str(e))
426
+ self.report_error(error_msg, ReportAction.READ)
427
+ return error_msg
428
+
429
+ # Normal processing path
430
+ html_content = self._fetch_url_content(
431
+ url,
432
+ timeout=timeout,
433
+ headers=headers,
434
+ cookies=cookies,
435
+ follow_redirects=follow_redirects,
436
+ )
437
+ if (
438
+ html_content.startswith("HTTP Error ")
439
+ or html_content == "Error"
440
+ or html_content == "Blocked"
441
+ ):
442
+ return html_content
443
+
444
+ # Extract and clean text
445
+ text = self._extract_and_clean_text(html_content)
446
+
447
+ # Filter by search strings if provided
448
+ if search_strings:
449
+ text = self._filter_by_search_strings(text, search_strings, context_chars)
450
+
451
+ # Apply limits
452
+ text = self._apply_limits(text, max_length, max_lines)
453
+
454
+ # Report success
455
+ num_lines = len(text.splitlines())
456
+ total_chars = len(text)
457
+ self.report_success(
458
+ tr(
459
+ "✅ {num_lines} {line_word}, {chars} chars",
460
+ num_lines=num_lines,
461
+ line_word=pluralize("line", num_lines),
462
+ chars=total_chars,
463
+ ),
464
+ ReportAction.READ,
465
+ )
466
+ return text
@@ -0,0 +1,143 @@
1
+ from janito.tools.tool_base import ToolBase, ToolPermissions
2
+ from janito.report_events import ReportAction
3
+ from janito.plugins.tools.decorators import register_core_tool
4
+ from janito.tools.tool_utils import pluralize, display_path
5
+ from janito.dir_walk_utils import walk_dir_with_gitignore
6
+ from janito.i18n import tr
7
+ import fnmatch
8
+ import os
9
+ from janito.tools.path_utils import expand_path
10
+ from janito.tools.loop_protection_decorator import protect_against_loops
11
+
12
+
13
+ @register_core_tool
14
+ class FindFiles(ToolBase):
15
+ """
16
+ Find files or directories in one or more directories matching a pattern. Respects .gitignore.
17
+
18
+ If a path is an existing file, it is checked against the provided pattern(s) and included in the results if it matches. This allows find_files to be used to look for a specific set of filenames in a single call, as well as searching directories.
19
+
20
+ Args:
21
+ paths (str): String of one or more paths (space-separated) to search in. Each path can be a directory or a file.
22
+ pattern (str): File pattern(s) to match. Multiple patterns can be separated by spaces. Uses Unix shell-style wildcards (fnmatch), e.g. '*.py', 'data_??.csv', '[a-z]*.txt'.
23
+ - If the pattern ends with '/' or '\', only matching directory names (with trailing slash) are returned, not the files within those directories. For example, pattern '*/' will return only directories at the specified depth.
24
+ max_depth (int, optional): Maximum directory depth to search. If None, unlimited recursion. If 0, only the top-level directory. If 1, only the root directory (matches 'find . -maxdepth 1').
25
+ include_gitignored (bool, optional): If True, includes files/directories ignored by .gitignore. Defaults to False.
26
+ Returns:
27
+ str: Newline-separated list of matching file paths. Example:
28
+ "/path/to/file1.py\n/path/to/file2.py"
29
+ "Warning: Empty file pattern provided. Operation skipped."
30
+ """
31
+
32
+ permissions = ToolPermissions(read=True)
33
+ tool_name = "find_files"
34
+
35
+ def _match_directories(self, root, dirs, pat):
36
+ dir_output = set()
37
+ dir_pat = pat.rstrip("/\\")
38
+ for d in dirs:
39
+ if fnmatch.fnmatch(d, dir_pat):
40
+ dir_output.add(os.path.join(root, d) + os.sep)
41
+ return dir_output
42
+
43
+ def _match_files(self, root, files, pat):
44
+ file_output = set()
45
+ for filename in fnmatch.filter(files, pat):
46
+ file_output.add(os.path.join(root, filename))
47
+ return file_output
48
+
49
+ def _match_dirs_without_slash(self, root, dirs, pat):
50
+ dir_output = set()
51
+ for d in fnmatch.filter(dirs, pat):
52
+ dir_output.add(os.path.join(root, d))
53
+ return dir_output
54
+
55
+ def _handle_path(self, directory, patterns):
56
+ dir_output = set()
57
+ filename = os.path.basename(directory)
58
+ for pat in patterns:
59
+ # Only match files, not directories, for file paths
60
+ if not (pat.endswith("/") or pat.endswith("\\")):
61
+ if fnmatch.fnmatch(filename, pat):
62
+ dir_output.add(directory)
63
+ break
64
+ return dir_output
65
+
66
+ def _handle_directory_path(
67
+ self, directory, patterns, max_depth, include_gitignored
68
+ ):
69
+ dir_output = set()
70
+ for root, dirs, files in walk_dir_with_gitignore(
71
+ directory,
72
+ max_depth=max_depth,
73
+ include_gitignored=include_gitignored,
74
+ ):
75
+ for pat in patterns:
76
+ if pat.endswith("/") or pat.endswith("\\"):
77
+ dir_output.update(self._match_directories(root, dirs, pat))
78
+ else:
79
+ dir_output.update(self._match_files(root, files, pat))
80
+ dir_output.update(self._match_dirs_without_slash(root, dirs, pat))
81
+ return dir_output
82
+
83
+ def _report_search(self, pattern, disp_path, depth_msg):
84
+ self.report_action(
85
+ tr(
86
+ "🔍 Search for files '{pattern}' in '{disp_path}'{depth_msg} ...",
87
+ pattern=pattern,
88
+ disp_path=disp_path,
89
+ depth_msg=depth_msg,
90
+ ),
91
+ ReportAction.READ,
92
+ )
93
+
94
+ def _report_success(self, count):
95
+ self.report_success(
96
+ tr(
97
+ " ✅ {count} {file_word}",
98
+ count=count,
99
+ file_word=pluralize("file", count),
100
+ ),
101
+ ReportAction.READ,
102
+ )
103
+
104
+ def _format_output(self, directory, dir_output):
105
+ if directory.strip() == ".":
106
+ dir_output = {
107
+ p[2:] if (p.startswith("./") or p.startswith(".\\")) else p
108
+ for p in dir_output
109
+ }
110
+ return sorted(dir_output)
111
+
112
+ @protect_against_loops(max_calls=5, time_window=10.0, key_field="paths")
113
+ def run(
114
+ self,
115
+ paths: str,
116
+ pattern: str,
117
+ max_depth: int = None,
118
+ include_gitignored: bool = False,
119
+ ) -> str:
120
+ if not pattern:
121
+ self.report_warning(tr("ℹ️ Empty file pattern provided."), ReportAction.READ)
122
+ return tr("Warning: Empty file pattern provided. Operation skipped.")
123
+ patterns = pattern.split()
124
+ results = []
125
+ for directory in [expand_path(p) for p in paths.split()]:
126
+ disp_path = display_path(directory)
127
+ depth_msg = (
128
+ tr(" (max depth: {max_depth})", max_depth=max_depth)
129
+ if max_depth is not None and max_depth > 0
130
+ else ""
131
+ )
132
+ self._report_search(pattern, disp_path, depth_msg)
133
+ dir_output = set()
134
+ if os.path.isfile(directory):
135
+ dir_output = self._handle_path(directory, patterns)
136
+ elif os.path.isdir(directory):
137
+ dir_output = self._handle_directory_path(
138
+ directory, patterns, max_depth, include_gitignored
139
+ )
140
+ self._report_success(len(dir_output))
141
+ results.extend(self._format_output(directory, dir_output))
142
+ result = "\n".join(results)
143
+ return result
@@ -0,0 +1,7 @@
1
+ """
2
+ File outline tools for janito.
3
+ """
4
+
5
+ from .core import GetFileOutline
6
+
7
+ __all__ = ["GetFileOutline"]