janito 1.9.0__py3-none-any.whl → 1.11.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 (106) hide show
  1. janito/__init__.py +1 -1
  2. janito/agent/api_exceptions.py +4 -0
  3. janito/agent/config.py +1 -1
  4. janito/agent/config_defaults.py +2 -26
  5. janito/agent/conversation.py +163 -122
  6. janito/agent/conversation_api.py +246 -168
  7. janito/agent/conversation_ui.py +1 -1
  8. janito/agent/{conversation_history.py → llm_conversation_history.py} +30 -1
  9. janito/agent/openai_client.py +38 -23
  10. janito/agent/openai_schema_generator.py +162 -129
  11. janito/agent/platform_discovery.py +134 -77
  12. janito/agent/profile_manager.py +5 -5
  13. janito/agent/rich_message_handler.py +80 -31
  14. janito/agent/templates/profiles/system_prompt_template_base.txt.j2 +20 -4
  15. janito/agent/test_openai_schema_generator.py +93 -0
  16. janito/agent/tool_base.py +7 -2
  17. janito/agent/tool_executor.py +54 -49
  18. janito/agent/tool_registry.py +5 -2
  19. janito/agent/tool_use_tracker.py +26 -5
  20. janito/agent/tools/__init__.py +8 -3
  21. janito/agent/tools/create_directory.py +3 -1
  22. janito/agent/tools/create_file.py +7 -1
  23. janito/agent/tools/fetch_url.py +40 -3
  24. janito/agent/tools/find_files.py +29 -14
  25. janito/agent/tools/get_file_outline/core.py +7 -8
  26. janito/agent/tools/get_file_outline/python_outline.py +139 -95
  27. janito/agent/tools/get_file_outline/search_outline.py +3 -1
  28. janito/agent/tools/get_lines.py +98 -64
  29. janito/agent/tools/move_file.py +59 -31
  30. janito/agent/tools/open_url.py +31 -0
  31. janito/agent/tools/present_choices.py +3 -1
  32. janito/agent/tools/python_command_runner.py +149 -0
  33. janito/agent/tools/python_file_runner.py +147 -0
  34. janito/agent/tools/python_stdin_runner.py +153 -0
  35. janito/agent/tools/remove_directory.py +3 -1
  36. janito/agent/tools/remove_file.py +5 -1
  37. janito/agent/tools/replace_file.py +12 -2
  38. janito/agent/tools/replace_text_in_file.py +195 -149
  39. janito/agent/tools/run_bash_command.py +30 -69
  40. janito/agent/tools/run_powershell_command.py +138 -105
  41. janito/agent/tools/search_text/__init__.py +1 -0
  42. janito/agent/tools/search_text/core.py +176 -0
  43. janito/agent/tools/search_text/match_lines.py +58 -0
  44. janito/agent/tools/search_text/pattern_utils.py +65 -0
  45. janito/agent/tools/search_text/traverse_directory.py +127 -0
  46. janito/agent/tools/validate_file_syntax/core.py +43 -30
  47. janito/agent/tools/validate_file_syntax/html_validator.py +21 -5
  48. janito/agent/tools/validate_file_syntax/markdown_validator.py +77 -34
  49. janito/agent/tools_utils/action_type.py +7 -0
  50. janito/agent/tools_utils/dir_walk_utils.py +3 -2
  51. janito/agent/tools_utils/formatting.py +47 -21
  52. janito/agent/tools_utils/gitignore_utils.py +89 -40
  53. janito/agent/tools_utils/test_gitignore_utils.py +46 -0
  54. janito/agent/tools_utils/utils.py +7 -1
  55. janito/cli/_print_config.py +63 -61
  56. janito/cli/arg_parser.py +13 -12
  57. janito/cli/cli_main.py +137 -147
  58. janito/cli/config_commands.py +112 -109
  59. janito/cli/main.py +152 -174
  60. janito/cli/one_shot.py +40 -26
  61. janito/i18n/__init__.py +1 -1
  62. janito/rich_utils.py +46 -8
  63. janito/shell/commands/__init__.py +2 -4
  64. janito/shell/commands/conversation_restart.py +3 -1
  65. janito/shell/commands/edit.py +3 -0
  66. janito/shell/commands/history_view.py +3 -3
  67. janito/shell/commands/lang.py +3 -0
  68. janito/shell/commands/livelogs.py +5 -3
  69. janito/shell/commands/prompt.py +6 -0
  70. janito/shell/commands/session.py +3 -0
  71. janito/shell/commands/session_control.py +3 -0
  72. janito/shell/commands/termweb_log.py +8 -0
  73. janito/shell/commands/tools.py +3 -0
  74. janito/shell/commands/track.py +36 -0
  75. janito/shell/commands/utility.py +13 -18
  76. janito/shell/commands/verbose.py +3 -4
  77. janito/shell/input_history.py +62 -0
  78. janito/shell/main.py +160 -181
  79. janito/shell/session/config.py +83 -75
  80. janito/shell/session/manager.py +0 -21
  81. janito/shell/ui/interactive.py +97 -75
  82. janito/termweb/static/editor.css +32 -33
  83. janito/termweb/static/editor.css.bak +140 -22
  84. janito/termweb/static/editor.html +12 -7
  85. janito/termweb/static/editor.html.bak +16 -11
  86. janito/termweb/static/editor.js +94 -40
  87. janito/termweb/static/editor.js.bak +97 -65
  88. janito/termweb/static/index.html +1 -2
  89. janito/termweb/static/index.html.bak +1 -1
  90. janito/termweb/static/termweb.css +1 -22
  91. janito/termweb/static/termweb.css.bak +6 -4
  92. janito/termweb/static/termweb.js +0 -6
  93. janito/termweb/static/termweb.js.bak +1 -2
  94. janito/tests/test_rich_utils.py +44 -0
  95. janito/web/app.py +0 -75
  96. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/METADATA +61 -42
  97. janito-1.11.0.dist-info/RECORD +163 -0
  98. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/WHEEL +1 -1
  99. janito/agent/providers.py +0 -77
  100. janito/agent/tools/run_python_command.py +0 -161
  101. janito/agent/tools/search_text.py +0 -204
  102. janito/shell/commands/sum.py +0 -49
  103. janito-1.9.0.dist-info/RECORD +0 -151
  104. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/entry_points.txt +0 -0
  105. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/licenses/LICENSE +0 -0
  106. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/top_level.txt +0 -0
@@ -3,6 +3,7 @@ import shutil
3
3
  from janito.agent.tool_registry import register_tool
4
4
  from janito.agent.tools_utils.utils import display_path
5
5
  from janito.agent.tool_base import ToolBase
6
+ from janito.agent.tools_utils.action_type import ActionType
6
7
  from janito.i18n import tr
7
8
 
8
9
  from janito.agent.tools.validate_file_syntax.core import validate_file_syntax
@@ -18,6 +19,8 @@ class ReplaceFileTool(ToolBase):
18
19
  Returns:
19
20
  str: Status message indicating the result. Example:
20
21
  - "✅ Successfully replaced the file at ..."
22
+
23
+ Note: Syntax validation is automatically performed after this operation.
21
24
  """
22
25
 
23
26
  def run(self, file_path: str, content: str) -> str:
@@ -34,6 +37,10 @@ class ReplaceFileTool(ToolBase):
34
37
  # Check previous operation
35
38
  tracker = ToolUseTracker()
36
39
  if not tracker.last_operation_is_full_read_or_replace(file_path):
40
+ self.report_info(
41
+ ActionType.WRITE,
42
+ tr("📝 Replace file '{disp_path}' ...", disp_path=disp_path),
43
+ )
37
44
  self.report_warning(tr("ℹ️ Missing full view."))
38
45
  try:
39
46
  with open(file_path, "r", encoding="utf-8", errors="replace") as f:
@@ -41,11 +48,14 @@ class ReplaceFileTool(ToolBase):
41
48
  except Exception as e:
42
49
  current_content = f"[Error reading file: {e}]"
43
50
  return (
44
- "⚠️ [missing full view] You must fully view or replace the file before updating.\n"
51
+ "⚠️ [missing full view] Update was NOT performed. The full content of the file is included below for your review. Repeat the operation if you wish to proceed.\n"
45
52
  f"--- Current content of {disp_path} ---\n"
46
53
  f"{current_content}"
47
54
  )
48
- self.report_info(tr("📝 Replacing file '{disp_path}' ...", disp_path=disp_path))
55
+ self.report_info(
56
+ ActionType.WRITE,
57
+ tr("📝 Replace file '{disp_path}' ...", disp_path=disp_path),
58
+ )
49
59
  backup_path = file_path + ".bak"
50
60
  shutil.copy2(file_path, backup_path)
51
61
  with open(file_path, "w", encoding="utf-8", errors="replace") as f:
@@ -1,6 +1,9 @@
1
1
  from janito.agent.tool_base import ToolBase
2
+ from janito.agent.tools_utils.action_type import ActionType
2
3
  from janito.agent.tool_registry import register_tool
3
4
  from janito.i18n import tr
5
+ import shutil
6
+ import re
4
7
 
5
8
 
6
9
  @register_tool(name="replace_text_in_file")
@@ -8,6 +11,10 @@ class ReplaceTextInFileTool(ToolBase):
8
11
  """
9
12
  Replace exact occurrences of a given text in a file.
10
13
 
14
+ Note:
15
+ To avoid syntax errors, ensure your replacement text is pre-indented as needed, matching the indentation of the
16
+ search text in its original location.
17
+
11
18
  Args:
12
19
  file_path (str): Path to the file to modify.
13
20
  search_text (str): The exact text to search for (including indentation).
@@ -32,12 +39,154 @@ class ReplaceTextInFileTool(ToolBase):
32
39
  from janito.agent.tools_utils.utils import display_path
33
40
 
34
41
  disp_path = display_path(file_path)
35
- action = "(all)" if replace_all else "(unique)"
42
+ action = "(all)" if replace_all else ""
36
43
  search_lines = len(search_text.splitlines())
37
44
  replace_lines = len(replacement_text.splitlines())
45
+ info_msg = self._format_info_msg(
46
+ disp_path,
47
+ search_lines,
48
+ replace_lines,
49
+ action,
50
+ search_text,
51
+ replacement_text,
52
+ file_path,
53
+ )
54
+ self.report_info(ActionType.WRITE, info_msg)
55
+ try:
56
+ content = self._read_file_content(file_path)
57
+ match_lines = self._find_match_lines(content, search_text)
58
+ occurrences = content.count(search_text)
59
+ replaced_count, new_content = self._replace_content(
60
+ content, search_text, replacement_text, replace_all, occurrences
61
+ )
62
+ file_changed = new_content != content
63
+ backup_path = file_path + ".bak"
64
+ if backup and file_changed:
65
+ self._backup_file(file_path, backup_path)
66
+ if file_changed:
67
+ self._write_file_content(file_path, new_content)
68
+ warning, concise_warning = self._handle_warnings(
69
+ replaced_count, file_changed, occurrences
70
+ )
71
+ if warning:
72
+ self.report_warning(warning)
73
+ if concise_warning:
74
+ return concise_warning
75
+ self._report_success(match_lines)
76
+ line_delta_str = self._get_line_delta_str(content, new_content)
77
+ match_info, details = self._format_match_details(
78
+ replaced_count,
79
+ match_lines,
80
+ search_lines,
81
+ replace_lines,
82
+ line_delta_str,
83
+ replace_all,
84
+ )
85
+ return self._format_final_msg(
86
+ file_path, warning, backup_path, match_info, details
87
+ )
88
+ except Exception as e:
89
+ self.report_error(tr(" \u274c Error"))
90
+ return tr("Error replacing text: {error}", error=e)
91
+
92
+ def _read_file_content(self, file_path):
93
+ """Read the entire content of the file."""
94
+ with open(file_path, "r", encoding="utf-8", errors="replace") as f:
95
+ return f.read()
96
+
97
+ def _find_match_lines(self, content, search_text):
98
+ """Find all line numbers where search_text occurs in content."""
99
+ lines = content.splitlines(keepends=True)
100
+ joined = "".join(lines)
101
+ match_lines = []
102
+ idx = 0
103
+ while True:
104
+ idx = joined.find(search_text, idx)
105
+ if idx == -1:
106
+ break
107
+ upto = joined[:idx]
108
+ line_no = upto.count("\n") + 1
109
+ match_lines.append(line_no)
110
+ idx += 1 if not search_text else len(search_text)
111
+ return match_lines
112
+
113
+ def _replace_content(
114
+ self, content, search_text, replacement_text, replace_all, occurrences
115
+ ):
116
+ """Replace occurrences of search_text with replacement_text in content."""
117
+ if replace_all:
118
+ replaced_count = content.count(search_text)
119
+ new_content = content.replace(search_text, replacement_text)
120
+ else:
121
+ if occurrences > 1:
122
+ return 0, content # No changes made, not unique
123
+ replaced_count = 1 if occurrences == 1 else 0
124
+ new_content = content.replace(search_text, replacement_text, 1)
125
+ return replaced_count, new_content
126
+
127
+ def _backup_file(self, file_path, backup_path):
128
+ """Create a backup of the file."""
129
+ shutil.copy2(file_path, backup_path)
130
+
131
+ def _write_file_content(self, file_path, content):
132
+ """Write content to the file."""
133
+ with open(file_path, "w", encoding="utf-8", errors="replace") as f:
134
+ f.write(content)
135
+
136
+ def _handle_warnings(self, replaced_count, file_changed, occurrences):
137
+ """Handle and return warnings and concise warnings if needed."""
138
+ warning = ""
139
+ concise_warning = None
140
+ if replaced_count == 0:
141
+ warning = tr(" [Warning: Search text not found in file]")
142
+ if not file_changed:
143
+ self.report_warning(tr(" \u2139\ufe0f No changes made. [not found]"))
144
+ concise_warning = tr(
145
+ "No changes made. The search text was not found. Expand your search context with surrounding lines if needed."
146
+ )
147
+ if occurrences > 1 and replaced_count == 0:
148
+ self.report_warning(tr(" \u2139\ufe0f No changes made. [not unique]"))
149
+ concise_warning = tr(
150
+ "No changes made. The search text is not unique. Expand your search context with surrounding lines to ensure uniqueness."
151
+ )
152
+ return warning, concise_warning
153
+
154
+ def _report_success(self, match_lines):
155
+ """Report success with line numbers where replacements occurred."""
156
+ if match_lines:
157
+ lines_str = ", ".join(str(line_no) for line_no in match_lines)
158
+ self.report_success(
159
+ tr(" \u2705 replaced at {lines_str}", lines_str=lines_str)
160
+ )
161
+ else:
162
+ self.report_success(tr(" \u2705 replaced (lines unknown)"))
163
+
164
+ def _get_line_delta_str(self, content, new_content):
165
+ """Return a string describing the net line change after replacement."""
166
+ total_lines_before = content.count("\n") + 1
167
+ total_lines_after = new_content.count("\n") + 1
168
+ line_delta = total_lines_after - total_lines_before
169
+ if line_delta > 0:
170
+ return f" (+{line_delta} lines)"
171
+ elif line_delta < 0:
172
+ return f" ({line_delta} lines)"
173
+ else:
174
+ return " (no net line change)"
175
+
176
+ def _format_info_msg(
177
+ self,
178
+ disp_path,
179
+ search_lines,
180
+ replace_lines,
181
+ action,
182
+ search_text,
183
+ replacement_text,
184
+ file_path,
185
+ ):
186
+ """Format the info message for the operation."""
38
187
  if replace_lines == 0:
39
- info_msg = tr(
40
- "📝 Replacing in {disp_path} del {search_lines} lines {action}",
188
+ return tr(
189
+ "📝 Replace in {disp_path} del {search_lines} lines {action}",
41
190
  disp_path=disp_path,
42
191
  search_lines=search_lines,
43
192
  action=action,
@@ -47,7 +196,7 @@ class ReplaceTextInFileTool(ToolBase):
47
196
  with open(file_path, "r", encoding="utf-8", errors="replace") as f:
48
197
  _content = f.read()
49
198
  _new_content = _content.replace(
50
- search_text, replacement_text, -1 if replace_all else 1
199
+ search_text, replacement_text, -1 if action else 1
51
200
  )
52
201
  _total_lines_before = _content.count("\n") + 1
53
202
  _total_lines_after = _new_content.count("\n") + 1
@@ -60,157 +209,54 @@ class ReplaceTextInFileTool(ToolBase):
60
209
  delta_str = f"{_line_delta} lines"
61
210
  else:
62
211
  delta_str = "+0"
63
- info_msg = tr(
64
- "📝 Replacing in {disp_path} {delta_str} {action}",
212
+ return tr(
213
+ "📝 Replace in {disp_path} {delta_str} {action}",
65
214
  disp_path=disp_path,
66
215
  delta_str=delta_str,
67
216
  action=action,
68
217
  )
69
- self.report_info(
70
- info_msg + (" ..." if not info_msg.rstrip().endswith("...") else "")
71
- )
72
- try:
73
- with open(file_path, "r", encoding="utf-8", errors="replace") as f:
74
- content = f.read()
75
-
76
- def find_match_lines(content, search_text):
77
- lines = content.splitlines(keepends=True)
78
- joined = "".join(lines)
79
- match_lines = []
80
- idx = 0
81
- while True:
82
- idx = joined.find(search_text, idx)
83
- if idx == -1:
84
- break
85
- upto = joined[:idx]
86
- line_no = upto.count("\n") + 1
87
- match_lines.append(line_no)
88
- idx += 1 if not search_text else len(search_text)
89
- return match_lines
90
-
91
- match_lines = find_match_lines(content, search_text)
92
- if replace_all:
93
- replaced_count = content.count(search_text)
94
- new_content = content.replace(search_text, replacement_text)
95
- else:
96
- occurrences = content.count(search_text)
97
- if occurrences > 1:
98
- self.report_warning(tr(" ℹ️ No changes made. [not unique]"))
99
- warning_detail = tr(
100
- "The search text is not unique. Expand your search context with surrounding lines to ensure uniqueness."
101
- )
102
- return tr(
103
- "No changes made. {warning_detail}",
104
- warning_detail=warning_detail,
105
- )
106
- replaced_count = 1 if occurrences == 1 else 0
107
- new_content = content.replace(search_text, replacement_text, 1)
108
- import shutil
109
-
110
- backup_path = file_path + ".bak"
111
- if backup and new_content != content:
112
- shutil.copy2(file_path, backup_path)
113
- if new_content != content:
114
- with open(file_path, "w", encoding="utf-8", errors="replace") as f:
115
- f.write(new_content)
116
- file_changed = True
117
- else:
118
- file_changed = False
119
- warning = ""
120
- if replaced_count == 0:
121
- warning = tr(" [Warning: Search text not found in file]")
122
- if not file_changed:
123
- self.report_warning(tr(" ℹ️ No changes made. [not found]"))
124
- concise_warning = tr(
125
- "The search text was not found. Expand your search context with surrounding lines if needed."
126
- )
127
- return tr(
128
- "No changes made. {concise_warning}",
129
- concise_warning=concise_warning,
130
- )
131
- if match_lines:
132
- lines_str = ", ".join(str(line_no) for line_no in match_lines)
133
- self.report_success(
134
- tr(" ✅ replaced at {lines_str}", lines_str=lines_str)
135
- )
136
- else:
137
- self.report_success(tr(" ✅ replaced (lines unknown)"))
138
218
 
139
- def leading_ws(line):
140
- import re
141
-
142
- m = re.match(r"^\s*", line)
143
- return m.group(0) if m else ""
144
-
145
- search_indent = (
146
- leading_ws(search_text.splitlines()[0])
147
- if search_text.splitlines()
148
- else ""
149
- )
150
- replace_indent = (
151
- leading_ws(replacement_text.splitlines()[0])
152
- if replacement_text.splitlines()
153
- else ""
154
- )
155
- indent_warning = ""
156
- if search_indent != replace_indent:
157
- indent_warning = tr(
158
- " [Warning: Indentation mismatch between search and replacement text: '{search_indent}' vs '{replace_indent}']",
159
- search_indent=search_indent,
160
- replace_indent=replace_indent,
161
- )
162
- total_lines_before = content.count("\n") + 1
163
- total_lines_after = new_content.count("\n") + 1
164
- line_delta = total_lines_after - total_lines_before
165
- line_delta_str = (
166
- f" (+{line_delta} lines)"
167
- if line_delta > 0
168
- else (
169
- f" ({line_delta} lines)"
170
- if line_delta < 0
171
- else " (no net line change)"
172
- )
173
- )
174
- if replaced_count > 0:
175
- if replace_all:
176
- match_info = tr(
177
- "Matches found at lines: {lines}. ",
178
- lines=", ".join(str(line) for line in match_lines),
179
- )
180
- else:
181
- match_info = (
182
- tr("Match found at line {line}. ", line=match_lines[0])
183
- if match_lines
184
- else ""
185
- )
186
- details = tr(
187
- "Replaced {replaced_count} occurrence(s) at above line(s): {search_lines} lines replaced with {replace_lines} lines each.{line_delta_str}",
188
- replaced_count=replaced_count,
189
- search_lines=search_lines,
190
- replace_lines=replace_lines,
191
- line_delta_str=line_delta_str,
219
+ def _format_match_details(
220
+ self,
221
+ replaced_count,
222
+ match_lines,
223
+ search_lines,
224
+ replace_lines,
225
+ line_delta_str,
226
+ replace_all,
227
+ ):
228
+ """Format match info and details for the final message."""
229
+ if replaced_count > 0:
230
+ if replace_all:
231
+ match_info = tr(
232
+ "Matches found at lines: {lines}. ",
233
+ lines=", ".join(str(line) for line in match_lines),
192
234
  )
193
235
  else:
194
- match_info = ""
195
- details = ""
196
- if "warning_detail" in locals():
197
- return tr(
198
- "Text replaced in {file_path}{warning}{indent_warning} (backup at {backup_path})\n{warning_detail}",
199
- file_path=file_path,
200
- warning=warning,
201
- indent_warning=indent_warning,
202
- backup_path=backup_path,
203
- warning_detail=warning_detail,
236
+ match_info = (
237
+ tr("Match found at line {line}. ", line=match_lines[0])
238
+ if match_lines
239
+ else ""
204
240
  )
205
- return tr(
206
- "Text replaced in {file_path}{warning}{indent_warning} (backup at {backup_path}). {match_info}{details}",
207
- file_path=file_path,
208
- warning=warning,
209
- indent_warning=indent_warning,
210
- backup_path=backup_path,
211
- match_info=match_info,
212
- details=details,
241
+ details = tr(
242
+ "Replaced {replaced_count} occurrence(s) at above line(s): {search_lines} lines replaced with {replace_lines} lines each.{line_delta_str}",
243
+ replaced_count=replaced_count,
244
+ search_lines=search_lines,
245
+ replace_lines=replace_lines,
246
+ line_delta_str=line_delta_str,
213
247
  )
214
- except Exception as e:
215
- self.report_error(tr(" Error"))
216
- return tr("Error replacing text: {error}", error=e)
248
+ else:
249
+ match_info = ""
250
+ details = ""
251
+ return match_info, details
252
+
253
+ def _format_final_msg(self, file_path, warning, backup_path, match_info, details):
254
+ """Format the final status message."""
255
+ return tr(
256
+ "Text replaced in {file_path}{warning} (backup at {backup_path}). {match_info}{details}",
257
+ file_path=file_path,
258
+ warning=warning,
259
+ backup_path=backup_path,
260
+ match_info=match_info,
261
+ details=details,
262
+ )
@@ -1,4 +1,5 @@
1
1
  from janito.agent.tool_base import ToolBase
2
+ from janito.agent.tools_utils.action_type import ActionType
2
3
  from janito.agent.tool_registry import register_tool
3
4
  from janito.i18n import tr
4
5
  import subprocess
@@ -16,7 +17,7 @@ class RunBashCommandTool(ToolBase):
16
17
  command (str): The bash command to execute.
17
18
  timeout (int, optional): Timeout in seconds for the command. Defaults to 60.
18
19
  require_confirmation (bool, optional): If True, require user confirmation before running. Defaults to False.
19
- interactive (bool, optional): If True, warns that the command may require user interaction. Defaults to False. Non-interactive commands are preferred for automation and reliability.
20
+ requires_user_input (bool, optional): If True, warns that the command may require user input and might hang. Defaults to False. Non-interactive commands are preferred for automation and reliability.
20
21
  Returns:
21
22
  str: File paths and line counts for stdout and stderr.
22
23
  """
@@ -26,16 +27,19 @@ class RunBashCommandTool(ToolBase):
26
27
  command: str,
27
28
  timeout: int = 60,
28
29
  require_confirmation: bool = False,
29
- interactive: bool = False,
30
+ requires_user_input: bool = False,
30
31
  ) -> str:
31
32
  if not command.strip():
32
- self.report_warning(tr("ℹ️ Empty command provided."))
33
+ self.report_warning(tr("\u2139\ufe0f Empty command provided."))
33
34
  return tr("Warning: Empty command provided. Operation skipped.")
34
- self.report_info(tr("🖥️ Running bash command: {command} ...\n", command=command))
35
- if interactive:
35
+ self.report_info(
36
+ ActionType.EXECUTE,
37
+ tr("🖥️ Run bash command: {command} ...\n", command=command),
38
+ )
39
+ if requires_user_input:
36
40
  self.report_warning(
37
41
  tr(
38
- "⚠️ Warning: This command might be interactive, require user input, and might hang."
42
+ "\u26a0\ufe0f Warning: This command might be interactive, require user input, and might hang."
39
43
  )
40
44
  )
41
45
  sys.stdout.flush()
@@ -61,88 +65,45 @@ class RunBashCommandTool(ToolBase):
61
65
  bufsize=1,
62
66
  env=env,
63
67
  )
64
- stdout_lines = 0
65
- stderr_lines = 0
66
- stdout_content = []
67
- stderr_content = []
68
- max_lines = 100
69
- import threading
70
-
71
- def stream_reader(
72
- stream, file_handle, report_func, content_list, line_counter
73
- ):
74
- for line in iter(stream.readline, ""):
75
- file_handle.write(line)
76
- file_handle.flush()
77
- report_func(line)
78
- content_list.append(line)
79
- line_counter[0] += 1
80
- stream.close()
81
-
82
- stdout_counter = [0]
83
- stderr_counter = [0]
84
- stdout_thread = threading.Thread(
85
- target=stream_reader,
86
- args=(
87
- process.stdout,
88
- stdout_file,
89
- self.report_stdout,
90
- stdout_content,
91
- stdout_counter,
92
- ),
93
- )
94
- stderr_thread = threading.Thread(
95
- target=stream_reader,
96
- args=(
97
- process.stderr,
98
- stderr_file,
99
- self.report_stderr,
100
- stderr_content,
101
- stderr_counter,
102
- ),
103
- )
104
- stdout_thread.start()
105
- stderr_thread.start()
106
68
  try:
107
- process.wait(timeout=timeout)
69
+ stdout_content, stderr_content = process.communicate(
70
+ timeout=timeout
71
+ )
108
72
  except subprocess.TimeoutExpired:
109
73
  process.kill()
110
74
  self.report_error(
111
- tr(" ❌ Timed out after {timeout} seconds.", timeout=timeout)
75
+ tr(
76
+ " \u274c Timed out after {timeout} seconds.",
77
+ timeout=timeout,
78
+ )
112
79
  )
113
80
  return tr(
114
81
  "Command timed out after {timeout} seconds.", timeout=timeout
115
82
  )
116
- stdout_thread.join()
117
- stderr_thread.join()
118
- stdout_lines = stdout_counter[0]
119
- stderr_lines = stderr_counter[0]
120
83
  self.report_success(
121
- tr(" ✅ return code {return_code}", return_code=process.returncode)
84
+ tr(
85
+ " \u2705 return code {return_code}",
86
+ return_code=process.returncode,
87
+ )
122
88
  )
123
89
  warning_msg = ""
124
- if interactive:
90
+ if requires_user_input:
125
91
  warning_msg = tr(
126
- "⚠️ Warning: This command might be interactive, require user input, and might hang.\n"
92
+ "\u26a0\ufe0f Warning: This command might be interactive, require user input, and might hang.\n"
127
93
  )
94
+ max_lines = 100
95
+ stdout_lines = stdout_content.count("\n")
96
+ stderr_lines = stderr_content.count("\n")
128
97
  if stdout_lines <= max_lines and stderr_lines <= max_lines:
129
- with open(
130
- stdout_file.name, "r", encoding="utf-8", errors="replace"
131
- ) as out_f:
132
- stdout_content_str = out_f.read()
133
- with open(
134
- stderr_file.name, "r", encoding="utf-8", errors="replace"
135
- ) as err_f:
136
- stderr_content_str = err_f.read()
137
98
  result = warning_msg + tr(
138
99
  "Return code: {return_code}\n--- STDOUT ---\n{stdout_content}",
139
100
  return_code=process.returncode,
140
- stdout_content=stdout_content_str,
101
+ stdout_content=stdout_content,
141
102
  )
142
- if stderr_content_str.strip():
103
+ if stderr_content.strip():
143
104
  result += tr(
144
105
  "\n--- STDERR ---\n{stderr_content}",
145
- stderr_content=stderr_content_str,
106
+ stderr_content=stderr_content,
146
107
  )
147
108
  return result
148
109
  else:
@@ -163,5 +124,5 @@ class RunBashCommandTool(ToolBase):
163
124
  )
164
125
  return result
165
126
  except Exception as e:
166
- self.report_error(tr(" Error: {error}", error=e))
127
+ self.report_error(tr(" \u274c Error: {error}", error=e))
167
128
  return tr("Error running command: {error}", error=e)