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
@@ -1,10 +1,9 @@
1
1
  import os
2
2
  import shutil
3
3
  from janito.agent.tool_registry import register_tool
4
-
5
- # from janito.agent.tools_utils.expand_path import expand_path
6
4
  from janito.agent.tools_utils.utils import display_path
7
5
  from janito.agent.tool_base import ToolBase
6
+ from janito.agent.tools_utils.action_type import ActionType
8
7
  from janito.i18n import tr
9
8
 
10
9
 
@@ -31,16 +30,55 @@ class MoveFileTool(ToolBase):
31
30
  ) -> str:
32
31
  original_src = src_path
33
32
  original_dest = dest_path
34
- src = src_path # Using src_path as is
35
- dest = dest_path # Using dest_path as is
33
+ src = src_path
34
+ dest = dest_path
36
35
  disp_src = display_path(original_src)
37
36
  disp_dest = display_path(original_dest)
38
37
  backup_path = None
38
+
39
+ valid, is_src_file, is_src_dir, err_msg = self._validate_source(src, disp_src)
40
+ if not valid:
41
+ return err_msg
42
+
43
+ dest_result = self._handle_destination(dest, disp_dest, overwrite, backup)
44
+ if dest_result is not None:
45
+ backup_path, err_msg = dest_result
46
+ if err_msg:
47
+ return err_msg
48
+
49
+ try:
50
+ self.report_info(
51
+ ActionType.WRITE,
52
+ tr(
53
+ "📝 Moving from '{disp_src}' to '{disp_dest}' ...",
54
+ disp_src=disp_src,
55
+ disp_dest=disp_dest,
56
+ ),
57
+ )
58
+ shutil.move(src, dest)
59
+ self.report_success(tr("✅ Move complete."))
60
+ msg = tr("✅ Move complete.")
61
+ if backup_path:
62
+ msg += tr(
63
+ " (backup at {backup_disp})",
64
+ backup_disp=display_path(backup_path),
65
+ )
66
+ return msg
67
+ except Exception as e:
68
+ self.report_error(tr("❌ Error moving: {error}", error=e))
69
+ return tr("❌ Error moving: {error}", error=e)
70
+
71
+ def _validate_source(self, src, disp_src):
39
72
  if not os.path.exists(src):
40
73
  self.report_error(
41
74
  tr("❌ Source '{disp_src}' does not exist.", disp_src=disp_src)
42
75
  )
43
- return tr("❌ Source '{disp_src}' does not exist.", disp_src=disp_src)
76
+ return (
77
+ False,
78
+ False,
79
+ False,
80
+ tr("❌ Source '{disp_src}' does not exist.", disp_src=disp_src),
81
+ )
44
82
  is_src_file = os.path.isfile(src)
45
83
  is_src_dir = os.path.isdir(src)
46
84
  if not (is_src_file or is_src_dir):
@@ -50,10 +88,19 @@ class MoveFileTool(ToolBase):
50
88
  disp_src=disp_src,
51
89
  )
52
90
  )
53
- return tr(
54
- "❌ Source path '{disp_src}' is neither a file nor a directory.",
55
- disp_src=disp_src,
91
+ return (
92
+ False,
93
+ False,
94
+ False,
95
+ tr(
96
+ "❌ Source path '{disp_src}' is neither a file nor a directory.",
97
+ disp_src=disp_src,
98
+ ),
56
99
  )
100
+ return True, is_src_file, is_src_dir, None
101
+
102
+ def _handle_destination(self, dest, disp_dest, overwrite, backup):
103
+ backup_path = None
57
104
  if os.path.exists(dest):
58
105
  if not overwrite:
59
106
  self.report_error(
@@ -62,7 +109,7 @@ class MoveFileTool(ToolBase):
62
109
  disp_dest=disp_dest,
63
110
  )
64
111
  )
65
- return tr(
112
+ return None, tr(
66
113
  "❗ Destination '{disp_dest}' already exists and overwrite is False.",
67
114
  disp_dest=disp_dest,
68
115
  )
@@ -82,26 +129,7 @@ class MoveFileTool(ToolBase):
82
129
  self.report_error(
83
130
  tr("❌ Error removing destination before move: {error}", error=e)
84
131
  )
85
- return tr("❌ Error removing destination before move: {error}", error=e)
86
- try:
87
- self.report_info(
88
- tr(
89
- "📝 Moving from '{disp_src}' to '{disp_dest}' ...",
90
- disp_src=disp_src,
91
- disp_dest=disp_dest,
132
+ return None, tr(
133
+ "❌ Error removing destination before move: {error}", error=e
92
134
  )
93
- )
94
- shutil.move(src, dest)
95
- self.report_success(tr("✅ Move complete."))
96
- msg = tr("✅ Move complete.")
97
- if backup_path:
98
- msg += tr(
99
- " (backup at {backup_disp})",
100
- backup_disp=display_path(
101
- original_dest + (".bak" if is_src_file else ".bak.zip")
102
- ),
103
- )
104
- return msg
105
- except Exception as e:
106
- self.report_error(tr("❌ Error moving: {error}", error=e))
107
- return tr("❌ Error moving: {error}", error=e)
135
+ return backup_path, None
@@ -0,0 +1,31 @@
1
+ import webbrowser
2
+ from janito.agent.tool_registry import register_tool
3
+ from janito.agent.tool_base import ToolBase
4
+ from janito.agent.tools_utils.action_type import ActionType
5
+ from janito.i18n import tr
6
+
7
+
8
+ @register_tool(name="open_url")
9
+ class OpenUrlTool(ToolBase):
10
+ """
11
+ Open the supplied URL in the default web browser.
12
+ Args:
13
+ url (str): The URL to open.
14
+ Returns:
15
+ str: Status message indicating the result.
16
+ """
17
+
18
+ def run(self, url: str) -> str:
19
+ if not url.strip():
20
+ self.report_warning(tr("ℹ️ Empty URL provided."))
21
+ return tr("Warning: Empty URL provided. Operation skipped.")
22
+ self.report_info(ActionType.READ, tr("🌐 Opening URL '{url}' ...", url=url))
23
+ try:
24
+ webbrowser.open(url)
25
+ except Exception as err:
26
+ self.report_error(
27
+ tr("❗ Error opening URL: {url}: {err}", url=url, err=str(err))
28
+ )
29
+ return tr("Warning: Error opening URL: {url}: {err}", url=url, err=str(err))
30
+ self.report_success(tr("✅ URL opened in browser: {url}", url=url))
31
+ return tr("URL opened in browser: {url}", url=url)
@@ -1,5 +1,6 @@
1
1
  from typing import List
2
2
  from janito.agent.tool_base import ToolBase
3
+ from janito.agent.tools_utils.action_type import ActionType
3
4
  from janito.agent.tool_registry import register_tool
4
5
  from janito.i18n import tr
5
6
  import questionary
@@ -36,11 +37,12 @@ class PresentChoicesTool(ToolBase):
36
37
  if not choices:
37
38
  return tr("⚠️ No choices provided.")
38
39
  self.report_info(
40
+ ActionType.EXECUTE,
39
41
  tr(
40
42
  "ℹ️ Prompting user: {prompt} (multi_select={multi_select}) ...",
41
43
  prompt=prompt,
42
44
  multi_select=multi_select,
43
- )
45
+ ),
44
46
  )
45
47
  if multi_select:
46
48
  result = questionary.checkbox(
@@ -0,0 +1,149 @@
1
+ import subprocess
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ import threading
6
+ from janito.agent.tool_base import ToolBase
7
+ from janito.agent.tools_utils.action_type import ActionType
8
+ from janito.agent.tool_registry import register_tool
9
+ from janito.i18n import tr
10
+
11
+
12
+ @register_tool(name="python_command_runner")
13
+ class PythonCommandRunnerTool(ToolBase):
14
+ """
15
+ Tool to execute Python code using the `python -c` command-line flag.
16
+ Args:
17
+ code (str): The Python code to execute as a string.
18
+ timeout (int, optional): Timeout in seconds for the command. Defaults to 60.
19
+ Returns:
20
+ str: Output and status message, or file paths/line counts if output is large.
21
+ """
22
+
23
+ def run(self, code: str, timeout: int = 60) -> str:
24
+ if not code.strip():
25
+ self.report_warning(tr("\u2139\ufe0f Empty code provided."))
26
+ return tr("Warning: Empty code provided. Operation skipped.")
27
+ self.report_info(
28
+ ActionType.EXECUTE, tr("🐍 Running: python -c ...\n{code}\n", code=code)
29
+ )
30
+ try:
31
+ with (
32
+ tempfile.NamedTemporaryFile(
33
+ mode="w+",
34
+ prefix="python_cmd_stdout_",
35
+ delete=False,
36
+ encoding="utf-8",
37
+ ) as stdout_file,
38
+ tempfile.NamedTemporaryFile(
39
+ mode="w+",
40
+ prefix="python_cmd_stderr_",
41
+ delete=False,
42
+ encoding="utf-8",
43
+ ) as stderr_file,
44
+ ):
45
+ process = subprocess.Popen(
46
+ [sys.executable, "-c", code],
47
+ stdout=subprocess.PIPE,
48
+ stderr=subprocess.PIPE,
49
+ text=True,
50
+ bufsize=1,
51
+ universal_newlines=True,
52
+ encoding="utf-8",
53
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
54
+ )
55
+ stdout_lines, stderr_lines = self._stream_process_output(
56
+ process, stdout_file, stderr_file
57
+ )
58
+ return_code = self._wait_for_process(process, timeout)
59
+ if return_code is None:
60
+ return tr(
61
+ "Code timed out after {timeout} seconds.", timeout=timeout
62
+ )
63
+ stdout_file.flush()
64
+ stderr_file.flush()
65
+ self.report_success(
66
+ tr("\u2705 Return code {return_code}", return_code=return_code)
67
+ )
68
+ return self._format_result(
69
+ stdout_file.name, stderr_file.name, return_code
70
+ )
71
+ except Exception as e:
72
+ self.report_error(tr("\u274c Error: {error}", error=e))
73
+ return tr("Error running code: {error}", error=e)
74
+
75
+ def _stream_process_output(self, process, stdout_file, stderr_file):
76
+ stdout_lines = 0
77
+ stderr_lines = 0
78
+
79
+ def stream_output(stream, file_obj, report_func, count_func):
80
+ nonlocal stdout_lines, stderr_lines
81
+ for line in stream:
82
+ file_obj.write(line)
83
+ file_obj.flush()
84
+ report_func(line)
85
+ if count_func == "stdout":
86
+ stdout_lines += 1
87
+ else:
88
+ stderr_lines += 1
89
+
90
+ stdout_thread = threading.Thread(
91
+ target=stream_output,
92
+ args=(process.stdout, stdout_file, self.report_stdout, "stdout"),
93
+ )
94
+ stderr_thread = threading.Thread(
95
+ target=stream_output,
96
+ args=(process.stderr, stderr_file, self.report_stderr, "stderr"),
97
+ )
98
+ stdout_thread.start()
99
+ stderr_thread.start()
100
+ stdout_thread.join()
101
+ stderr_thread.join()
102
+ return stdout_lines, stderr_lines
103
+
104
+ def _wait_for_process(self, process, timeout):
105
+ try:
106
+ return process.wait(timeout=timeout)
107
+ except subprocess.TimeoutExpired:
108
+ process.kill()
109
+ self.report_error(
110
+ tr("\u274c Timed out after {timeout} seconds.", timeout=timeout)
111
+ )
112
+ return None
113
+
114
+ def _format_result(self, stdout_file_name, stderr_file_name, return_code):
115
+ with open(stdout_file_name, "r", encoding="utf-8", errors="replace") as out_f:
116
+ stdout_content = out_f.read()
117
+ with open(stderr_file_name, "r", encoding="utf-8", errors="replace") as err_f:
118
+ stderr_content = err_f.read()
119
+ max_lines = 100
120
+ stdout_lines = stdout_content.count("\n")
121
+ stderr_lines = stderr_content.count("\n")
122
+
123
+ def head_tail(text, n=10):
124
+ lines = text.splitlines()
125
+ if len(lines) <= 2 * n:
126
+ return "\n".join(lines)
127
+ return "\n".join(
128
+ lines[:n]
129
+ + ["... ({} lines omitted) ...".format(len(lines) - 2 * n)]
130
+ + lines[-n:]
131
+ )
132
+
133
+ if stdout_lines <= max_lines and stderr_lines <= max_lines:
134
+ result = f"Return code: {return_code}\n--- STDOUT ---\n{stdout_content}"
135
+ if stderr_content.strip():
136
+ result += f"\n--- STDERR ---\n{stderr_content}"
137
+ return result
138
+ else:
139
+ result = f"stdout_file: {stdout_file_name} (lines: {stdout_lines})\n"
140
+ if stderr_lines > 0 and stderr_content.strip():
141
+ result += f"stderr_file: {stderr_file_name} (lines: {stderr_lines})\n"
142
+ result += f"returncode: {return_code}\n"
143
+ result += "--- STDOUT (head/tail) ---\n" + head_tail(stdout_content) + "\n"
144
+ if stderr_content.strip():
145
+ result += (
146
+ "--- STDERR (head/tail) ---\n" + head_tail(stderr_content) + "\n"
147
+ )
148
+ result += "Use the get_lines tool to inspect the contents of these files when needed."
149
+ return result
@@ -0,0 +1,147 @@
1
+ import subprocess
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ import threading
6
+ from janito.agent.tool_base import ToolBase
7
+ from janito.agent.tools_utils.action_type import ActionType
8
+ from janito.agent.tool_registry import register_tool
9
+ from janito.i18n import tr
10
+
11
+
12
+ @register_tool(name="python_file_runner")
13
+ class PythonFileRunnerTool(ToolBase):
14
+ """
15
+ Tool to execute a specified Python script file.
16
+ Args:
17
+ file_path (str): Path to the Python script file to execute.
18
+ timeout (int, optional): Timeout in seconds for the command. Defaults to 60.
19
+ Returns:
20
+ str: Output and status message, or file paths/line counts if output is large.
21
+ """
22
+
23
+ def run(self, file_path: str, timeout: int = 60) -> str:
24
+ self.report_info(
25
+ ActionType.EXECUTE,
26
+ tr("🚀 Running: python {file_path}", file_path=file_path),
27
+ )
28
+ try:
29
+ with (
30
+ tempfile.NamedTemporaryFile(
31
+ mode="w+",
32
+ prefix="python_file_stdout_",
33
+ delete=False,
34
+ encoding="utf-8",
35
+ ) as stdout_file,
36
+ tempfile.NamedTemporaryFile(
37
+ mode="w+",
38
+ prefix="python_file_stderr_",
39
+ delete=False,
40
+ encoding="utf-8",
41
+ ) as stderr_file,
42
+ ):
43
+ process = subprocess.Popen(
44
+ [sys.executable, file_path],
45
+ stdout=subprocess.PIPE,
46
+ stderr=subprocess.PIPE,
47
+ text=True,
48
+ bufsize=1,
49
+ universal_newlines=True,
50
+ encoding="utf-8",
51
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
52
+ )
53
+ stdout_lines, stderr_lines = self._stream_process_output(
54
+ process, stdout_file, stderr_file
55
+ )
56
+ return_code = self._wait_for_process(process, timeout)
57
+ if return_code is None:
58
+ return tr(
59
+ "Code timed out after {timeout} seconds.", timeout=timeout
60
+ )
61
+ stdout_file.flush()
62
+ stderr_file.flush()
63
+ self.report_success(
64
+ tr("\u2705 Return code {return_code}", return_code=return_code)
65
+ )
66
+ return self._format_result(
67
+ stdout_file.name, stderr_file.name, return_code
68
+ )
69
+ except Exception as e:
70
+ self.report_error(tr("\u274c Error: {error}", error=e))
71
+ return tr("Error running file: {error}", error=e)
72
+
73
+ def _stream_process_output(self, process, stdout_file, stderr_file):
74
+ stdout_lines = 0
75
+ stderr_lines = 0
76
+
77
+ def stream_output(stream, file_obj, report_func, count_func):
78
+ nonlocal stdout_lines, stderr_lines
79
+ for line in stream:
80
+ file_obj.write(line)
81
+ file_obj.flush()
82
+ report_func(line)
83
+ if count_func == "stdout":
84
+ stdout_lines += 1
85
+ else:
86
+ stderr_lines += 1
87
+
88
+ stdout_thread = threading.Thread(
89
+ target=stream_output,
90
+ args=(process.stdout, stdout_file, self.report_stdout, "stdout"),
91
+ )
92
+ stderr_thread = threading.Thread(
93
+ target=stream_output,
94
+ args=(process.stderr, stderr_file, self.report_stderr, "stderr"),
95
+ )
96
+ stdout_thread.start()
97
+ stderr_thread.start()
98
+ stdout_thread.join()
99
+ stderr_thread.join()
100
+ return stdout_lines, stderr_lines
101
+
102
+ def _wait_for_process(self, process, timeout):
103
+ try:
104
+ return process.wait(timeout=timeout)
105
+ except subprocess.TimeoutExpired:
106
+ process.kill()
107
+ self.report_error(
108
+ tr("\u274c Timed out after {timeout} seconds.", timeout=timeout)
109
+ )
110
+ return None
111
+
112
+ def _format_result(self, stdout_file_name, stderr_file_name, return_code):
113
+ with open(stdout_file_name, "r", encoding="utf-8", errors="replace") as out_f:
114
+ stdout_content = out_f.read()
115
+ with open(stderr_file_name, "r", encoding="utf-8", errors="replace") as err_f:
116
+ stderr_content = err_f.read()
117
+ max_lines = 100
118
+ stdout_lines = stdout_content.count("\n")
119
+ stderr_lines = stderr_content.count("\n")
120
+
121
+ def head_tail(text, n=10):
122
+ lines = text.splitlines()
123
+ if len(lines) <= 2 * n:
124
+ return "\n".join(lines)
125
+ return "\n".join(
126
+ lines[:n]
127
+ + ["... ({} lines omitted) ...".format(len(lines) - 2 * n)]
128
+ + lines[-n:]
129
+ )
130
+
131
+ if stdout_lines <= max_lines and stderr_lines <= max_lines:
132
+ result = f"Return code: {return_code}\n--- STDOUT ---\n{stdout_content}"
133
+ if stderr_content.strip():
134
+ result += f"\n--- STDERR ---\n{stderr_content}"
135
+ return result
136
+ else:
137
+ result = f"stdout_file: {stdout_file_name} (lines: {stdout_lines})\n"
138
+ if stderr_lines > 0 and stderr_content.strip():
139
+ result += f"stderr_file: {stderr_file_name} (lines: {stderr_lines})\n"
140
+ result += f"returncode: {return_code}\n"
141
+ result += "--- STDOUT (head/tail) ---\n" + head_tail(stdout_content) + "\n"
142
+ if stderr_content.strip():
143
+ result += (
144
+ "--- STDERR (head/tail) ---\n" + head_tail(stderr_content) + "\n"
145
+ )
146
+ result += "Use the get_lines tool to inspect the contents of these files when needed."
147
+ return result
@@ -0,0 +1,153 @@
1
+ import subprocess
2
+ import os
3
+ import sys
4
+ import tempfile
5
+ import threading
6
+ from janito.agent.tool_base import ToolBase
7
+ from janito.agent.tools_utils.action_type import ActionType
8
+ from janito.agent.tool_registry import register_tool
9
+ from janito.i18n import tr
10
+
11
+
12
+ @register_tool(name="python_stdin_runner")
13
+ class PythonStdinRunnerTool(ToolBase):
14
+ """
15
+ Tool to execute Python code by passing it to the interpreter via standard input (stdin).
16
+ Args:
17
+ code (str): The Python code to execute as a string.
18
+ timeout (int, optional): Timeout in seconds for the command. Defaults to 60.
19
+ Returns:
20
+ str: Output and status message, or file paths/line counts if output is large.
21
+ """
22
+
23
+ def run(self, code: str, timeout: int = 60) -> str:
24
+ if not code.strip():
25
+ self.report_warning(tr("\u2139\ufe0f Empty code provided."))
26
+ return tr("Warning: Empty code provided. Operation skipped.")
27
+ self.report_info(
28
+ ActionType.EXECUTE,
29
+ tr("⚡ Running: python (stdin mode) ...\n{code}\n", code=code),
30
+ )
31
+ try:
32
+ with (
33
+ tempfile.NamedTemporaryFile(
34
+ mode="w+",
35
+ prefix="python_stdin_stdout_",
36
+ delete=False,
37
+ encoding="utf-8",
38
+ ) as stdout_file,
39
+ tempfile.NamedTemporaryFile(
40
+ mode="w+",
41
+ prefix="python_stdin_stderr_",
42
+ delete=False,
43
+ encoding="utf-8",
44
+ ) as stderr_file,
45
+ ):
46
+ process = subprocess.Popen(
47
+ [sys.executable],
48
+ stdin=subprocess.PIPE,
49
+ stdout=subprocess.PIPE,
50
+ stderr=subprocess.PIPE,
51
+ text=True,
52
+ bufsize=1,
53
+ universal_newlines=True,
54
+ encoding="utf-8",
55
+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},
56
+ )
57
+ stdout_lines, stderr_lines = self._stream_process_output(
58
+ process, stdout_file, stderr_file, code
59
+ )
60
+ return_code = self._wait_for_process(process, timeout)
61
+ if return_code is None:
62
+ return tr(
63
+ "Code timed out after {timeout} seconds.", timeout=timeout
64
+ )
65
+ stdout_file.flush()
66
+ stderr_file.flush()
67
+ self.report_success(
68
+ tr("\u2705 Return code {return_code}", return_code=return_code)
69
+ )
70
+ return self._format_result(
71
+ stdout_file.name, stderr_file.name, return_code
72
+ )
73
+ except Exception as e:
74
+ self.report_error(tr("\u274c Error: {error}", error=e))
75
+ return tr("Error running code via stdin: {error}", error=e)
76
+
77
+ def _stream_process_output(self, process, stdout_file, stderr_file, code):
78
+ stdout_lines = 0
79
+ stderr_lines = 0
80
+
81
+ def stream_output(stream, file_obj, report_func, count_func):
82
+ nonlocal stdout_lines, stderr_lines
83
+ for line in stream:
84
+ file_obj.write(line)
85
+ file_obj.flush()
86
+ report_func(line)
87
+ if count_func == "stdout":
88
+ stdout_lines += 1
89
+ else:
90
+ stderr_lines += 1
91
+
92
+ stdout_thread = threading.Thread(
93
+ target=stream_output,
94
+ args=(process.stdout, stdout_file, self.report_stdout, "stdout"),
95
+ )
96
+ stderr_thread = threading.Thread(
97
+ target=stream_output,
98
+ args=(process.stderr, stderr_file, self.report_stderr, "stderr"),
99
+ )
100
+ stdout_thread.start()
101
+ stderr_thread.start()
102
+ process.stdin.write(code)
103
+ process.stdin.close()
104
+ stdout_thread.join()
105
+ stderr_thread.join()
106
+ return stdout_lines, stderr_lines
107
+
108
+ def _wait_for_process(self, process, timeout):
109
+ try:
110
+ return process.wait(timeout=timeout)
111
+ except subprocess.TimeoutExpired:
112
+ process.kill()
113
+ self.report_error(
114
+ tr("\u274c Timed out after {timeout} seconds.", timeout=timeout)
115
+ )
116
+ return None
117
+
118
+ def _format_result(self, stdout_file_name, stderr_file_name, return_code):
119
+ with open(stdout_file_name, "r", encoding="utf-8", errors="replace") as out_f:
120
+ stdout_content = out_f.read()
121
+ with open(stderr_file_name, "r", encoding="utf-8", errors="replace") as err_f:
122
+ stderr_content = err_f.read()
123
+ max_lines = 100
124
+ stdout_lines = stdout_content.count("\n")
125
+ stderr_lines = stderr_content.count("\n")
126
+
127
+ def head_tail(text, n=10):
128
+ lines = text.splitlines()
129
+ if len(lines) <= 2 * n:
130
+ return "\n".join(lines)
131
+ return "\n".join(
132
+ lines[:n]
133
+ + ["... ({} lines omitted) ...".format(len(lines) - 2 * n)]
134
+ + lines[-n:]
135
+ )
136
+
137
+ if stdout_lines <= max_lines and stderr_lines <= max_lines:
138
+ result = f"Return code: {return_code}\n--- STDOUT ---\n{stdout_content}"
139
+ if stderr_content.strip():
140
+ result += f"\n--- STDERR ---\n{stderr_content}"
141
+ return result
142
+ else:
143
+ result = f"stdout_file: {stdout_file_name} (lines: {stdout_lines})\n"
144
+ if stderr_lines > 0 and stderr_content.strip():
145
+ result += f"stderr_file: {stderr_file_name} (lines: {stderr_lines})\n"
146
+ result += f"returncode: {return_code}\n"
147
+ result += "--- STDOUT (head/tail) ---\n" + head_tail(stdout_content) + "\n"
148
+ if stderr_content.strip():
149
+ result += (
150
+ "--- STDERR (head/tail) ---\n" + head_tail(stderr_content) + "\n"
151
+ )
152
+ result += "Use the get_lines tool to inspect the contents of these files when needed."
153
+ return result
@@ -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.agent.tools_utils.utils import pluralize, display_path
4
5
  from janito.i18n import tr
@@ -24,7 +25,8 @@ class RemoveDirectoryTool(ToolBase):
24
25
  def run(self, file_path: str, recursive: bool = False) -> str:
25
26
  disp_path = display_path(file_path)
26
27
  self.report_info(
27
- tr("🗃️ Removing directory '{disp_path}' ...", disp_path=disp_path)
28
+ ActionType.WRITE,
29
+ tr("🗃️ Remove directory '{disp_path}' ...", disp_path=disp_path),
28
30
  )
29
31
  backup_zip = None
30
32
  try:
@@ -5,6 +5,7 @@ from janito.agent.tool_registry import register_tool
5
5
  # from janito.agent.tools_utils.expand_path import expand_path
6
6
  from janito.agent.tools_utils.utils import display_path
7
7
  from janito.agent.tool_base import ToolBase
8
+ from janito.agent.tools_utils.action_type import ActionType
8
9
  from janito.i18n import tr
9
10
 
10
11
 
@@ -28,7 +29,10 @@ class RemoveFileTool(ToolBase):
28
29
  disp_path = display_path(original_path)
29
30
  backup_path = None
30
31
  # Report initial info about what is going to be removed
31
- self.report_info(tr("🗑️ Removing file '{disp_path}' ...", disp_path=disp_path))
32
+ self.report_info(
33
+ ActionType.WRITE,
34
+ tr("🗑️ Remove file '{disp_path}' ...", disp_path=disp_path),
35
+ )
32
36
  if not os.path.exists(path):
33
37
  self.report_error(tr("❌ File does not exist."))
34
38
  return tr("❌ File does not exist.")