janito 3.2.0__py3-none-any.whl → 3.3.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 (166) hide show
  1. janito/README.md +0 -3
  2. janito/cli/chat_mode/bindings.py +0 -26
  3. janito/cli/chat_mode/session.py +1 -12
  4. janito/cli/chat_mode/shell/commands/security/allowed_sites.py +33 -47
  5. janito/cli/cli_commands/list_plugins.py +8 -13
  6. janito/cli/core/model_guesser.py +24 -40
  7. janito/cli/prompt_core.py +9 -20
  8. janito/i18n/it.py +46 -46
  9. janito/llm/agent.py +16 -32
  10. janito/llm/driver.py +0 -8
  11. janito/{plugin_system → plugin_system_backup_20250825_070018}/core_loader.py +3 -76
  12. janito/{plugin_system → plugin_system_backup_20250825_070018}/core_loader_fixed.py +3 -79
  13. janito/plugins/__init__.py +21 -29
  14. janito/plugins/__main__.py +85 -0
  15. janito/plugins/base.py +57 -0
  16. janito/plugins/builtin.py +1 -1
  17. janito/plugins/core/filemanager/tools/copy_file.py +25 -1
  18. janito/plugins/core/filemanager/tools/create_directory.py +28 -1
  19. janito/plugins/core/filemanager/tools/create_file.py +27 -3
  20. janito/plugins/core/filemanager/tools/delete_text_in_file.py +1 -0
  21. janito/plugins/core/imagedisplay/plugin.py +1 -1
  22. janito/plugins/core_loader.py +144 -0
  23. janito/plugins/discovery.py +3 -3
  24. janito/plugins/example_plugin.py +1 -1
  25. janito/plugins/manager.py +1 -1
  26. janito/plugins_backup_20250825_070018/__init__.py +36 -0
  27. janito/{plugins → plugins_backup_20250825_070018}/auto_loader.py +11 -12
  28. janito/plugins_backup_20250825_070018/builtin.py +102 -0
  29. janito/plugins_backup_20250825_070018/config.py +84 -0
  30. janito/plugins_backup_20250825_070018/core/__init__.py +7 -0
  31. janito/plugins_backup_20250825_070018/core/codeanalyzer/__init__.py +43 -0
  32. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/get_file_outline/__init__.py +1 -0
  33. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/get_file_outline/core.py +122 -0
  34. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/search_text/__init__.py +1 -0
  35. janito/plugins_backup_20250825_070018/core/codeanalyzer/tools/search_text/core.py +205 -0
  36. janito/plugins_backup_20250825_070018/core/filemanager/__init__.py +124 -0
  37. janito/plugins_backup_20250825_070018/core/filemanager/tools/copy_file.py +87 -0
  38. janito/plugins_backup_20250825_070018/core/filemanager/tools/create_directory.py +70 -0
  39. janito/plugins_backup_20250825_070018/core/filemanager/tools/create_file.py +87 -0
  40. janito/plugins_backup_20250825_070018/core/filemanager/tools/delete_text_in_file.py +135 -0
  41. janito/plugins_backup_20250825_070018/core/filemanager/tools/find_files.py +143 -0
  42. janito/plugins_backup_20250825_070018/core/filemanager/tools/move_file.py +131 -0
  43. janito/plugins_backup_20250825_070018/core/filemanager/tools/read_files.py +58 -0
  44. janito/plugins_backup_20250825_070018/core/filemanager/tools/remove_directory.py +55 -0
  45. janito/plugins_backup_20250825_070018/core/filemanager/tools/remove_file.py +58 -0
  46. janito/plugins_backup_20250825_070018/core/filemanager/tools/replace_text_in_file.py +270 -0
  47. janito/plugins_backup_20250825_070018/core/filemanager/tools/validate_file_syntax/__init__.py +1 -0
  48. janito/plugins_backup_20250825_070018/core/filemanager/tools/validate_file_syntax/core.py +114 -0
  49. janito/plugins_backup_20250825_070018/core/filemanager/tools/view_file.py +172 -0
  50. janito/plugins_backup_20250825_070018/core/imagedisplay/__init__.py +14 -0
  51. janito/plugins_backup_20250825_070018/core/imagedisplay/plugin.py +51 -0
  52. janito/plugins_backup_20250825_070018/core/imagedisplay/tools/__init__.py +1 -0
  53. janito/plugins_backup_20250825_070018/core/imagedisplay/tools/show_image.py +83 -0
  54. janito/plugins_backup_20250825_070018/core/imagedisplay/tools/show_image_grid.py +84 -0
  55. janito/plugins_backup_20250825_070018/core/system/__init__.py +23 -0
  56. janito/plugins_backup_20250825_070018/core/system/tools/run_bash_command.py +183 -0
  57. janito/plugins_backup_20250825_070018/core/system/tools/run_powershell_command.py +218 -0
  58. janito/plugins_backup_20250825_070018/core_adapter.py +55 -0
  59. janito/plugins_backup_20250825_070018/dev/__init__.py +7 -0
  60. janito/plugins_backup_20250825_070018/dev/pythondev/__init__.py +37 -0
  61. janito/plugins_backup_20250825_070018/dev/pythondev/tools/python_code_run.py +172 -0
  62. janito/plugins_backup_20250825_070018/dev/pythondev/tools/python_command_run.py +171 -0
  63. janito/plugins_backup_20250825_070018/dev/pythondev/tools/python_file_run.py +172 -0
  64. janito/plugins_backup_20250825_070018/dev/visualization/__init__.py +23 -0
  65. janito/plugins_backup_20250825_070018/dev/visualization/tools/read_chart.py +259 -0
  66. janito/plugins_backup_20250825_070018/discovery.py +289 -0
  67. janito/{plugins → plugins_backup_20250825_070018}/discovery_core.py +9 -14
  68. janito/plugins_backup_20250825_070018/example_plugin.py +108 -0
  69. janito/plugins_backup_20250825_070018/manager.py +243 -0
  70. janito/{plugins → plugins_backup_20250825_070018}/tools/core_tools_plugin.py +10 -9
  71. janito/{plugins → plugins_backup_20250825_070018}/tools/create_file.py +2 -2
  72. janito/{plugins → plugins_backup_20250825_070018}/tools/delete_text_in_file.py +1 -0
  73. janito/plugins_backup_20250825_070018/tools/get_file_outline/java_outline.py +47 -0
  74. janito/plugins_backup_20250825_070018/tools/get_file_outline/markdown_outline.py +14 -0
  75. janito/plugins_backup_20250825_070018/tools/get_file_outline/python_outline.py +303 -0
  76. janito/plugins_backup_20250825_070018/tools/get_file_outline/search_outline.py +36 -0
  77. janito/plugins_backup_20250825_070018/tools/search_text/match_lines.py +67 -0
  78. janito/plugins_backup_20250825_070018/tools/search_text/pattern_utils.py +73 -0
  79. janito/plugins_backup_20250825_070018/tools/search_text/traverse_directory.py +145 -0
  80. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/css_validator.py +35 -0
  81. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/html_validator.py +100 -0
  82. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/jinja2_validator.py +50 -0
  83. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/js_validator.py +27 -0
  84. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/json_validator.py +6 -0
  85. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/markdown_validator.py +109 -0
  86. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/ps1_validator.py +32 -0
  87. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/python_validator.py +5 -0
  88. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/xml_validator.py +11 -0
  89. janito/plugins_backup_20250825_070018/tools/validate_file_syntax/yaml_validator.py +6 -0
  90. janito/plugins_backup_20250825_070018/ui/__init__.py +7 -0
  91. janito/plugins_backup_20250825_070018/ui/userinterface/__init__.py +16 -0
  92. janito/plugins_backup_20250825_070018/ui/userinterface/tools/ask_user.py +110 -0
  93. janito/plugins_backup_20250825_070018/web/__init__.py +7 -0
  94. janito/plugins_backup_20250825_070018/web/webtools/__init__.py +33 -0
  95. janito/plugins_backup_20250825_070018/web/webtools/tools/fetch_url.py +458 -0
  96. janito/plugins_backup_20250825_070018/web/webtools/tools/open_html_in_browser.py +51 -0
  97. janito/plugins_backup_20250825_070018/web/webtools/tools/open_url.py +37 -0
  98. janito/providers/__init__.py +0 -1
  99. janito/tools/base.py +31 -1
  100. janito/tools/cli_initializer.py +1 -1
  101. janito/tools/function_adapter.py +176 -0
  102. janito/tools/initialize.py +1 -1
  103. janito/tools/loop_protection_decorator.py +117 -114
  104. janito/tools/tool_base.py +142 -114
  105. janito/tools/tools_schema.py +12 -6
  106. {janito-3.2.0.dist-info → janito-3.3.0.dist-info}/METADATA +1 -1
  107. {janito-3.2.0.dist-info → janito-3.3.0.dist-info}/RECORD +160 -95
  108. janito/llm/cancellation_manager.py +0 -63
  109. janito/llm/enter_cancellation.py +0 -107
  110. janito/plugins/core_adapter.py +0 -131
  111. janito/providers/together/__init__.py +0 -1
  112. janito/providers/together/model_info.py +0 -69
  113. janito/providers/together/provider.py +0 -108
  114. /janito/{plugin_system → plugin_system_backup_20250825_070018}/__init__.py +0 -0
  115. /janito/{plugin_system → plugin_system_backup_20250825_070018}/base.py +0 -0
  116. /janito/{plugins → plugins_backup_20250825_070018}/auto_loader_fixed.py +0 -0
  117. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/get_file_outline/java_outline.py +0 -0
  118. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/get_file_outline/markdown_outline.py +0 -0
  119. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/get_file_outline/python_outline.py +0 -0
  120. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/get_file_outline/search_outline.py +0 -0
  121. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/search_text/match_lines.py +0 -0
  122. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/search_text/pattern_utils.py +0 -0
  123. /janito/{plugins → plugins_backup_20250825_070018/core/codeanalyzer}/tools/search_text/traverse_directory.py +0 -0
  124. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/css_validator.py +0 -0
  125. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/html_validator.py +0 -0
  126. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/jinja2_validator.py +0 -0
  127. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/js_validator.py +0 -0
  128. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/json_validator.py +0 -0
  129. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/markdown_validator.py +0 -0
  130. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/ps1_validator.py +0 -0
  131. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/python_validator.py +0 -0
  132. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/xml_validator.py +0 -0
  133. /janito/{plugins → plugins_backup_20250825_070018/core/filemanager}/tools/validate_file_syntax/yaml_validator.py +0 -0
  134. /janito/{plugins → plugins_backup_20250825_070018}/tools/__init__.py +0 -0
  135. /janito/{plugins → plugins_backup_20250825_070018}/tools/ask_user.py +0 -0
  136. /janito/{plugins → plugins_backup_20250825_070018}/tools/copy_file.py +0 -0
  137. /janito/{plugins → plugins_backup_20250825_070018}/tools/create_directory.py +0 -0
  138. /janito/{plugins → plugins_backup_20250825_070018}/tools/decorators.py +0 -0
  139. /janito/{plugins → plugins_backup_20250825_070018}/tools/fetch_url.py +0 -0
  140. /janito/{plugins → plugins_backup_20250825_070018}/tools/find_files.py +0 -0
  141. /janito/{plugins → plugins_backup_20250825_070018}/tools/get_file_outline/__init__.py +0 -0
  142. /janito/{plugins → plugins_backup_20250825_070018}/tools/get_file_outline/core.py +0 -0
  143. /janito/{plugins → plugins_backup_20250825_070018}/tools/move_file.py +0 -0
  144. /janito/{plugins → plugins_backup_20250825_070018}/tools/open_html_in_browser.py +0 -0
  145. /janito/{plugins → plugins_backup_20250825_070018}/tools/open_url.py +0 -0
  146. /janito/{plugins → plugins_backup_20250825_070018}/tools/python_code_run.py +0 -0
  147. /janito/{plugins → plugins_backup_20250825_070018}/tools/python_command_run.py +0 -0
  148. /janito/{plugins → plugins_backup_20250825_070018}/tools/python_file_run.py +0 -0
  149. /janito/{plugins → plugins_backup_20250825_070018}/tools/read_chart.py +0 -0
  150. /janito/{plugins → plugins_backup_20250825_070018}/tools/read_files.py +0 -0
  151. /janito/{plugins → plugins_backup_20250825_070018}/tools/remove_directory.py +0 -0
  152. /janito/{plugins → plugins_backup_20250825_070018}/tools/remove_file.py +0 -0
  153. /janito/{plugins → plugins_backup_20250825_070018}/tools/replace_text_in_file.py +0 -0
  154. /janito/{plugins → plugins_backup_20250825_070018}/tools/run_bash_command.py +0 -0
  155. /janito/{plugins → plugins_backup_20250825_070018}/tools/run_powershell_command.py +0 -0
  156. /janito/{plugins → plugins_backup_20250825_070018}/tools/search_text/__init__.py +0 -0
  157. /janito/{plugins → plugins_backup_20250825_070018}/tools/search_text/core.py +0 -0
  158. /janito/{plugins → plugins_backup_20250825_070018}/tools/show_image.py +0 -0
  159. /janito/{plugins → plugins_backup_20250825_070018}/tools/show_image_grid.py +0 -0
  160. /janito/{plugins → plugins_backup_20250825_070018}/tools/validate_file_syntax/__init__.py +0 -0
  161. /janito/{plugins → plugins_backup_20250825_070018}/tools/validate_file_syntax/core.py +0 -0
  162. /janito/{plugins → plugins_backup_20250825_070018}/tools/view_file.py +0 -0
  163. {janito-3.2.0.dist-info → janito-3.3.0.dist-info}/WHEEL +0 -0
  164. {janito-3.2.0.dist-info → janito-3.3.0.dist-info}/entry_points.txt +0 -0
  165. {janito-3.2.0.dist-info → janito-3.3.0.dist-info}/licenses/LICENSE +0 -0
  166. {janito-3.2.0.dist-info → janito-3.3.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,176 @@
1
+ """
2
+ Function-to-Tool adapter for core plugins.
3
+
4
+ This module provides a way to wrap function-based tools into proper ToolBase classes.
5
+ """
6
+
7
+ import inspect
8
+ from typing import Any, Dict, List, Optional, get_type_hints
9
+ from janito.tools.tool_base import ToolBase, ToolPermissions
10
+
11
+
12
+ class FunctionToolAdapter(ToolBase):
13
+ """
14
+ Adapter that wraps a function into a ToolBase class.
15
+
16
+ This adapter provides a unified interface for function-based tools by wrapping
17
+ individual functions with the ToolBase protocol. It handles parameter mapping
18
+ and validation automatically.
19
+
20
+ Parameters:
21
+ path (str): Target file path for file operations
22
+ content (str): File content to write or process
23
+ overwrite (bool): Whether to overwrite existing files (default: False)
24
+ sources (str): Source file(s) to copy from
25
+ target (str): Destination path for copy operations
26
+ recursive (bool): Whether to process directories recursively
27
+ from_line (int): Starting line number for file reading
28
+ to_line (int): Ending line number for file reading
29
+ search_text (str): Text to search for in files
30
+ replacement_text (str): Text to replace search matches with
31
+ use_regex (bool): Whether to treat search as regex pattern
32
+ case_sensitive (bool): Whether search should be case sensitive
33
+ max_depth (int): Maximum directory depth to search
34
+ include_gitignored (bool): Whether to include .gitignored files
35
+ timeout (int): Timeout in seconds for operations
36
+ require_confirmation (bool): Whether to require user confirmation
37
+ data (dict): Chart data for visualization tools
38
+ title (str): Chart title
39
+ width (int): Chart width in pixels
40
+ height (int): Chart height in pixels
41
+ query (str): Search query for text search
42
+ paths (str): Directory or file paths to search in
43
+ src_path (str): Source path for move operations
44
+ dest_path (str): Destination path for move operations
45
+ code (str): Python code to execute
46
+ pattern (str): File pattern to match (e.g., '*.py')
47
+ """
48
+
49
+ def __init__(self, func, tool_name: str = None, description: str = None):
50
+ super().__init__()
51
+ self._func = func
52
+ self.tool_name = tool_name or getattr(func, "tool_name", func.__name__)
53
+ self._description = description or func.__doc__ or f"Tool: {self.tool_name}"
54
+ self.permissions = ToolPermissions(read=True, write=True, execute=True)
55
+
56
+ def run(
57
+ self,
58
+ path: str = None,
59
+ content: str = None,
60
+ overwrite: bool = None,
61
+ sources: str = None,
62
+ target: str = None,
63
+ recursive: bool = None,
64
+ from_line: int = None,
65
+ to_line: int = None,
66
+ search_text: str = None,
67
+ replacement_text: str = None,
68
+ use_regex: bool = None,
69
+ case_sensitive: bool = None,
70
+ max_depth: int = None,
71
+ include_gitignored: bool = None,
72
+ timeout: int = None,
73
+ require_confirmation: bool = None,
74
+ data: dict = None,
75
+ title: str = None,
76
+ width: int = None,
77
+ height: int = None,
78
+ query: str = None,
79
+ paths: str = None,
80
+ src_path: str = None,
81
+ dest_path: str = None,
82
+ code: str = None,
83
+ pattern: str = None,
84
+ ) -> str:
85
+ """Execute the wrapped function."""
86
+ # Build kwargs from non-None parameters
87
+ import inspect
88
+
89
+ sig = inspect.signature(self._func)
90
+ filtered_kwargs = {}
91
+
92
+ # Map parameter names to their actual values
93
+ param_map = {
94
+ "path": path,
95
+ "content": content,
96
+ "overwrite": overwrite,
97
+ "sources": sources,
98
+ "target": target,
99
+ "recursive": recursive,
100
+ "from_line": from_line,
101
+ "to_line": to_line,
102
+ "search_text": search_text,
103
+ "replacement_text": replacement_text,
104
+ "use_regex": use_regex,
105
+ "case_sensitive": case_sensitive,
106
+ "max_depth": max_depth,
107
+ "include_gitignored": include_gitignored,
108
+ "timeout": timeout,
109
+ "require_confirmation": require_confirmation,
110
+ "data": data,
111
+ "title": title,
112
+ "width": width,
113
+ "height": height,
114
+ "query": query,
115
+ "paths": paths,
116
+ "src_path": src_path,
117
+ "dest_path": dest_path,
118
+ "code": code,
119
+ "pattern": pattern,
120
+ }
121
+
122
+ # Only include parameters that exist in the function signature
123
+ for name, param in sig.parameters.items():
124
+ if name in param_map and param_map[name] is not None:
125
+ filtered_kwargs[name] = param_map[name]
126
+
127
+ result = self._func(**filtered_kwargs)
128
+ return str(result) if result is not None else ""
129
+
130
+ def get_signature(self) -> Dict[str, Any]:
131
+ """Get function signature for documentation."""
132
+ sig = inspect.signature(self._func)
133
+ type_hints = get_type_hints(self._func)
134
+
135
+ params = {}
136
+ for name, param in sig.parameters.items():
137
+ param_info = {
138
+ "type": str(type_hints.get(name, Any)),
139
+ "default": (
140
+ param.default if param.default != inspect.Parameter.empty else None
141
+ ),
142
+ "required": param.default == inspect.Parameter.empty,
143
+ }
144
+ params[name] = param_info
145
+
146
+ return {
147
+ "name": self.tool_name,
148
+ "description": self._description,
149
+ "parameters": params,
150
+ "return_type": str(type_hints.get("return", Any)),
151
+ }
152
+
153
+
154
+ def create_function_tool(func, tool_name: str = None, description: str = None) -> type:
155
+ """
156
+ Create a ToolBase class from a function.
157
+
158
+ Args:
159
+ func: The function to wrap
160
+ tool_name: Optional custom tool name
161
+ description: Optional custom description
162
+
163
+ Returns:
164
+ A ToolBase subclass that wraps the function
165
+ """
166
+ # Resolve tool_name in outer scope
167
+ resolved_tool_name = tool_name or getattr(func, "tool_name", func.__name__)
168
+
169
+ class DynamicFunctionTool(FunctionToolAdapter):
170
+ permissions = ToolPermissions(read=True, write=True, execute=True)
171
+ tool_name = resolved_tool_name
172
+
173
+ def __init__(self):
174
+ super().__init__(func, DynamicFunctionTool.tool_name, description)
175
+
176
+ return DynamicFunctionTool
@@ -9,7 +9,7 @@ import sys
9
9
  from pathlib import Path
10
10
  from typing import List, Optional
11
11
 
12
- from janito.plugin_system.core_loader_fixed import load_core_plugin
12
+ from janito.plugins.core_loader import load_core_plugin
13
13
  from janito.tools.adapters.local.adapter import LocalToolsAdapter
14
14
 
15
15
 
@@ -1,140 +1,143 @@
1
1
  import functools
2
2
  import time
3
3
  import threading
4
- from typing import Any, Tuple
4
+ from typing import Callable, Any
5
+ from janito.tools.loop_protection import LoopProtection
6
+ from janito.tools.tool_use_tracker import normalize_path
7
+
5
8
 
6
9
  # Global tracking for decorator-based loop protection
7
10
  _decorator_call_tracker = {}
8
11
  _decorator_call_tracker_lock = threading.Lock()
9
12
 
10
13
 
11
- def _normalize_key_value(key_field: str, key_value: Any) -> Any:
12
- """Normalize key values, especially paths, so different representations map to the same key."""
13
- if key_value is None:
14
- return None
15
-
16
- try:
17
- if isinstance(key_field, str) and "path" in key_field.lower():
18
- from janito.tools.tool_use_tracker import (
19
- normalize_path as _norm, # reuse existing normalization
20
- )
21
-
22
- if isinstance(key_value, str):
23
- return _norm(key_value)
24
- if isinstance(key_value, (list, tuple)):
25
- return tuple(_norm(v) if isinstance(v, str) else v for v in key_value)
26
- except Exception:
27
- # Best-effort normalization – fall back to original value
28
- pass
29
-
30
- return key_value
31
-
32
-
33
- def _get_param_value(func, args, kwargs, key_field: str):
34
- """Extract the watched parameter value from args/kwargs using function signature."""
35
- if key_field in kwargs:
36
- return kwargs[key_field]
37
-
38
- # Handle positional arguments by mapping to parameter names
39
- if len(args) > 1: # args[0] is self
40
- import inspect
41
-
42
- try:
43
- sig = inspect.signature(func)
44
- param_names = list(sig.parameters.keys())
45
- if key_field in param_names:
46
- idx = param_names.index(key_field)
47
- if idx < len(args):
48
- return args[idx]
49
- except Exception:
50
- return None
51
-
52
- return None
53
-
54
-
55
- def _determine_operation_name(func, args, kwargs, key_field: str) -> str:
56
- """Build the operation name for rate limiting, optionally including a normalized key value."""
57
- if key_field:
58
- raw_value = _get_param_value(func, args, kwargs, key_field)
59
- if raw_value is not None:
60
- norm_value = _normalize_key_value(key_field, raw_value)
61
- return f"{func.__name__}_{norm_value}"
62
- return func.__name__
63
-
64
-
65
- def _check_and_record(
66
- op_name: str,
67
- current_time: float,
68
- time_window: float,
69
- max_calls: int,
70
- tool_instance: Any,
71
- ) -> Tuple[bool, str]:
72
- """Check loop limits for op_name and record the call. Returns (exceeded, message)."""
73
- with _decorator_call_tracker_lock:
74
- # Clean old timestamps
75
- if op_name in _decorator_call_tracker:
76
- _decorator_call_tracker[op_name] = [
77
- ts
78
- for ts in _decorator_call_tracker[op_name]
79
- if current_time - ts <= time_window
80
- ]
81
-
82
- # Check limit
83
- if (
84
- op_name in _decorator_call_tracker
85
- and len(_decorator_call_tracker[op_name]) >= max_calls
86
- ):
87
- if all(
88
- current_time - ts <= time_window
89
- for ts in _decorator_call_tracker[op_name]
90
- ):
91
- msg = (
92
- f"Loop protection: Too many {op_name} operations in a short time period "
93
- f"({max_calls} calls in {time_window}s). Please try a different approach or wait before retrying."
94
- )
95
- if hasattr(tool_instance, "report_error"):
96
- try:
97
- tool_instance.report_error(msg)
98
- except Exception:
99
- pass
100
- return True, msg
101
-
102
- # Record this call
103
- if op_name not in _decorator_call_tracker:
104
- _decorator_call_tracker[op_name] = []
105
- _decorator_call_tracker[op_name].append(current_time)
106
-
107
- return False, ""
108
-
109
-
110
14
  def protect_against_loops(
111
15
  max_calls: int = 5, time_window: float = 10.0, key_field: str = None
112
16
  ):
113
17
  """
114
18
  Decorator that adds loop protection to tool run methods.
115
19
 
116
- Tracks calls within a sliding time window and prevents excessive repeated operations.
117
- When key_field is provided, the limit is applied per unique normalized value of that parameter
118
- (e.g., per-path protection for file tools).
20
+ This decorator monitors tool executions and prevents excessive calls within
21
+ a configurable time window. It helps prevent infinite loops or excessive
22
+ resource consumption when tools are called repeatedly.
23
+
24
+ When the configured limits are exceeded, the decorator raises a RuntimeError
25
+ with a descriptive message. This exception will propagate up the call stack
26
+ unless caught by a try/except block in the calling code.
27
+
28
+ The decorator works by:
29
+ 1. Tracking the number of calls to the decorated function
30
+ 2. Checking if the calls exceed the configured limits
31
+ 3. Raising a RuntimeError if a potential loop is detected
32
+ 4. Allowing the method to proceed normally if the operation is safe
33
+
34
+ Args:
35
+ max_calls (int): Maximum number of calls allowed within the time window.
36
+ Defaults to 5 calls.
37
+ time_window (float): Time window in seconds for detecting excessive calls.
38
+ Defaults to 10.0 seconds.
39
+ key_field (str, optional): The parameter name to use for key matching instead of function name.
40
+ If provided, the decorator will track calls based on the value of this
41
+ parameter rather than the function name. Useful for tools that operate
42
+ on specific files or resources.
43
+
44
+ Example:
45
+ >>> @protect_against_loops(max_calls=3, time_window=5.0)
46
+ >>> def run(self, path: str) -> str:
47
+ >>> # Implementation here
48
+ >>> pass
49
+
50
+ >>> @protect_against_loops(max_calls=10, time_window=30.0)
51
+ >>> def run(self, file_paths: list) -> str:
52
+ >>> # Implementation here
53
+ >>> pass
54
+
55
+ >>> @protect_against_loops(max_calls=5, time_window=10.0, key_field='path')
56
+ >>> def run(self, path: str) -> str:
57
+ >>> # This will track calls per unique path value
58
+ >>> pass
59
+
60
+ Note:
61
+ When loop protection is triggered, a RuntimeError will be raised with a
62
+ descriptive message. This exception will propagate up the call stack
63
+ unless caught by a try/except block in the calling code.
119
64
  """
120
65
 
121
66
  def decorator(func):
122
67
  @functools.wraps(func)
123
68
  def wrapper(*args, **kwargs):
124
- # Methods should always have self; if not, execute directly.
69
+ # Get the tool instance (self)
125
70
  if not args:
71
+ # This shouldn't happen in normal usage as methods need self
126
72
  return func(*args, **kwargs)
127
73
 
128
- op_name = _determine_operation_name(func, args, kwargs, key_field)
129
- exceeded, msg = _check_and_record(
130
- op_name=op_name,
131
- current_time=time.time(),
132
- time_window=time_window,
133
- max_calls=max_calls,
134
- tool_instance=args[0],
135
- )
136
- if exceeded:
137
- return msg
74
+ # Determine the operation key
75
+ if key_field:
76
+ # Use the key_field parameter value as the operation key
77
+ key_value = None
78
+ if key_field in kwargs:
79
+ key_value = kwargs[key_field]
80
+ elif len(args) > 1:
81
+ # Handle positional arguments - need to map parameter names
82
+ import inspect
83
+
84
+ try:
85
+ sig = inspect.signature(func)
86
+ param_names = list(sig.parameters.keys())
87
+ if key_field in param_names:
88
+ field_index = param_names.index(key_field)
89
+ if field_index < len(args):
90
+ key_value = args[field_index]
91
+ except (ValueError, TypeError):
92
+ pass
93
+
94
+ if key_value is not None:
95
+ op_name = f"{func.__name__}_{key_value}"
96
+ else:
97
+ op_name = func.__name__
98
+ else:
99
+ # Use the function name as the operation name
100
+ op_name = func.__name__
101
+
102
+ # Check call limits
103
+ current_time = time.time()
104
+
105
+ with _decorator_call_tracker_lock:
106
+ # Clean up old entries outside the time window
107
+ if op_name in _decorator_call_tracker:
108
+ _decorator_call_tracker[op_name] = [
109
+ timestamp
110
+ for timestamp in _decorator_call_tracker[op_name]
111
+ if current_time - timestamp <= time_window
112
+ ]
113
+
114
+ # Check if we're exceeding the limit
115
+ if op_name in _decorator_call_tracker:
116
+ if len(_decorator_call_tracker[op_name]) >= max_calls:
117
+ # Check if all recent calls are within the time window
118
+ if all(
119
+ current_time - timestamp <= time_window
120
+ for timestamp in _decorator_call_tracker[op_name]
121
+ ):
122
+ # Return loop protection message as string instead of raising exception
123
+ error_msg = f"Loop protection: Too many {op_name} operations in a short time period ({max_calls} calls in {time_window}s). Please try a different approach or wait before retrying."
124
+
125
+ # Try to report the error through the tool's reporting mechanism
126
+ tool_instance = args[0] if args else None
127
+ if hasattr(tool_instance, "report_error"):
128
+ try:
129
+ tool_instance.report_error(error_msg)
130
+ except Exception:
131
+ pass # If reporting fails, we still return the message
132
+
133
+ return error_msg
134
+
135
+ # Record this call
136
+ if op_name not in _decorator_call_tracker:
137
+ _decorator_call_tracker[op_name] = []
138
+ _decorator_call_tracker[op_name].append(current_time)
139
+
140
+ # Proceed with the original function
138
141
  return func(*args, **kwargs)
139
142
 
140
143
  return wrapper