janito 2.33.0__py3-none-any.whl → 3.1.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 (147) hide show
  1. janito/cli/chat_mode/bindings.py +26 -0
  2. janito/cli/chat_mode/session.py +7 -1
  3. janito/cli/cli_commands/check_tools.py +212 -0
  4. janito/cli/cli_commands/list_plugins.py +52 -43
  5. janito/cli/core/getters.py +3 -0
  6. janito/cli/main_cli.py +9 -12
  7. janito/cli/prompt_core.py +19 -9
  8. janito/drivers/openai/driver.py +1 -0
  9. janito/drivers/zai/driver.py +1 -0
  10. janito/llm/agent.py +30 -17
  11. janito/llm/auth_utils.py +14 -5
  12. janito/llm/cancellation_manager.py +62 -0
  13. janito/llm/driver.py +7 -0
  14. janito/llm/enter_cancellation.py +93 -0
  15. janito/plugin_system/__init__.py +10 -0
  16. janito/{plugins → plugin_system}/base.py +5 -2
  17. janito/{plugins/core_loader_fixed.py → plugin_system/core_loader.py} +45 -26
  18. janito/plugin_system/core_loader_fixed.py +149 -0
  19. janito/plugins/__init__.py +31 -12
  20. janito/plugins/auto_loader_fixed.py +12 -11
  21. janito/plugins/builtin.py +15 -1
  22. janito/plugins/core/__init__.py +7 -0
  23. janito/plugins/core/codeanalyzer/__init__.py +43 -0
  24. janito/plugins/core/filemanager/__init__.py +124 -0
  25. janito/plugins/core/filemanager/tools/create_file.py +87 -0
  26. janito/plugins/core/filemanager/tools/replace_text_in_file.py +270 -0
  27. janito/plugins/core/imagedisplay/__init__.py +14 -0
  28. janito/plugins/core/imagedisplay/plugin.py +51 -0
  29. janito/plugins/core/imagedisplay/tools/__init__.py +1 -0
  30. janito/plugins/core/imagedisplay/tools/show_image.py +83 -0
  31. janito/{tools/adapters/local → plugins/core/imagedisplay/tools}/show_image_grid.py +13 -5
  32. janito/plugins/core/system/__init__.py +23 -0
  33. janito/plugins/core_adapter.py +11 -9
  34. janito/plugins/dev/__init__.py +7 -0
  35. janito/plugins/dev/pythondev/__init__.py +37 -0
  36. janito/plugins/dev/visualization/__init__.py +23 -0
  37. janito/plugins/discovery.py +5 -5
  38. janito/plugins/example_plugin.py +108 -0
  39. janito/plugins/manager.py +1 -1
  40. janito/plugins/tools/__init__.py +10 -0
  41. janito/{tools/adapters/local → plugins/tools}/ask_user.py +3 -3
  42. janito/plugins/tools/copy_file.py +87 -0
  43. janito/plugins/tools/core_tools_plugin.py +88 -0
  44. janito/plugins/tools/create_directory.py +70 -0
  45. janito/{tools/adapters/local → plugins/tools}/create_file.py +4 -4
  46. janito/plugins/tools/decorators.py +19 -0
  47. janito/plugins/tools/delete_text_in_file.py +134 -0
  48. janito/{tools/adapters/local → plugins/tools}/fetch_url.py +3 -3
  49. janito/plugins/tools/find_files.py +143 -0
  50. janito/plugins/tools/get_file_outline/__init__.py +7 -0
  51. janito/plugins/tools/get_file_outline/core.py +122 -0
  52. janito/plugins/tools/get_file_outline/java_outline.py +47 -0
  53. janito/plugins/tools/get_file_outline/markdown_outline.py +14 -0
  54. janito/plugins/tools/get_file_outline/python_outline.py +303 -0
  55. janito/plugins/tools/get_file_outline/search_outline.py +36 -0
  56. janito/plugins/tools/move_file.py +131 -0
  57. janito/plugins/tools/open_html_in_browser.py +51 -0
  58. janito/plugins/tools/open_url.py +37 -0
  59. janito/plugins/tools/python_code_run.py +172 -0
  60. janito/plugins/tools/python_command_run.py +171 -0
  61. janito/plugins/tools/python_file_run.py +172 -0
  62. janito/plugins/tools/read_chart.py +259 -0
  63. janito/plugins/tools/read_files.py +58 -0
  64. janito/plugins/tools/remove_directory.py +55 -0
  65. janito/plugins/tools/remove_file.py +58 -0
  66. janito/{tools/adapters/local → plugins/tools}/replace_text_in_file.py +4 -4
  67. janito/plugins/tools/run_bash_command.py +183 -0
  68. janito/plugins/tools/run_powershell_command.py +218 -0
  69. janito/plugins/tools/search_text/__init__.py +7 -0
  70. janito/plugins/tools/search_text/core.py +205 -0
  71. janito/plugins/tools/search_text/match_lines.py +67 -0
  72. janito/plugins/tools/search_text/pattern_utils.py +73 -0
  73. janito/plugins/tools/search_text/traverse_directory.py +145 -0
  74. janito/{tools/adapters/local → plugins/tools}/show_image.py +15 -6
  75. janito/plugins/tools/show_image_grid.py +85 -0
  76. janito/plugins/tools/validate_file_syntax/__init__.py +7 -0
  77. janito/plugins/tools/validate_file_syntax/core.py +114 -0
  78. janito/plugins/tools/validate_file_syntax/css_validator.py +35 -0
  79. janito/plugins/tools/validate_file_syntax/html_validator.py +100 -0
  80. janito/plugins/tools/validate_file_syntax/jinja2_validator.py +50 -0
  81. janito/plugins/tools/validate_file_syntax/js_validator.py +27 -0
  82. janito/plugins/tools/validate_file_syntax/json_validator.py +6 -0
  83. janito/plugins/tools/validate_file_syntax/markdown_validator.py +109 -0
  84. janito/plugins/tools/validate_file_syntax/ps1_validator.py +32 -0
  85. janito/plugins/tools/validate_file_syntax/python_validator.py +5 -0
  86. janito/plugins/tools/validate_file_syntax/xml_validator.py +11 -0
  87. janito/plugins/tools/validate_file_syntax/yaml_validator.py +6 -0
  88. janito/plugins/tools/view_file.py +172 -0
  89. janito/plugins/ui/__init__.py +7 -0
  90. janito/plugins/ui/userinterface/__init__.py +16 -0
  91. janito/plugins/ui/userinterface/tools/ask_user.py +110 -0
  92. janito/plugins/web/__init__.py +7 -0
  93. janito/plugins/web/webtools/__init__.py +33 -0
  94. janito/plugins/web/webtools/tools/fetch_url.py +458 -0
  95. janito/tools/__init__.py +31 -7
  96. janito/tools/adapters/__init__.py +6 -1
  97. janito/tools/adapters/local/__init__.py +7 -70
  98. janito/tools/cli_initializer.py +88 -0
  99. janito/tools/function_adapter.py +93 -16
  100. janito/tools/initialize.py +70 -0
  101. {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/METADATA +1 -2
  102. {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/RECORD +146 -76
  103. janito/plugins/core_loader.py +0 -120
  104. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/__init__.py +0 -0
  105. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/core.py +0 -0
  106. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/java_outline.py +0 -0
  107. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/markdown_outline.py +0 -0
  108. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/python_outline.py +0 -0
  109. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/search_outline.py +0 -0
  110. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/__init__.py +0 -0
  111. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/core.py +0 -0
  112. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/match_lines.py +0 -0
  113. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/pattern_utils.py +0 -0
  114. /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/traverse_directory.py +0 -0
  115. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/copy_file.py +0 -0
  116. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/create_directory.py +0 -0
  117. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/delete_text_in_file.py +0 -0
  118. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/find_files.py +0 -0
  119. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/move_file.py +0 -0
  120. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/read_files.py +0 -0
  121. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_directory.py +0 -0
  122. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_file.py +0 -0
  123. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/__init__.py +0 -0
  124. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/core.py +0 -0
  125. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/css_validator.py +0 -0
  126. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/html_validator.py +0 -0
  127. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/jinja2_validator.py +0 -0
  128. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/js_validator.py +0 -0
  129. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/json_validator.py +0 -0
  130. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/markdown_validator.py +0 -0
  131. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/ps1_validator.py +0 -0
  132. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/python_validator.py +0 -0
  133. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/xml_validator.py +0 -0
  134. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/yaml_validator.py +0 -0
  135. /janito/{tools/adapters/local → plugins/core/filemanager/tools}/view_file.py +0 -0
  136. /janito/{tools/adapters/local → plugins/core/system/tools}/run_bash_command.py +0 -0
  137. /janito/{tools/adapters/local → plugins/core/system/tools}/run_powershell_command.py +0 -0
  138. /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_code_run.py +0 -0
  139. /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_command_run.py +0 -0
  140. /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_file_run.py +0 -0
  141. /janito/{tools/adapters/local → plugins/dev/visualization/tools}/read_chart.py +0 -0
  142. /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_html_in_browser.py +0 -0
  143. /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_url.py +0 -0
  144. {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/WHEEL +0 -0
  145. {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/entry_points.txt +0 -0
  146. {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/licenses/LICENSE +0 -0
  147. {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,43 @@
1
+ """
2
+ Code Analyzer Plugin
3
+
4
+ Tools for understanding and searching code structure.
5
+ """
6
+
7
+ from typing import List, Optional
8
+
9
+
10
+ def get_file_outline(path: str) -> str:
11
+ """Get file structure (classes, functions, etc.)"""
12
+ return f"get_file_outline(path='{path}')"
13
+
14
+
15
+ get_file_outline.tool_name = "get_file_outline"
16
+
17
+
18
+ def search_outline(path: str) -> str:
19
+ """Search within file outlines"""
20
+ return f"search_outline(path='{path}')"
21
+
22
+
23
+ search_outline.tool_name = "search_outline"
24
+
25
+
26
+ def search_text(
27
+ paths: str,
28
+ query: str,
29
+ use_regex: bool = False,
30
+ case_sensitive: bool = True,
31
+ max_depth: Optional[int] = None,
32
+ ) -> str:
33
+ """Full-text search across files with regex support"""
34
+ return f"search_text(paths='{paths}', query='{query}', regex={use_regex})"
35
+
36
+
37
+ search_text.tool_name = "search_text"
38
+
39
+
40
+ # Plugin metadata
41
+ __plugin_name__ = "core.codeanalyzer"
42
+ __plugin_description__ = "Code analysis and structure understanding"
43
+ __plugin_tools__ = [get_file_outline, search_outline, search_text]
@@ -0,0 +1,124 @@
1
+ """
2
+ File Manager Plugin
3
+
4
+ Core file and directory operations for managing project files.
5
+ """
6
+
7
+ from typing import List, Optional
8
+ import os
9
+
10
+
11
+ def create_file(path: str, content: str = "", overwrite: bool = False) -> str:
12
+ """Create a new file with content"""
13
+ return f"create_file(path='{path}', content='{len(content)} chars', overwrite={overwrite})"
14
+
15
+
16
+ create_file.tool_name = "create_file"
17
+
18
+
19
+ def read_files(paths: List[str]) -> str:
20
+ """Read multiple files at once"""
21
+ return f"read_files(paths={paths})"
22
+
23
+
24
+ read_files.tool_name = "read_files"
25
+
26
+
27
+ def view_file(
28
+ path: str, from_line: Optional[int] = None, to_line: Optional[int] = None
29
+ ) -> str:
30
+ """Read specific lines or entire files"""
31
+ range_str = f"{from_line}-{to_line}" if from_line or to_line else "all"
32
+ return f"view_file(path='{path}', range='{range_str}')"
33
+
34
+
35
+ view_file.tool_name = "view_file"
36
+
37
+
38
+ def replace_text_in_file(
39
+ path: str, search_text: str, replacement_text: str, replace_all: bool = True
40
+ ) -> str:
41
+ """Find and replace text in files"""
42
+ return f"replace_text_in_file(path='{path}', search='{search_text[:20]}...', replace='{replacement_text[:20]}...')"
43
+
44
+
45
+ replace_text_in_file.tool_name = "replace_text_in_file"
46
+
47
+
48
+ def validate_file_syntax(path: str) -> str:
49
+ """Check file syntax (Python/Markdown)"""
50
+ return f"validate_file_syntax(path='{path}')"
51
+
52
+
53
+ validate_file_syntax.tool_name = "validate_file_syntax"
54
+
55
+
56
+ def create_directory(path: str) -> str:
57
+ """Create new directories"""
58
+ return f"create_directory(path='{path}')"
59
+
60
+
61
+ create_directory.tool_name = "create_directory"
62
+
63
+
64
+ def remove_directory(path: str, recursive: bool = False) -> str:
65
+ """Remove directories (recursive option)"""
66
+ return f"remove_directory(path='{path}', recursive={recursive})"
67
+
68
+
69
+ remove_directory.tool_name = "remove_directory"
70
+
71
+
72
+ def remove_file(path: str) -> str:
73
+ """Delete single files"""
74
+ return f"remove_file(path='{path}')"
75
+
76
+
77
+ remove_file.tool_name = "remove_file"
78
+
79
+
80
+ def copy_file(sources: str, target: str, overwrite: bool = False) -> str:
81
+ """Copy files or directories"""
82
+ return f"copy_file(sources='{sources}', target='{target}', overwrite={overwrite})"
83
+
84
+
85
+ copy_file.tool_name = "copy_file"
86
+
87
+
88
+ def move_file(src_path: str, dest_path: str, overwrite: bool = False) -> str:
89
+ """Move/rename files or directories"""
90
+ return f"move_file(src='{src_path}', dest='{dest_path}', overwrite={overwrite})"
91
+
92
+
93
+ move_file.tool_name = "move_file"
94
+
95
+
96
+ def find_files(
97
+ paths: str,
98
+ pattern: str,
99
+ max_depth: Optional[int] = None,
100
+ include_gitignored: bool = False,
101
+ ) -> str:
102
+ """Search for files by pattern (respects .gitignore)"""
103
+ return f"find_files(paths='{paths}', pattern='{pattern}', max_depth={max_depth})"
104
+
105
+
106
+ find_files.tool_name = "find_files"
107
+
108
+
109
+ # Plugin metadata
110
+ __plugin_name__ = "core.filemanager"
111
+ __plugin_description__ = "Core file and directory operations"
112
+ __plugin_tools__ = [
113
+ create_file,
114
+ read_files,
115
+ view_file,
116
+ replace_text_in_file,
117
+ validate_file_syntax,
118
+ create_directory,
119
+ remove_directory,
120
+ remove_file,
121
+ copy_file,
122
+ move_file,
123
+ find_files,
124
+ ]
@@ -0,0 +1,87 @@
1
+ import os
2
+ from janito.tools.path_utils import expand_path
3
+ from janito.tools.adapters.local.adapter import register_local_tool
4
+
5
+ from janito.tools.tool_utils import display_path
6
+ from janito.tools.tool_base import ToolBase, ToolPermissions
7
+ from janito.report_events import ReportAction
8
+ from janito.i18n import tr
9
+ from janito.tools.loop_protection_decorator import protect_against_loops
10
+
11
+ from janito.tools.adapters.local.validate_file_syntax.core import validate_file_syntax
12
+
13
+
14
+ @register_local_tool
15
+ class CreateFileTool(ToolBase):
16
+ """
17
+ Create a new file with the given content.
18
+
19
+ Args:
20
+ path (str): Path to the file to create.
21
+ content (str): Content to write to the file.
22
+ overwrite (bool, optional): Overwrite existing file if True. Default: False. Recommended only after reading the file to be overwritten.
23
+ Returns:
24
+ str: Status message indicating the result. Example:
25
+ - "✅ Successfully created the file at ..."
26
+
27
+ Note: Syntax validation is automatically performed after this operation.
28
+
29
+ Security: This tool includes loop protection to prevent excessive file creation operations.
30
+ Maximum 5 calls per 10 seconds for the same file path.
31
+ """
32
+
33
+ permissions = ToolPermissions(write=True)
34
+ tool_name = "create_file"
35
+
36
+ @protect_against_loops(max_calls=5, time_window=10.0, key_field="path")
37
+ def run(self, path: str, content: str, overwrite: bool = False) -> str:
38
+ path = expand_path(path)
39
+ disp_path = display_path(path)
40
+ if os.path.exists(path) and not overwrite:
41
+ try:
42
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
43
+ existing_content = f.read()
44
+ except Exception as e:
45
+ existing_content = f"[Error reading file: {e}]"
46
+ return tr(
47
+ "❗ Cannot create file: file already exists at '{disp_path}'.\n--- Current file content ---\n{existing_content}",
48
+ disp_path=disp_path,
49
+ existing_content=existing_content,
50
+ )
51
+ # Determine if we are overwriting an existing file
52
+ is_overwrite = os.path.exists(path) and overwrite
53
+ if is_overwrite:
54
+ # Overwrite branch: log only overwrite warning (no create message)
55
+ self.report_action(
56
+ tr("⚠️ Overwriting file '{disp_path}'", disp_path=disp_path),
57
+ ReportAction.CREATE,
58
+ )
59
+ dir_name = os.path.dirname(path)
60
+ if dir_name:
61
+ os.makedirs(dir_name, exist_ok=True)
62
+ if not is_overwrite:
63
+ # Create branch: log file creation message
64
+ self.report_action(
65
+ tr("📝 Create file '{disp_path}' ...", disp_path=disp_path),
66
+ ReportAction.CREATE,
67
+ )
68
+ with open(path, "w", encoding="utf-8", errors="replace") as f:
69
+ f.write(content)
70
+ new_lines = content.count("\n") + 1 if content else 0
71
+ self.report_success(
72
+ tr("✅ {new_lines} lines", new_lines=new_lines), ReportAction.CREATE
73
+ )
74
+ # Perform syntax validation and append result
75
+ validation_result = validate_file_syntax(path)
76
+ if is_overwrite:
77
+ # Overwrite branch: return minimal overwrite info to user
78
+ return (
79
+ tr("✅ {new_lines} lines", new_lines=new_lines)
80
+ + f"\n{validation_result}"
81
+ )
82
+ else:
83
+ # Create branch: return detailed create success to user
84
+ return (
85
+ tr("✅ Created file {new_lines} lines.", new_lines=new_lines)
86
+ + f"\n{validation_result}"
87
+ )
@@ -0,0 +1,270 @@
1
+ from janito.tools.tool_base import ToolBase, ToolPermissions
2
+ from janito.report_events import ReportAction
3
+ from janito.tools.adapters.local.adapter import register_local_tool
4
+ from janito.i18n import tr
5
+ import shutil
6
+ import re
7
+ from janito.tools.adapters.local.validate_file_syntax.core import validate_file_syntax
8
+
9
+
10
+ @register_local_tool
11
+ class ReplaceTextInFileTool(ToolBase):
12
+ """
13
+ Replace exact occurrences of a given text in a file.
14
+
15
+ Note:
16
+ To avoid syntax errors, ensure your replacement text is pre-indented as needed, matching the indentation of the
17
+ search text in its original location.
18
+
19
+ Args:
20
+ path (str): Path to the file to modify.
21
+ search_text (str): The exact text to search for (including indentation).
22
+ replacement_text (str): The text to replace with (including indentation).
23
+ replace_all (bool): If True, replace all occurrences; otherwise, only the first occurrence.
24
+ backup (bool, optional): Deprecated. No backups are created anymore and this flag is ignored. Defaults to False.
25
+ Returns:
26
+ str: Status message. Example:
27
+ - "Text replaced in /path/to/file"
28
+ - "No changes made. [Warning: Search text not found in file] Please review the original file."
29
+ - "Error replacing text: <error message>"
30
+ """
31
+
32
+ permissions = ToolPermissions(read=True, write=True)
33
+ tool_name = "replace_text_in_file"
34
+
35
+ def run(
36
+ self,
37
+ path: str,
38
+ search_text: str,
39
+ replacement_text: str,
40
+ replace_all: bool = False,
41
+ backup: bool = False,
42
+ ) -> str:
43
+ from janito.tools.tool_utils import display_path
44
+
45
+ disp_path = display_path(path)
46
+ action = "(all)" if replace_all else ""
47
+ search_lines = len(search_text.splitlines())
48
+ replace_lines = len(replacement_text.splitlines())
49
+ info_msg = self._format_info_msg(
50
+ disp_path,
51
+ search_lines,
52
+ replace_lines,
53
+ action,
54
+ search_text,
55
+ replacement_text,
56
+ path,
57
+ )
58
+ self.report_action(info_msg, ReportAction.CREATE)
59
+ try:
60
+ content = self._read_file_content(path)
61
+ match_lines = self._find_match_lines(content, search_text)
62
+ occurrences = content.count(search_text)
63
+ replaced_count, new_content = self._replace_content(
64
+ content, search_text, replacement_text, replace_all, occurrences
65
+ )
66
+ file_changed = new_content != content
67
+ backup_path = None
68
+ validation_result = ""
69
+ if file_changed:
70
+ self._write_file_content(path, new_content)
71
+ # Perform syntax validation and append result
72
+ validation_result = validate_file_syntax(path)
73
+ warning, concise_warning = self._handle_warnings(
74
+ replaced_count, file_changed, occurrences
75
+ )
76
+
77
+ if concise_warning:
78
+ return concise_warning
79
+ self._report_success(match_lines)
80
+ line_delta_str = self._get_line_delta_str(content, new_content)
81
+ match_info, details = self._format_match_details(
82
+ replaced_count,
83
+ match_lines,
84
+ search_lines,
85
+ replace_lines,
86
+ line_delta_str,
87
+ replace_all,
88
+ )
89
+ return self._format_final_msg(path, warning, match_info, details) + (
90
+ f"\n{validation_result}" if validation_result else ""
91
+ )
92
+ except Exception as e:
93
+ self.report_error(tr(" ❌ Error"), ReportAction.UPDATE)
94
+ return tr("Error replacing text: {error}", error=e)
95
+
96
+ def _read_file_content(self, path):
97
+ """Read the entire content of the file."""
98
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
99
+ return f.read()
100
+
101
+ def _find_match_lines(self, content, search_text):
102
+ """Find all line numbers where search_text occurs in content."""
103
+ lines = content.splitlines(keepends=True)
104
+ joined = "".join(lines)
105
+ match_lines = []
106
+ idx = 0
107
+ while True:
108
+ idx = joined.find(search_text, idx)
109
+ if idx == -1:
110
+ break
111
+ upto = joined[:idx]
112
+ line_no = upto.count("\n") + 1
113
+ match_lines.append(line_no)
114
+ idx += 1 if not search_text else len(search_text)
115
+ return match_lines
116
+
117
+ def _replace_content(
118
+ self, content, search_text, replacement_text, replace_all, occurrences
119
+ ):
120
+ """Replace occurrences of search_text with replacement_text in content."""
121
+ if replace_all:
122
+ replaced_count = content.count(search_text)
123
+ new_content = content.replace(search_text, replacement_text)
124
+ else:
125
+ if occurrences > 1:
126
+ return 0, content # No changes made, not unique
127
+ replaced_count = 1 if occurrences == 1 else 0
128
+ new_content = content.replace(search_text, replacement_text, 1)
129
+ return replaced_count, new_content
130
+
131
+ def _backup_file(self, path, backup_path):
132
+ """Create a backup of the file."""
133
+ shutil.copy2(path, backup_path)
134
+
135
+ def _write_file_content(self, path, content):
136
+ """Write content to the file."""
137
+ with open(path, "w", encoding="utf-8", errors="replace") as f:
138
+ f.write(content)
139
+
140
+ def _handle_warnings(self, replaced_count, file_changed, occurrences):
141
+ """Handle and return warnings and concise warnings if needed."""
142
+ warning = ""
143
+ concise_warning = None
144
+ if replaced_count == 0:
145
+ warning = tr(" [Warning: Search text not found in file]")
146
+ if not file_changed:
147
+ self.report_warning(
148
+ tr(" ℹ️ No changes made. (not found)"), ReportAction.CREATE
149
+ )
150
+ concise_warning = tr(
151
+ "No changes made. The search text was not found. Expand your search context with surrounding lines if needed."
152
+ )
153
+ if occurrences > 1 and replaced_count == 0:
154
+ self.report_warning(
155
+ tr(" ℹ️ No changes made. (not unique)"), ReportAction.CREATE
156
+ )
157
+ concise_warning = tr(
158
+ "No changes made. The search text is not unique. Expand your search context with surrounding lines to ensure uniqueness."
159
+ )
160
+ return warning, concise_warning
161
+
162
+ def _report_success(self, match_lines):
163
+ """Report success with line numbers where replacements occurred."""
164
+ if match_lines:
165
+ lines_str = ", ".join(str(line_no) for line_no in match_lines)
166
+ self.report_success(
167
+ tr(" ✅ replaced at {lines_str}", lines_str=lines_str),
168
+ ReportAction.CREATE,
169
+ )
170
+ else:
171
+ self.report_success(tr(" ✅ replaced (lines unknown)"), ReportAction.CREATE)
172
+
173
+ def _get_line_delta_str(self, content, new_content):
174
+ """Return a string describing the net line change after replacement."""
175
+ total_lines_before = content.count("\n") + 1
176
+ total_lines_after = new_content.count("\n") + 1
177
+ line_delta = total_lines_after - total_lines_before
178
+ if line_delta > 0:
179
+ return f" (+{line_delta} lines)"
180
+ elif line_delta < 0:
181
+ return f" ({line_delta} lines)"
182
+ else:
183
+ return " (no net line change)"
184
+
185
+ def _format_info_msg(
186
+ self,
187
+ disp_path,
188
+ search_lines,
189
+ replace_lines,
190
+ action,
191
+ search_text,
192
+ replacement_text,
193
+ path,
194
+ ):
195
+ """Format the info message for the operation."""
196
+ if replace_lines == 0:
197
+ return tr(
198
+ "📝 Replace in {disp_path} del {search_lines} lines {action}",
199
+ disp_path=disp_path,
200
+ search_lines=search_lines,
201
+ action=action,
202
+ )
203
+ else:
204
+ try:
205
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
206
+ _content = f.read()
207
+ _new_content = _content.replace(
208
+ search_text, replacement_text, -1 if action else 1
209
+ )
210
+ _total_lines_before = _content.count("\n") + 1
211
+ _total_lines_after = _new_content.count("\n") + 1
212
+ _line_delta = _total_lines_after - _total_lines_before
213
+ except Exception:
214
+ _line_delta = replace_lines - search_lines
215
+ if _line_delta > 0:
216
+ delta_str = f"+{_line_delta} lines"
217
+ elif _line_delta < 0:
218
+ delta_str = f"{_line_delta} lines"
219
+ else:
220
+ delta_str = "+0"
221
+ return tr(
222
+ "📝 Replace in {disp_path} {delta_str} {action}",
223
+ disp_path=disp_path,
224
+ delta_str=delta_str,
225
+ action=action,
226
+ )
227
+
228
+ def _format_match_details(
229
+ self,
230
+ replaced_count,
231
+ match_lines,
232
+ search_lines,
233
+ replace_lines,
234
+ line_delta_str,
235
+ replace_all,
236
+ ):
237
+ """Format match info and details for the final message."""
238
+ if replaced_count > 0:
239
+ if replace_all:
240
+ match_info = tr(
241
+ "Matches found at lines: {lines}. ",
242
+ lines=", ".join(str(line) for line in match_lines),
243
+ )
244
+ else:
245
+ match_info = (
246
+ tr("Match found at line {line}. ", line=match_lines[0])
247
+ if match_lines
248
+ else ""
249
+ )
250
+ details = tr(
251
+ "Replaced {replaced_count} occurrence(s) at above line(s): {search_lines} lines replaced with {replace_lines} lines each.{line_delta_str}",
252
+ replaced_count=replaced_count,
253
+ search_lines=search_lines,
254
+ replace_lines=replace_lines,
255
+ line_delta_str=line_delta_str,
256
+ )
257
+ else:
258
+ match_info = ""
259
+ details = ""
260
+ return match_info, details
261
+
262
+ def _format_final_msg(self, path, warning, match_info, details):
263
+ """Format the final status message."""
264
+ return tr(
265
+ "Text replaced in {path}{warning}. {match_info}{details}",
266
+ path=path,
267
+ warning=warning,
268
+ match_info=match_info,
269
+ details=details,
270
+ )
@@ -0,0 +1,14 @@
1
+ """
2
+ Image Display Plugin - Core plugin for displaying images inline in the terminal.
3
+
4
+ This plugin provides tools for displaying images directly in the terminal using
5
+ rich library's image rendering capabilities.
6
+ """
7
+
8
+ from .plugin import ImageDisplayPlugin
9
+
10
+ # Plugin metadata for discovery/listing
11
+ __plugin_name__ = "core.imagedisplay"
12
+ __plugin_description__ = "Display images inline in the terminal using rich"
13
+
14
+ __all__ = ["ImageDisplayPlugin"]
@@ -0,0 +1,51 @@
1
+ """
2
+ Image Display Plugin implementation.
3
+ """
4
+
5
+ from typing import Dict, Any, List, Type
6
+
7
+ from janito.plugin_system.base import Plugin, PluginMetadata
8
+ from janito.tools.tool_base import ToolBase
9
+ from .tools.show_image import ShowImageTool
10
+ from .tools.show_image_grid import ShowImageGridTool
11
+
12
+
13
+ class ImageDisplayPlugin(Plugin):
14
+ """Plugin for displaying images inline in the terminal using rich."""
15
+
16
+ def get_metadata(self) -> PluginMetadata:
17
+ return PluginMetadata(
18
+ name="core.imagedisplay",
19
+ version="1.0.0",
20
+ description="Display images inline in the terminal using rich",
21
+ author="Janito",
22
+ dependencies=["rich", "pillow"],
23
+ )
24
+
25
+ def get_tools(self) -> List[Type[ToolBase]]:
26
+ # Return tool classes so the PluginManager can register them
27
+ return [ShowImageTool, ShowImageGridTool]
28
+
29
+ def get_config_schema(self) -> Dict[str, Any]:
30
+ return {
31
+ "type": "object",
32
+ "properties": {
33
+ "default_width": {
34
+ "type": "integer",
35
+ "description": "Default width for image display",
36
+ "minimum": 1,
37
+ "maximum": 200,
38
+ },
39
+ "default_height": {
40
+ "type": "integer",
41
+ "description": "Default height for image display",
42
+ "minimum": 1,
43
+ "maximum": 100,
44
+ },
45
+ "preserve_aspect": {
46
+ "type": "boolean",
47
+ "description": "Preserve aspect ratio by default",
48
+ "default": True,
49
+ },
50
+ },
51
+ }
@@ -0,0 +1 @@
1
+ """Tools for image display plugin."""
@@ -0,0 +1,83 @@
1
+ from janito.tools.tool_base import ToolBase, ToolPermissions
2
+ from janito.report_events import ReportAction
3
+ from janito.i18n import tr
4
+ from janito.tools.loop_protection_decorator import protect_against_loops
5
+
6
+
7
+ class ShowImageTool(ToolBase):
8
+ """Display an image inline in the terminal using the rich library.
9
+
10
+ Args:
11
+ path (str): Path to the image file.
12
+ width (int, optional): Target width in terminal cells. If unset, auto-fit.
13
+ height (int, optional): Target height in terminal rows. If unset, auto-fit.
14
+ preserve_aspect (bool, optional): Preserve aspect ratio. Default: True.
15
+
16
+ Returns:
17
+ str: Status message indicating display result or error details.
18
+ """
19
+
20
+ permissions = ToolPermissions(read=True)
21
+ tool_name = "show_image"
22
+
23
+ @protect_against_loops(max_calls=5, time_window=10.0, key_field="path")
24
+ def run(
25
+ self,
26
+ path: str,
27
+ width: int | None = None,
28
+ height: int | None = None,
29
+ preserve_aspect: bool = True,
30
+ ) -> str:
31
+ from janito.tools.tool_utils import display_path
32
+ from janito.tools.path_utils import expand_path
33
+ import os
34
+
35
+ # Defer heavy imports to runtime
36
+ try:
37
+ from rich.console import Console
38
+ from PIL import Image as PILImage
39
+ except Exception as e:
40
+ msg = tr("⚠️ Missing dependency: PIL/Pillow ({error})", error=e)
41
+ self.report_error(msg)
42
+ return msg
43
+
44
+ path = expand_path(path)
45
+ disp_path = display_path(path)
46
+ self.report_action(
47
+ tr("🖼️ Show image '{disp_path}'", disp_path=disp_path), ReportAction.READ
48
+ )
49
+
50
+ if not os.path.exists(path):
51
+ msg = tr("❗ not found")
52
+ self.report_warning(msg)
53
+ return tr("Error: file not found: {path}", path=disp_path)
54
+
55
+ try:
56
+ console = Console()
57
+ # rich.image.Image handles inline terminal display of common formats
58
+ from rich.console import Console
59
+ from rich.text import Text
60
+
61
+ console = Console()
62
+ img = PILImage.open(path)
63
+ console.print(
64
+ Text(
65
+ f"Image: {disp_path} ({img.width}x{img.height})", style="bold green"
66
+ )
67
+ )
68
+ console.print(img)
69
+ self.report_success(tr("✅ Displayed"))
70
+ details = []
71
+ if width:
72
+ details.append(f"width={width}")
73
+ if height:
74
+ details.append(f"height={height}")
75
+ if not preserve_aspect:
76
+ details.append("preserve_aspect=False")
77
+ info = ("; ".join(details)) if details else "auto-fit"
78
+ return tr(
79
+ "Image displayed: {disp_path} ({info})", disp_path=disp_path, info=info
80
+ )
81
+ except Exception as e:
82
+ self.report_error(tr(" ❌ Error: {error}", error=e))
83
+ return tr("Error displaying image: {error}", error=e)