janito 1.9.0__py3-none-any.whl → 1.10.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 (81) 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 +149 -159
  7. janito/agent/{conversation_history.py → llm_conversation_history.py} +18 -1
  8. janito/agent/openai_client.py +38 -23
  9. janito/agent/openai_schema_generator.py +162 -129
  10. janito/agent/platform_discovery.py +134 -77
  11. janito/agent/profile_manager.py +5 -5
  12. janito/agent/rich_message_handler.py +80 -31
  13. janito/agent/templates/profiles/system_prompt_template_base.txt.j2 +5 -4
  14. janito/agent/test_openai_schema_generator.py +93 -0
  15. janito/agent/tool_base.py +7 -2
  16. janito/agent/tool_executor.py +54 -49
  17. janito/agent/tool_registry.py +5 -2
  18. janito/agent/tool_use_tracker.py +26 -5
  19. janito/agent/tools/__init__.py +6 -3
  20. janito/agent/tools/create_directory.py +3 -1
  21. janito/agent/tools/create_file.py +7 -1
  22. janito/agent/tools/fetch_url.py +40 -3
  23. janito/agent/tools/find_files.py +3 -1
  24. janito/agent/tools/get_file_outline/core.py +6 -7
  25. janito/agent/tools/get_file_outline/search_outline.py +3 -1
  26. janito/agent/tools/get_lines.py +7 -2
  27. janito/agent/tools/move_file.py +3 -1
  28. janito/agent/tools/present_choices.py +3 -1
  29. janito/agent/tools/python_command_runner.py +150 -0
  30. janito/agent/tools/python_file_runner.py +148 -0
  31. janito/agent/tools/python_stdin_runner.py +154 -0
  32. janito/agent/tools/remove_directory.py +3 -1
  33. janito/agent/tools/remove_file.py +5 -1
  34. janito/agent/tools/replace_file.py +12 -2
  35. janito/agent/tools/replace_text_in_file.py +4 -2
  36. janito/agent/tools/run_bash_command.py +30 -69
  37. janito/agent/tools/run_powershell_command.py +134 -105
  38. janito/agent/tools/search_text.py +172 -122
  39. janito/agent/tools/validate_file_syntax/core.py +3 -1
  40. janito/agent/tools_utils/action_type.py +7 -0
  41. janito/agent/tools_utils/dir_walk_utils.py +3 -2
  42. janito/agent/tools_utils/formatting.py +47 -21
  43. janito/agent/tools_utils/gitignore_utils.py +66 -40
  44. janito/agent/tools_utils/test_gitignore_utils.py +46 -0
  45. janito/cli/_print_config.py +63 -61
  46. janito/cli/arg_parser.py +13 -12
  47. janito/cli/cli_main.py +137 -147
  48. janito/cli/main.py +152 -174
  49. janito/cli/one_shot.py +40 -26
  50. janito/i18n/__init__.py +1 -1
  51. janito/rich_utils.py +46 -8
  52. janito/shell/commands/__init__.py +2 -4
  53. janito/shell/commands/conversation_restart.py +3 -1
  54. janito/shell/commands/edit.py +3 -0
  55. janito/shell/commands/history_view.py +3 -3
  56. janito/shell/commands/lang.py +3 -0
  57. janito/shell/commands/livelogs.py +5 -3
  58. janito/shell/commands/prompt.py +6 -0
  59. janito/shell/commands/session.py +3 -0
  60. janito/shell/commands/session_control.py +3 -0
  61. janito/shell/commands/termweb_log.py +8 -0
  62. janito/shell/commands/tools.py +3 -0
  63. janito/shell/commands/track.py +36 -0
  64. janito/shell/commands/utility.py +13 -18
  65. janito/shell/commands/verbose.py +3 -4
  66. janito/shell/input_history.py +62 -0
  67. janito/shell/main.py +117 -181
  68. janito/shell/session/manager.py +0 -21
  69. janito/shell/ui/interactive.py +0 -2
  70. janito/termweb/static/editor.css +0 -4
  71. janito/tests/test_rich_utils.py +44 -0
  72. janito/web/app.py +0 -75
  73. {janito-1.9.0.dist-info → janito-1.10.0.dist-info}/METADATA +61 -42
  74. {janito-1.9.0.dist-info → janito-1.10.0.dist-info}/RECORD +78 -71
  75. {janito-1.9.0.dist-info → janito-1.10.0.dist-info}/WHEEL +1 -1
  76. janito/agent/providers.py +0 -77
  77. janito/agent/tools/run_python_command.py +0 -161
  78. janito/shell/commands/sum.py +0 -49
  79. {janito-1.9.0.dist-info → janito-1.10.0.dist-info}/entry_points.txt +0 -0
  80. {janito-1.9.0.dist-info → janito-1.10.0.dist-info}/licenses/LICENSE +0 -0
  81. {janito-1.9.0.dist-info → janito-1.10.0.dist-info}/top_level.txt +0 -0
@@ -5,6 +5,16 @@ from janito.agent.message_handler_protocol import MessageHandlerProtocol
5
5
  console = Console()
6
6
 
7
7
 
8
+ def _print_metadata_if_verbose(msg):
9
+ if unified_config.get("verbose_messages", False):
10
+ # Exclude 'message' field from metadata
11
+ meta = {k: v for k, v in msg.items() if k != "message"}
12
+ if meta:
13
+ console.print("[bold][cyan]Message metadata:[/cyan][/bold]")
14
+ for k, v in meta.items():
15
+ console.print(f" [green]{k}[/green]: [magenta]{v}[/magenta]")
16
+
17
+
8
18
  class RichMessageHandler(MessageHandlerProtocol):
9
19
  """
10
20
  Unified message handler for all output (tool, agent, system) using Rich for styled output.
@@ -18,13 +28,10 @@ class RichMessageHandler(MessageHandlerProtocol):
18
28
  Handles a dict with 'type' and 'message'.
19
29
  All messages must be dicts. Raises if not.
20
30
  """
21
- # Check trust config: suppress all output except 'content' if enabled
22
31
  trust = runtime_config.get("trust")
23
32
  if trust is None:
24
33
  trust = unified_config.get("trust", False)
25
34
 
26
- from rich.markdown import Markdown
27
-
28
35
  if not isinstance(msg, dict):
29
36
  raise TypeError(
30
37
  f"RichMessageHandler.handle_message expects a dict with 'type' and 'message', got {type(msg)}: {msg!r}"
@@ -35,32 +42,74 @@ class RichMessageHandler(MessageHandlerProtocol):
35
42
 
36
43
  if trust and msg_type != "content":
37
44
  return # Suppress all except content
38
- if msg_type == "content":
39
- self.console.print(Markdown(message))
40
- elif msg_type == "info":
41
- self.console.print(f" {message}", style="cyan", end="")
42
- elif msg_type == "success":
43
- self.console.print(message, style="bold green", end="\n")
44
- elif msg_type == "error":
45
- self.console.print(message, style="bold red", end="\n")
46
- elif msg_type == "progress":
47
- self._handle_progress(message)
48
- elif msg_type == "warning":
49
- self.console.print(message, style="bold yellow", end="\n")
50
- elif msg_type == "stdout":
51
- from rich.text import Text
52
-
53
- self.console.print(
54
- Text(message, style="on #003300", no_wrap=True, overflow=None),
55
- end="",
56
- )
57
- elif msg_type == "stderr":
58
- from rich.text import Text
59
45
 
60
- self.console.print(
61
- Text(message, style="on #330000", no_wrap=True, overflow=None),
62
- end="",
63
- )
64
- else:
65
- # Ignore unsupported message types silently
66
- return
46
+ handler_map = {
47
+ "content": self._handle_content,
48
+ "info": self._handle_info,
49
+ "success": self._handle_success,
50
+ "error": self._handle_error,
51
+ "progress": self._handle_progress,
52
+ "warning": self._handle_warning,
53
+ "stdout": self._handle_stdout,
54
+ "stderr": self._handle_stderr,
55
+ }
56
+
57
+ handler = handler_map.get(msg_type)
58
+ if handler:
59
+ handler(msg, message)
60
+ # Ignore unsupported message types silently
61
+
62
+ def _handle_content(self, msg, message):
63
+ from rich.markdown import Markdown
64
+
65
+ _print_metadata_if_verbose(msg)
66
+ self.console.print(Markdown(message))
67
+
68
+ def _handle_info(self, msg, message):
69
+ action_type = msg.get("action_type", None)
70
+ style = "cyan" # default
71
+ action_type_name = action_type.name if action_type else None
72
+ if action_type_name == "READ":
73
+ style = "cyan"
74
+ elif action_type_name == "WRITE":
75
+ style = "bright_magenta"
76
+ elif action_type_name == "EXECUTE":
77
+ style = "yellow"
78
+ _print_metadata_if_verbose(msg)
79
+ self.console.print(f" {message}", style=style, end="")
80
+
81
+ def _handle_success(self, msg, message):
82
+ _print_metadata_if_verbose(msg)
83
+ self.console.print(message, style="bold green", end="\n")
84
+
85
+ def _handle_error(self, msg, message):
86
+ _print_metadata_if_verbose(msg)
87
+ self.console.print(message, style="bold red", end="\n")
88
+
89
+ def _handle_progress(self, msg, message=None):
90
+ _print_metadata_if_verbose(msg)
91
+ # Existing logic for progress messages (if any)
92
+ # Placeholder: implement as needed
93
+ pass
94
+
95
+ def _handle_warning(self, msg, message):
96
+ _print_metadata_if_verbose(msg)
97
+ self.console.print(message, style="bold yellow", end="\n")
98
+
99
+ def _handle_stdout(self, msg, message):
100
+ from rich.text import Text
101
+
102
+ _print_metadata_if_verbose(msg)
103
+ self.console.print(
104
+ Text(message, style="on #003300", no_wrap=True, overflow=None),
105
+ end="",
106
+ )
107
+
108
+ def _handle_stderr(self, msg, message):
109
+ from rich.text import Text
110
+
111
+ _print_metadata_if_verbose(msg)
112
+ self.console.print(
113
+ Text(message, style="on #330000", no_wrap=True, overflow=None),
114
+ end="",
115
+ )
@@ -6,9 +6,10 @@ You will be developing and testing in the following environment:
6
6
  Shell/Environment: {{ shell_info }}
7
7
 
8
8
  Respond according to the following guidelines:
9
- - Before answering check for files in the current project that might be related to the question
9
+ - Before answering check for files that might be related to the question
10
10
  - Before using your namespace functions, provide a concise explanation.
11
- - When you are likely to need the entire file content, get the full content by omitting range numbers
12
- - Do not provide the code in the messages, use the namespace functions to provide the cocde changes.
11
+ - When planning to get the entire file content, set the range line numbers to None
12
+ - Do not provide the code in the messages, use the namespace functions to provide the code changes.
13
13
  - Prefer making localized edits using string replacements. If the required change is extensive, replace the entire file instead, provide full content without placeholders.
14
- - When locating code lines to change, check the surrounding lines content for indentation precise replacement.
14
+ - Before creating files search the code for the location related to the file purpose
15
+ - Once development or updates are finished, ensure that all new or updated packages, modules, functions, and methods
@@ -0,0 +1,93 @@
1
+ """
2
+ Tests for OpenAISchemaGenerator class-based API.
3
+ """
4
+
5
+ import pytest
6
+ from janito.agent.openai_schema_generator import OpenAISchemaGenerator
7
+
8
+
9
+ class DummyTool:
10
+ """
11
+ Dummy tool for testing.
12
+
13
+ Args:
14
+ foo (str): Foo parameter.
15
+ bar (int): Bar parameter.
16
+ Returns:
17
+ The result as a string.
18
+ """
19
+
20
+ name = "dummy_tool"
21
+
22
+ def run(self, foo: str, bar: int) -> str:
23
+ """Run the dummy tool."""
24
+ return f"{foo}-{bar}"
25
+
26
+
27
+ # Simulate decorator metadata for tests
28
+ DummyTool._tool_run_method = DummyTool().run
29
+ DummyTool._tool_name = DummyTool.name
30
+
31
+
32
+ def test_generate_schema_success():
33
+ generator = OpenAISchemaGenerator()
34
+ tool = DummyTool
35
+ schema = generator.generate_schema(tool)
36
+ assert schema["name"] == tool.name
37
+ assert "foo" in schema["parameters"]["properties"]
38
+ assert "bar" in schema["parameters"]["properties"]
39
+ assert schema["parameters"]["properties"]["foo"]["type"] == "string"
40
+ assert schema["parameters"]["properties"]["bar"]["type"] == "integer"
41
+ assert schema["description"].startswith("Dummy tool for testing.")
42
+
43
+
44
+ def test_generate_schema_missing_type():
45
+ class BadTool:
46
+ """
47
+ Args:
48
+ foo (str): Foo parameter.
49
+ Returns:
50
+ String result.
51
+ """
52
+
53
+ name = "bad_tool"
54
+
55
+ def run(self, foo):
56
+ return str(foo)
57
+
58
+ BadTool._tool_run_method = BadTool().run
59
+ BadTool._tool_name = BadTool.name
60
+ generator = OpenAISchemaGenerator()
61
+ with pytest.raises(ValueError):
62
+ generator.generate_schema(BadTool)
63
+
64
+
65
+ def test_generate_schema_missing_doc():
66
+ class BadTool2:
67
+ """
68
+ Args:
69
+ foo (str): Foo parameter.
70
+ Returns:
71
+ String result.
72
+ """
73
+
74
+ name = "bad_tool2"
75
+
76
+ def run(self, foo: str, bar: int) -> str:
77
+ return str(foo)
78
+
79
+ BadTool2._tool_run_method = BadTool2().run
80
+ BadTool2._tool_name = BadTool2.name
81
+ generator = OpenAISchemaGenerator()
82
+ with pytest.raises(ValueError):
83
+ generator.generate_schema(BadTool2)
84
+
85
+
86
+ def test_generate_schema_requires_metadata():
87
+ class NotRegisteredTool:
88
+ def run(self, foo: str) -> str:
89
+ return foo
90
+
91
+ generator = OpenAISchemaGenerator()
92
+ with pytest.raises(ValueError):
93
+ generator.generate_schema(NotRegisteredTool)
janito/agent/tool_base.py CHANGED
@@ -37,9 +37,14 @@ class ToolBase(ABC):
37
37
  if hasattr(self, "_progress_callback") and self._progress_callback:
38
38
  self._progress_callback(progress)
39
39
 
40
- def report_info(self, message: str):
40
+ def report_info(self, action_type, message: str):
41
41
  self.update_progress(
42
- {"type": "info", "tool": self.__class__.__name__, "message": message}
42
+ {
43
+ "type": "info",
44
+ "tool": self.__class__.__name__,
45
+ "action_type": action_type,
46
+ "message": message,
47
+ }
43
48
  )
44
49
 
45
50
  def report_success(self, message: str):
@@ -16,7 +16,9 @@ class ToolExecutor:
16
16
  def execute(self, tool_entry, tool_call, arguments):
17
17
  import uuid
18
18
 
19
- call_id = getattr(tool_call, "id", None) or str(uuid.uuid4())
19
+ call_id = getattr(tool_call, "id", None)
20
+ if call_id is None:
21
+ raise ValueError("Tool call is missing required 'id' from server.")
20
22
  func = tool_entry["function"]
21
23
  args = arguments
22
24
  if runtime_config.get("no_tools_tracking", False):
@@ -25,15 +27,21 @@ class ToolExecutor:
25
27
  tool_call_reason = args.pop(
26
28
  "tool_call_reason", None
27
29
  ) # Extract and remove 'tool_call_reason' if present
28
- # Record tool usage
29
- try:
30
- from janito.agent.tool_use_tracker import ToolUseTracker
31
30
 
32
- ToolUseTracker().record(tool_call.function.name, dict(args))
31
+ self._maybe_log_tool_call(tool_call, args, tool_call_reason)
32
+ instance = self._maybe_set_progress_callback(func)
33
+ self._emit_tool_call_event(tool_call, call_id, args, tool_call_reason)
34
+ self._validate_arguments(func, args, tool_call, call_id, tool_call_reason)
35
+ try:
36
+ result = func(**args)
37
+ self._emit_tool_result_event(tool_call, call_id, result, tool_call_reason)
38
+ self._record_tool_usage(tool_call, args, result)
39
+ return result
33
40
  except Exception as e:
34
- if runtime_config.get("verbose", False):
35
- print(f"[ToolExecutor] ToolUseTracker record failed: {e}")
41
+ self._emit_tool_error_event(tool_call, call_id, str(e), tool_call_reason)
42
+ raise
36
43
 
44
+ def _maybe_log_tool_call(self, tool_call, args, tool_call_reason):
37
45
  verbose = runtime_config.get("verbose", False)
38
46
  if verbose:
39
47
  print(
@@ -50,12 +58,16 @@ class ToolExecutor:
50
58
  tool_call_reason=tool_call_reason,
51
59
  )
52
60
  )
61
+
62
+ def _maybe_set_progress_callback(self, func):
53
63
  instance = None
54
64
  if hasattr(func, "__self__") and isinstance(func.__self__, ToolBase):
55
65
  instance = func.__self__
56
66
  if self.message_handler:
57
67
  instance._progress_callback = self.message_handler.handle_message
58
- # Emit tool_call event before calling the tool
68
+ return instance
69
+
70
+ def _emit_tool_call_event(self, tool_call, call_id, args, tool_call_reason):
59
71
  if self.message_handler:
60
72
  event = {
61
73
  "type": "tool_call",
@@ -66,52 +78,45 @@ class ToolExecutor:
66
78
  if tool_call_reason and not runtime_config.get("no_tools_tracking", False):
67
79
  event["tool_call_reason"] = tool_call_reason
68
80
  self.message_handler.handle_message(event)
69
- # Argument validation
81
+
82
+ def _validate_arguments(self, func, args, tool_call, call_id, tool_call_reason):
70
83
  sig = inspect.signature(func)
71
84
  try:
72
85
  sig.bind(**args)
73
86
  except TypeError as e:
74
87
  error_msg = f"Argument validation error for tool '{tool_call.function.name}': {str(e)}"
75
- if self.message_handler:
76
- error_event = {
77
- "type": "tool_error",
78
- "tool": tool_call.function.name,
79
- "call_id": call_id,
80
- "error": error_msg,
81
- }
82
- if tool_call_reason and not runtime_config.get(
83
- "no_tools_tracking", False
84
- ):
85
- error_event["tool_call_reason"] = tool_call_reason
86
- self.message_handler.handle_message(error_event)
88
+ self._emit_tool_error_event(tool_call, call_id, error_msg, tool_call_reason)
87
89
  raise TypeError(error_msg)
88
- # Execute tool
90
+
91
+ def _emit_tool_result_event(self, tool_call, call_id, result, tool_call_reason):
92
+ if self.message_handler:
93
+ result_event = {
94
+ "type": "tool_result",
95
+ "tool": tool_call.function.name,
96
+ "call_id": call_id,
97
+ "result": result,
98
+ }
99
+ if tool_call_reason and not runtime_config.get("no_tools_tracking", False):
100
+ result_event["tool_call_reason"] = tool_call_reason
101
+ self.message_handler.handle_message(result_event)
102
+
103
+ def _emit_tool_error_event(self, tool_call, call_id, error, tool_call_reason):
104
+ if self.message_handler:
105
+ error_event = {
106
+ "type": "tool_error",
107
+ "tool": tool_call.function.name,
108
+ "call_id": call_id,
109
+ "error": error,
110
+ }
111
+ if tool_call_reason and not runtime_config.get("no_tools_tracking", False):
112
+ error_event["tool_call_reason"] = tool_call_reason
113
+ self.message_handler.handle_message(error_event)
114
+
115
+ def _record_tool_usage(self, tool_call, args, result):
89
116
  try:
90
- result = func(**args)
91
- if self.message_handler:
92
- result_event = {
93
- "type": "tool_result",
94
- "tool": tool_call.function.name,
95
- "call_id": call_id,
96
- "result": result,
97
- }
98
- if tool_call_reason and not runtime_config.get(
99
- "no_tools_tracking", False
100
- ):
101
- result_event["tool_call_reason"] = tool_call_reason
102
- self.message_handler.handle_message(result_event)
103
- return result
117
+ from janito.agent.tool_use_tracker import ToolUseTracker
118
+
119
+ ToolUseTracker().record(tool_call.function.name, dict(args), result)
104
120
  except Exception as e:
105
- if self.message_handler:
106
- error_event = {
107
- "type": "tool_error",
108
- "tool": tool_call.function.name,
109
- "call_id": call_id,
110
- "error": str(e),
111
- }
112
- if tool_call_reason and not runtime_config.get(
113
- "no_tools_tracking", False
114
- ):
115
- error_event["tool_call_reason"] = tool_call_reason
116
- self.message_handler.handle_message(error_event)
117
- raise
121
+ if runtime_config.get("verbose", False):
122
+ print(f"[ToolExecutor] ToolUseTracker record failed: {e}")
@@ -1,6 +1,6 @@
1
1
  # janito/agent/tool_registry.py
2
2
  from janito.agent.tool_base import ToolBase
3
- from janito.agent.openai_schema_generator import generate_openai_function_schema
3
+ from janito.agent.openai_schema_generator import OpenAISchemaGenerator
4
4
 
5
5
  _tool_registry = {}
6
6
 
@@ -17,9 +17,12 @@ def register_tool(tool=None, *, name: str = None):
17
17
  f"Tool '{tool.__name__}' must implement a callable 'call' method."
18
18
  )
19
19
  tool_name = override_name or instance.name
20
+ # Add metadata for schema generation
21
+ tool._tool_run_method = instance.run
22
+ tool._tool_name = tool_name
20
23
  if tool_name in _tool_registry:
21
24
  raise ValueError(f"Tool '{tool_name}' is already registered.")
22
- schema = generate_openai_function_schema(instance.run, tool_name, tool_class=tool)
25
+ schema = OpenAISchemaGenerator().generate_schema(tool)
23
26
  _tool_registry[tool_name] = {
24
27
  "function": instance.run,
25
28
  "description": schema["description"],
@@ -1,7 +1,14 @@
1
1
  import threading
2
+ import os
2
3
  from typing import Any, Dict, List
3
4
 
4
5
 
6
+ def normalize_path(path: str) -> str:
7
+ if not isinstance(path, str):
8
+ return path
9
+ return os.path.normcase(os.path.abspath(path))
10
+
11
+
5
12
  class ToolUseTracker:
6
13
  _instance = None
7
14
  _lock = threading.Lock()
@@ -14,25 +21,39 @@ class ToolUseTracker:
14
21
  cls._instance._history = []
15
22
  return cls._instance
16
23
 
17
- def record(self, tool_name: str, params: Dict[str, Any]):
18
- self._history.append({"tool": tool_name, "params": params})
24
+ def record(self, tool_name: str, params: Dict[str, Any], result: Any = None):
25
+ # Normalize file_path in params if present
26
+ norm_params = params.copy()
27
+ if "file_path" in norm_params:
28
+ norm_params["file_path"] = normalize_path(norm_params["file_path"])
29
+ self._history.append(
30
+ {"tool": tool_name, "params": norm_params, "result": result}
31
+ )
19
32
 
20
33
  def get_history(self) -> List[Dict[str, Any]]:
21
34
  return list(self._history)
22
35
 
23
36
  def get_operations_on_file(self, file_path: str) -> List[Dict[str, Any]]:
37
+ norm_file_path = normalize_path(file_path)
24
38
  ops = []
25
39
  for entry in self._history:
26
40
  params = entry["params"]
27
- if any(isinstance(v, str) and file_path in v for v in params.values()):
28
- ops.append(entry)
41
+ # Normalize any string param values for comparison
42
+ for v in params.values():
43
+ if isinstance(v, str) and normalize_path(v) == norm_file_path:
44
+ ops.append(entry)
45
+ break
29
46
  return ops
30
47
 
31
48
  def file_fully_read(self, file_path: str) -> bool:
49
+ norm_file_path = normalize_path(file_path)
32
50
  for entry in self._history:
33
51
  if entry["tool"] == "get_lines":
34
52
  params = entry["params"]
35
- if params.get("file_path") == file_path:
53
+ if (
54
+ "file_path" in params
55
+ and normalize_path(params["file_path"]) == norm_file_path
56
+ ):
36
57
  # If both from_line and to_line are None, full file was read
37
58
  if (
38
59
  params.get("from_line") is None
@@ -14,9 +14,11 @@ from . import replace_text_in_file
14
14
  from . import delete_text_in_file
15
15
  from . import run_bash_command
16
16
  from . import run_powershell_command
17
- from . import run_python_command
18
17
  from . import present_choices
19
18
  from . import search_text
19
+ from . import python_command_runner
20
+ from . import python_file_runner
21
+ from . import python_stdin_runner
20
22
 
21
23
  __all__ = [
22
24
  "ask_user",
@@ -35,8 +37,9 @@ __all__ = [
35
37
  "delete_text_in_file",
36
38
  "run_bash_command",
37
39
  "run_powershell_command",
38
- "run_python_command",
39
- "search_files",
40
40
  "present_choices",
41
41
  "search_text",
42
+ "python_command_runner",
43
+ "python_file_runner",
44
+ "python_stdin_runner",
42
45
  ]
@@ -3,6 +3,7 @@ from janito.agent.tool_registry import register_tool
3
3
  # from janito.agent.tools_utils.expand_path import expand_path
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
  import os
8
9
 
@@ -24,7 +25,8 @@ class CreateDirectoryTool(ToolBase):
24
25
  # Using file_path as is
25
26
  disp_path = display_path(file_path)
26
27
  self.report_info(
27
- tr("📁 Creating directory '{disp_path}' ...", disp_path=disp_path)
28
+ ActionType.WRITE,
29
+ tr("📁 Creating directory '{disp_path}' ...", disp_path=disp_path),
28
30
  )
29
31
  try:
30
32
  if os.path.exists(file_path):
@@ -4,6 +4,7 @@ from janito.agent.tool_registry import register_tool
4
4
  # from janito.agent.tools_utils.expand_path import expand_path
5
5
  from janito.agent.tools_utils.utils import display_path
6
6
  from janito.agent.tool_base import ToolBase
7
+ from janito.agent.tools_utils.action_type import ActionType
7
8
  from janito.i18n import tr
8
9
 
9
10
 
@@ -20,6 +21,8 @@ class CreateFileTool(ToolBase):
20
21
  Returns:
21
22
  str: Status message indicating the result. Example:
22
23
  - "✅ Successfully created the file at ..."
24
+
25
+ Note: Syntax validation is automatically performed after this operation.
23
26
  """
24
27
 
25
28
  def run(self, file_path: str, content: str) -> str:
@@ -40,7 +43,10 @@ class CreateFileTool(ToolBase):
40
43
  dir_name = os.path.dirname(file_path)
41
44
  if dir_name:
42
45
  os.makedirs(dir_name, exist_ok=True)
43
- self.report_info(tr("📝 Creating file '{disp_path}' ...", disp_path=disp_path))
46
+ self.report_info(
47
+ ActionType.WRITE,
48
+ tr("📝 Creating file '{disp_path}' ...", disp_path=disp_path),
49
+ )
44
50
  with open(file_path, "w", encoding="utf-8", errors="replace") as f:
45
51
  f.write(content)
46
52
  new_lines = content.count("\n") + 1 if content else 0
@@ -2,6 +2,7 @@ import requests
2
2
  from bs4 import BeautifulSoup
3
3
  from janito.agent.tool_registry import register_tool
4
4
  from janito.agent.tool_base import ToolBase
5
+ from janito.agent.tools_utils.action_type import ActionType
5
6
  from janito.i18n import tr
6
7
  from janito.agent.tools_utils.utils import pluralize
7
8
 
@@ -24,9 +25,45 @@ class FetchUrlTool(ToolBase):
24
25
  if not url.strip():
25
26
  self.report_warning(tr("ℹ️ Empty URL provided."))
26
27
  return tr("Warning: Empty URL provided. Operation skipped.")
27
- self.report_info(tr("🌐 Fetching URL '{url}' ...", url=url))
28
- response = requests.get(url, timeout=10)
29
- response.raise_for_status()
28
+ self.report_info(ActionType.READ, tr("🌐 Fetching URL '{url}' ...", url=url))
29
+ try:
30
+ response = requests.get(url, timeout=10)
31
+ response.raise_for_status()
32
+ except requests.exceptions.HTTPError as http_err:
33
+ status_code = http_err.response.status_code if http_err.response else None
34
+ if status_code and 400 <= status_code < 500:
35
+ self.report_error(
36
+ tr(
37
+ "❗ HTTP {status_code} error for URL: {url}",
38
+ status_code=status_code,
39
+ url=url,
40
+ )
41
+ )
42
+ return tr(
43
+ "Warning: HTTP {status_code} error for URL: {url}",
44
+ status_code=status_code,
45
+ url=url,
46
+ )
47
+ else:
48
+ self.report_error(
49
+ tr(
50
+ "❗ HTTP error for URL: {url}: {err}",
51
+ url=url,
52
+ err=str(http_err),
53
+ )
54
+ )
55
+ return tr(
56
+ "Warning: HTTP error for URL: {url}: {err}",
57
+ url=url,
58
+ err=str(http_err),
59
+ )
60
+ except Exception as err:
61
+ self.report_error(
62
+ tr("❗ Error fetching URL: {url}: {err}", url=url, err=str(err))
63
+ )
64
+ return tr(
65
+ "Warning: Error fetching URL: {url}: {err}", url=url, err=str(err)
66
+ )
30
67
  self.update_progress(
31
68
  {
32
69
  "event": "progress",
@@ -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.agent.tools_utils.dir_walk_utils import walk_dir_with_gitignore
@@ -38,12 +39,13 @@ class FindFilesTool(ToolBase):
38
39
  else ""
39
40
  )
40
41
  self.report_info(
42
+ ActionType.READ,
41
43
  tr(
42
44
  "🔍 Searching for files '{pattern}' in '{disp_path}'{depth_msg} ...",
43
45
  pattern=pattern,
44
46
  disp_path=disp_path,
45
47
  depth_msg=depth_msg,
46
- )
48
+ ),
47
49
  )
48
50
  dir_output = set()
49
51
  for root, dirs, files in walk_dir_with_gitignore(