janito 0.15.0__py3-none-any.whl → 1.0.1__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 (109) hide show
  1. janito/__init__.py +1 -5
  2. janito/__main__.py +3 -5
  3. janito/agent/__init__.py +1 -0
  4. janito/agent/agent.py +96 -0
  5. janito/agent/config.py +113 -0
  6. janito/agent/config_defaults.py +10 -0
  7. janito/agent/conversation.py +107 -0
  8. janito/agent/queued_tool_handler.py +16 -0
  9. janito/agent/runtime_config.py +30 -0
  10. janito/agent/tool_handler.py +124 -0
  11. janito/agent/tools/__init__.py +11 -0
  12. janito/agent/tools/ask_user.py +63 -0
  13. janito/agent/tools/bash_exec.py +58 -0
  14. janito/agent/tools/create_directory.py +19 -0
  15. janito/agent/tools/create_file.py +43 -0
  16. janito/agent/tools/fetch_url.py +48 -0
  17. janito/agent/tools/file_str_replace.py +48 -0
  18. janito/agent/tools/find_files.py +37 -0
  19. janito/agent/tools/gitignore_utils.py +40 -0
  20. janito/agent/tools/move_file.py +37 -0
  21. janito/agent/tools/remove_file.py +19 -0
  22. janito/agent/tools/rich_live.py +37 -0
  23. janito/agent/tools/rich_utils.py +31 -0
  24. janito/agent/tools/search_text.py +41 -0
  25. janito/agent/tools/view_file.py +34 -0
  26. janito/cli/__init__.py +0 -6
  27. janito/cli/_print_config.py +68 -0
  28. janito/cli/_utils.py +8 -0
  29. janito/cli/arg_parser.py +26 -0
  30. janito/cli/config_commands.py +131 -0
  31. janito/cli/logging_setup.py +27 -0
  32. janito/cli/main.py +39 -0
  33. janito/cli/runner.py +138 -0
  34. janito/cli_chat_shell/__init__.py +1 -0
  35. janito/cli_chat_shell/chat_loop.py +148 -0
  36. janito/cli_chat_shell/commands.py +202 -0
  37. janito/cli_chat_shell/config_shell.py +75 -0
  38. janito/cli_chat_shell/load_prompt.py +15 -0
  39. janito/cli_chat_shell/session_manager.py +60 -0
  40. janito/cli_chat_shell/ui.py +136 -0
  41. janito/render_prompt.py +12 -0
  42. janito/templates/system_instructions.j2 +38 -0
  43. janito/web/__init__.py +0 -0
  44. janito/web/__main__.py +17 -0
  45. janito/web/app.py +132 -0
  46. janito-1.0.1.dist-info/METADATA +144 -0
  47. janito-1.0.1.dist-info/RECORD +51 -0
  48. {janito-0.15.0.dist-info → janito-1.0.1.dist-info}/WHEEL +2 -1
  49. janito-1.0.1.dist-info/entry_points.txt +2 -0
  50. {janito-0.15.0.dist-info → janito-1.0.1.dist-info}/licenses/LICENSE +2 -2
  51. janito-1.0.1.dist-info/top_level.txt +1 -0
  52. janito/callbacks.py +0 -34
  53. janito/cli/agent/__init__.py +0 -7
  54. janito/cli/agent/conversation.py +0 -149
  55. janito/cli/agent/initialization.py +0 -168
  56. janito/cli/agent/query.py +0 -112
  57. janito/cli/agent.py +0 -12
  58. janito/cli/app.py +0 -178
  59. janito/cli/commands/__init__.py +0 -12
  60. janito/cli/commands/config.py +0 -30
  61. janito/cli/commands/history.py +0 -119
  62. janito/cli/commands/profile.py +0 -93
  63. janito/cli/commands/validation.py +0 -24
  64. janito/cli/commands/workspace.py +0 -31
  65. janito/cli/commands.py +0 -12
  66. janito/cli/output.py +0 -29
  67. janito/cli/utils.py +0 -22
  68. janito/config/README.md +0 -104
  69. janito/config/__init__.py +0 -16
  70. janito/config/cli/__init__.py +0 -28
  71. janito/config/cli/commands.py +0 -397
  72. janito/config/cli/validators.py +0 -77
  73. janito/config/core/__init__.py +0 -23
  74. janito/config/core/file_operations.py +0 -90
  75. janito/config/core/properties.py +0 -316
  76. janito/config/core/singleton.py +0 -282
  77. janito/config/profiles/__init__.py +0 -8
  78. janito/config/profiles/definitions.py +0 -38
  79. janito/config/profiles/manager.py +0 -80
  80. janito/data/instructions_template.txt +0 -34
  81. janito/token_report.py +0 -154
  82. janito/tools/__init__.py +0 -44
  83. janito/tools/bash/bash.py +0 -157
  84. janito/tools/bash/unix_persistent_bash.py +0 -215
  85. janito/tools/bash/win_persistent_bash.py +0 -341
  86. janito/tools/decorators.py +0 -90
  87. janito/tools/delete_file.py +0 -65
  88. janito/tools/fetch_webpage/__init__.py +0 -23
  89. janito/tools/fetch_webpage/core.py +0 -182
  90. janito/tools/find_files.py +0 -220
  91. janito/tools/move_file.py +0 -72
  92. janito/tools/prompt_user.py +0 -57
  93. janito/tools/replace_file.py +0 -63
  94. janito/tools/rich_console.py +0 -176
  95. janito/tools/search_text.py +0 -226
  96. janito/tools/str_replace_editor/__init__.py +0 -6
  97. janito/tools/str_replace_editor/editor.py +0 -55
  98. janito/tools/str_replace_editor/handlers/__init__.py +0 -16
  99. janito/tools/str_replace_editor/handlers/create.py +0 -60
  100. janito/tools/str_replace_editor/handlers/insert.py +0 -100
  101. janito/tools/str_replace_editor/handlers/str_replace.py +0 -94
  102. janito/tools/str_replace_editor/handlers/undo.py +0 -64
  103. janito/tools/str_replace_editor/handlers/view.py +0 -165
  104. janito/tools/str_replace_editor/utils.py +0 -33
  105. janito/tools/think.py +0 -37
  106. janito/tools/usage_tracker.py +0 -137
  107. janito-0.15.0.dist-info/METADATA +0 -481
  108. janito-0.15.0.dist-info/RECORD +0 -64
  109. janito-0.15.0.dist-info/entry_points.txt +0 -2
@@ -0,0 +1,51 @@
1
+ janito/__init__.py,sha256=j9q3lYMZra0QrErNnn9E5GNXxWLOlDgeOkmX8oXa7ro,23
2
+ janito/__main__.py,sha256=CBScR30Tm-vuhIJM8o5HXKr0q-smICiwSVyuU68BP8U,78
3
+ janito/render_prompt.py,sha256=HrMUELV4tI3PWqv6RM6teiVvnUejdehBcnHUFzit3Bo,445
4
+ janito/agent/__init__.py,sha256=CByAH5Yk-yH64zo0RU7Z3nsn_7Vmandphqk0JNlpyj8,21
5
+ janito/agent/agent.py,sha256=qGjkGajNjroz1kU-iV--0DD_2FwmwjAM1Y9Z5foxwoE,3590
6
+ janito/agent/config.py,sha256=6WQbjrK-UwkG9Yb5e5ljfBIvQs3Y_Wgd3Py8FbO0RiI,3565
7
+ janito/agent/config_defaults.py,sha256=cR4kFkjg6BFccE0psy4khBiKjnj60VCQhmqLvLbjcJM,373
8
+ janito/agent/conversation.py,sha256=5UtWgDsRh205p0Dq8tEtqEPT0avL8KFs3xmwJomaYEk,4664
9
+ janito/agent/queued_tool_handler.py,sha256=THPymKXnpoXfN49EhW5b4hrwpWZZup73JKFDJ_U03tI,540
10
+ janito/agent/runtime_config.py,sha256=gigcKUwaXs_qSdXdC5InUTPmdXUbOA-tRUx2ZJ5zzI0,906
11
+ janito/agent/tool_handler.py,sha256=f3iOWi78bKn0B6twMlayedmE0OMeQ1do32yZl4DMzaE,4399
12
+ janito/agent/tools/__init__.py,sha256=7-RjFK1YXacifjSrXT4EdMXG_kyKVl7TCjrcHkklaCQ,414
13
+ janito/agent/tools/ask_user.py,sha256=MHKHyBTD4iyCM-z9_ZUbe7AMn-pz7cr6FIAB0SdESH4,1895
14
+ janito/agent/tools/bash_exec.py,sha256=1HkjvTlXunjZ7xvxqzdayG8JWtrioC0MYOfdid_6uiY,2486
15
+ janito/agent/tools/create_directory.py,sha256=qnP8bFeAYr3fnstbIIp6EOqur1o0xAVv1k21Y9LOAHs,698
16
+ janito/agent/tools/create_file.py,sha256=pauO9YYnPDeO61U2tcTHgC1VPJ7yhWQOrIHhCKuLk8E,1782
17
+ janito/agent/tools/fetch_url.py,sha256=ZPasbnPxM-lcVlpRUwviGmhiqm-MoVFA1_1K99h8I94,1926
18
+ janito/agent/tools/file_str_replace.py,sha256=9ooaDVEHT4WDdSbFZuz_QHkQpG9s8OtP1g99_GbechA,2012
19
+ janito/agent/tools/find_files.py,sha256=KgvnAAa7YbU59ASYcUI6XsGpxB7ouPde7E1h8e8Vf4E,1608
20
+ janito/agent/tools/gitignore_utils.py,sha256=zXiqx4HetZ7iKkV5qXyHyZ5yrrVex4G17WHBWToFo3Y,1158
21
+ janito/agent/tools/move_file.py,sha256=aIbZ0Jxt0JI8fHqW5SPkNMiFFs40s_wYXoHT8ooPHzs,1679
22
+ janito/agent/tools/remove_file.py,sha256=sWvdDIP5lrQh4rhBcQEEa1hQ6AJDCuFovsBZkirk3mU,658
23
+ janito/agent/tools/rich_live.py,sha256=cuZ3-ZxpuHxR1TvIcp0bi9F3QM1M6Ms0XiOMd8If8gU,1161
24
+ janito/agent/tools/rich_utils.py,sha256=aQMqeaq3hIpzZ5EHQBNTKS5dNsojQp9MDfJSoqOQe0k,837
25
+ janito/agent/tools/search_text.py,sha256=TdTpaomLt4oZpX_0zz9W_bXhI5vvQLu0IjA7mCRCJYU,2020
26
+ janito/agent/tools/view_file.py,sha256=i4IBpn_Waw_4sgHUOaPIYPcMNmmvzM9ECoR5O5fldfU,1535
27
+ janito/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
28
+ janito/cli/_print_config.py,sha256=gsdVgG8uGHoWZHUSzgvB-FIrlvAawF0HjXtiQZAloPk,3116
29
+ janito/cli/_utils.py,sha256=Q_OCFZmbr78qW4hSSUUhjondVc0ao7-iUHE7Ig8IP1g,289
30
+ janito/cli/arg_parser.py,sha256=6Y_gBJSPk7tdHKSAsi1fQdr4pnCp8dcSGFrlu7s8KiI,2498
31
+ janito/cli/config_commands.py,sha256=Ovk2LszVrHcKSqXjlH-fvJYhT3axZomlh9_wpNQfSYI,5675
32
+ janito/cli/logging_setup.py,sha256=dWQ0wFf4YuF5lxZlhpN6lis7G56LeFYUwQdh9nA5NmA,1141
33
+ janito/cli/main.py,sha256=ONmn_lIPu8_Rd57j3YfWEx46fWj8gAkONPLdctABwy0,1333
34
+ janito/cli/runner.py,sha256=K_xpygfg4MpyLuI6hx3s1I6-leEd80w08l3F6PIO4so,5362
35
+ janito/cli_chat_shell/__init__.py,sha256=PDGl7xK_vgkROoXvUxGZqVQFfuL9U4TjdexpP8E2JKg,41
36
+ janito/cli_chat_shell/chat_loop.py,sha256=KjnmhOYU0zblBzV5Q80BCqgvKSi_rPpE3TykzzDoexk,5259
37
+ janito/cli_chat_shell/commands.py,sha256=Tvhw8azybchGS1qi2yJEn3FKho-FDYOK1ZT865GYwhM,7615
38
+ janito/cli_chat_shell/config_shell.py,sha256=s59PCt_TmBPqQJ_C8nkKo4kCcW9aq3Jhpe9RlRCa0-s,3265
39
+ janito/cli_chat_shell/load_prompt.py,sha256=EuUlHg317T8f5VqEMaJxFgzWBl51zC2sND0eeYr6pJ4,612
40
+ janito/cli_chat_shell/session_manager.py,sha256=Gax0pC0ediDsExLUwPEg_nD8MdSrznaHoer53zxLYuE,1966
41
+ janito/cli_chat_shell/ui.py,sha256=7O36dWaXDQ5r-GGD6a57iHSiDpN2pkdav3HxSdf6CIc,5279
42
+ janito/templates/system_instructions.j2,sha256=f-hRp0ZliGac8vg6HJiYkU0TketpFoSbUunh9TOQrtE,1795
43
+ janito/web/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
44
+ janito/web/__main__.py,sha256=oPXNF332aCeI7aUWr7_8M57oOKugw422VrEubxFp0P4,354
45
+ janito/web/app.py,sha256=bZse9S_F9hFSYRTJxoel5RjrtoAmvJ_lYkPfKRmBI1o,4125
46
+ janito-1.0.1.dist-info/licenses/LICENSE,sha256=sHBqv0bvtrb29H7WRR-Z603YHm9pLtJIo3nHU_9cmgE,1091
47
+ janito-1.0.1.dist-info/METADATA,sha256=NcSx21pY78wR4NzupbiIuEc0srPMn9nToBpLFbKZQjM,5103
48
+ janito-1.0.1.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
49
+ janito-1.0.1.dist-info/entry_points.txt,sha256=wIo5zZxbmu4fC-ZMrsKD0T0vq7IqkOOLYhrqRGypkx4,48
50
+ janito-1.0.1.dist-info/top_level.txt,sha256=m0NaVCq0-ivxbazE2-ND0EA9Hmuijj_OGkmCbnBcCig,7
51
+ janito-1.0.1.dist-info/RECORD,,
@@ -1,4 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.27.0
2
+ Generator: setuptools (78.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ janito = janito.__main__:main
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) [year] [copyright holder]
3
+ Copyright (c) [year] [Full Name]
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ janito
janito/callbacks.py DELETED
@@ -1,34 +0,0 @@
1
- """
2
- Callback functions for tool execution in janito.
3
- """
4
-
5
- from rich.console import Console
6
- from rich.markdown import Markdown
7
-
8
- from janito.config import get_config
9
-
10
- # Counter for pre-tool callbacks
11
- pre_tool_callbacks = 0
12
-
13
- def text_callback(text: str) -> None:
14
- """
15
- Callback function that handles text output from the agent.
16
-
17
- Args:
18
- text: Text output from the agent
19
-
20
- Returns:
21
- None
22
- """
23
- console = Console()
24
-
25
- # Add debug counter only when debug mode is enabled
26
- if get_config().debug_mode:
27
- if not hasattr(text_callback, "counter"):
28
- text_callback.counter = 1
29
- console.print(f"[bold blue]DEBUG: Text callback #{text_callback.counter}[/bold blue]")
30
- text_callback.counter += 1
31
-
32
- # Print the text with markdown formatting
33
- console.print(Markdown(text, code_theme="monokai"), end="")
34
-
@@ -1,7 +0,0 @@
1
- """
2
- Agent initialization and query handling for Janito CLI.
3
- """
4
- from janito.cli.agent.query import handle_query
5
- from janito.cli.agent.conversation import load_messages, save_messages
6
-
7
- __all__ = ["handle_query", "load_messages", "save_messages"]
@@ -1,149 +0,0 @@
1
- """
2
- Conversation management functionality for Janito CLI.
3
- """
4
- import json
5
- import datetime
6
- import sys
7
- from typing import Optional, List, Dict, Any
8
- from rich.console import Console
9
- from pathlib import Path
10
- import claudine
11
-
12
- from janito.config import get_config
13
-
14
- console = Console()
15
-
16
- def generate_message_id() -> str:
17
- """
18
- Generate a message ID based on timestamp with seconds granularity
19
-
20
- Returns:
21
- str: A timestamp-based message ID
22
- """
23
- timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
24
- return timestamp
25
-
26
- def save_messages(agent: claudine.Agent) -> Optional[str]:
27
- """
28
- Save agent messages to .janito/last_messages/{message_id}.json
29
-
30
- Args:
31
- agent: The claudine agent instance
32
-
33
- Returns:
34
- str: The message ID used for saving, or None if saving failed
35
- """
36
- try:
37
- # Get the workspace directory
38
- workspace_dir = Path(get_config().workspace_dir)
39
-
40
- # Create .janito directory if it doesn't exist
41
- janito_dir = workspace_dir / ".janito"
42
- janito_dir.mkdir(exist_ok=True)
43
-
44
- # Create last_messages directory if it doesn't exist
45
- messages_dir = janito_dir / "last_messages"
46
- messages_dir.mkdir(exist_ok=True)
47
-
48
- # Generate a unique message ID
49
- message_id = generate_message_id()
50
-
51
- # Get messages from the agent
52
- messages = agent.get_messages()
53
-
54
- # Create a message object with metadata
55
- message_object = {
56
- "id": message_id,
57
- "timestamp": datetime.datetime.now().isoformat(),
58
- "messages": messages
59
- }
60
-
61
- # Save messages to file
62
- message_file = messages_dir / f"{message_id}.json"
63
- with open(message_file, "w", encoding="utf-8") as f:
64
- json.dump(message_object, f, ensure_ascii=False, indent=2)
65
-
66
- if get_config().verbose:
67
- console.print(f"[bold green]✅ Conversation saved to {message_file}[/bold green]")
68
-
69
- return message_id
70
- except Exception as e:
71
- console.print(f"[bold red]❌ Error saving conversation:[/bold red] {str(e)}")
72
- return None
73
-
74
- def load_messages(message_id: Optional[str] = None) -> Optional[List[Dict[str, Any]]]:
75
- """
76
- Load messages from .janito/last_messages/{message_id}.json or the latest message file
77
-
78
- Args:
79
- message_id: Optional message ID to load specific conversation
80
-
81
- Returns:
82
- List of message dictionaries or None if file doesn't exist
83
- """
84
- try:
85
- # Get the workspace directory
86
- workspace_dir = Path(get_config().workspace_dir)
87
- janito_dir = workspace_dir / ".janito"
88
- messages_dir = janito_dir / "last_messages"
89
-
90
- # If message_id is provided, try to load that specific conversation
91
- if message_id:
92
- # Check if the message ID is a file name or just the ID
93
- if message_id.endswith('.json'):
94
- message_file = messages_dir / message_id
95
- else:
96
- message_file = messages_dir / f"{message_id}.json"
97
-
98
- if not message_file.exists():
99
- console.print(f"[bold yellow]⚠️ No conversation found with ID {message_id}[/bold yellow]")
100
- return None
101
-
102
- # Load messages from file
103
- with open(message_file, "r", encoding="utf-8") as f:
104
- message_object = json.load(f)
105
-
106
- # Extract messages from the message object
107
- if isinstance(message_object, dict) and "messages" in message_object:
108
- messages = message_object["messages"]
109
- else:
110
- # Handle legacy format
111
- messages = message_object
112
-
113
- if get_config().verbose:
114
- console.print(f"[bold green]✅ Loaded conversation from {message_file}[/bold green]")
115
- console.print(f"[dim]📝 Conversation has {len(messages)} messages[/dim]")
116
-
117
- return messages
118
-
119
- # If no message_id is provided, try to load the latest message from last_messages directory
120
- if not messages_dir.exists() or not any(messages_dir.iterdir()):
121
- console.print("[bold yellow]⚠️ No previous conversation found[/bold yellow]")
122
- return None
123
-
124
- # Find the latest message file (based on filename which is a timestamp)
125
- latest_file = max(
126
- [f for f in messages_dir.iterdir() if f.is_file() and f.suffix == '.json'],
127
- key=lambda x: x.stem
128
- )
129
-
130
- # Load messages from the latest file
131
- with open(latest_file, "r", encoding="utf-8") as f:
132
- message_object = json.load(f)
133
-
134
- # Extract messages from the message object
135
- if isinstance(message_object, dict) and "messages" in message_object:
136
- messages = message_object["messages"]
137
- else:
138
- # Handle legacy format
139
- messages = message_object
140
-
141
- if get_config().verbose:
142
- console.print(f"[bold green]✅ Loaded latest conversation from {latest_file}[/bold green]")
143
- console.print(f"[dim]📝 Conversation has {len(messages)} messages[/dim]")
144
-
145
- return messages
146
- except Exception as e:
147
- console.print(f"[bold red]❌ Error loading conversation:[/bold red] {str(e)}")
148
- return None
149
-
@@ -1,168 +0,0 @@
1
- """
2
- Agent initialization functionality for Janito CLI.
3
- """
4
- import os
5
- import platform
6
- import typer
7
- from typing import Optional, Dict, Any
8
- from rich.console import Console
9
- from jinja2 import Template
10
- import importlib.resources as pkg_resources
11
- import claudine
12
-
13
- from janito.config import get_config, Config
14
- from janito.callbacks import text_callback
15
- from janito.tools import str_replace_editor, get_tools, reset_tracker
16
- from janito.tools.bash.bash import bash_tool
17
- from janito.cli.output import display_generation_params
18
-
19
- console = Console()
20
-
21
- def get_api_key() -> str:
22
- """
23
- Get the API key from global config or user input.
24
-
25
- Returns:
26
- str: The API key
27
- """
28
- # Get API key from global config or ask the user
29
- api_key = Config.get_api_key()
30
-
31
- # If not found, prompt the user
32
- if not api_key:
33
- console.print("[bold yellow]⚠️ Warning:[/bold yellow] API key not found in global config.")
34
- console.print("🔑 Please set it using --set-api-key or provide your API key now:")
35
- api_key = typer.prompt("Anthropic API Key", hide_input=True)
36
-
37
- return api_key
38
-
39
- def load_instructions() -> str:
40
- """
41
- Load instructions template and render it with variables.
42
-
43
- Returns:
44
- str: The rendered instructions
45
- """
46
- try:
47
- # For Python 3.9+
48
- try:
49
- from importlib.resources import files
50
- template_content = files('janito.data').joinpath('instructions_template.txt').read_text(encoding='utf-8')
51
- # Fallback for older Python versions
52
- except (ImportError, AttributeError):
53
- template_content = pkg_resources.read_text('janito.data', 'instructions_template.txt', encoding='utf-8')
54
-
55
- # Create template variables
56
- template_variables = {
57
- 'platform': platform.system(),
58
- 'role': get_config().role,
59
- # Add any other variables you want to pass to the template here
60
- }
61
-
62
- # Create template and render
63
- template = Template(template_content)
64
- instructions = template.render(**template_variables)
65
-
66
- except Exception as e:
67
- console.print(f"[bold red]❌ Error loading instructions template:[/bold red] {str(e)}")
68
- # Try to fall back to regular instructions.txt
69
- try:
70
- # For Python 3.9+
71
- try:
72
- from importlib.resources import files
73
- instructions = files('janito.data').joinpath('instructions.txt').read_text(encoding='utf-8')
74
- # Fallback for older Python versions
75
- except (ImportError, AttributeError):
76
- instructions = pkg_resources.read_text('janito.data', 'instructions.txt', encoding='utf-8')
77
- except Exception as e2:
78
- console.print(f"[bold red]❌ Error loading fallback instructions:[/bold red] {str(e2)}")
79
- instructions = "You are Janito, an AI assistant."
80
-
81
- return instructions
82
-
83
- def initialize_agent(temperature: float, verbose: bool, system_instructions: Optional[str] = None) -> claudine.Agent:
84
- """
85
- Initialize the Claude agent with tools and configuration.
86
-
87
- Args:
88
- temperature: Temperature value for model generation
89
- verbose: Whether to enable verbose mode
90
- system_instructions: Optional custom system instructions to use instead of loading from file
91
-
92
- Returns:
93
- claudine.Agent: The initialized agent
94
- """
95
- # Get API key
96
- api_key = get_api_key()
97
-
98
- # Load instructions or use provided system instructions
99
- if system_instructions:
100
- instructions = system_instructions
101
- if verbose:
102
- console.print("[bold blue]🔄 Using custom system instructions provided via --system parameter[/bold blue]")
103
- # Print the first 50 characters of the instructions for verification
104
- preview = system_instructions[:50] + "..." if len(system_instructions) > 50 else system_instructions
105
- console.print(f"[dim]System instructions preview: {preview}[/dim]")
106
- else:
107
- instructions = load_instructions()
108
-
109
- # Get tools
110
- tools_list = get_tools()
111
-
112
- # Reset usage tracker before each query
113
- reset_tracker()
114
-
115
- # Use command line parameters if provided (not default values), otherwise use config
116
- temp_to_use = temperature if temperature != 0.0 else get_config().temperature
117
-
118
- # Get profile parameters if a profile is set
119
- config = get_config()
120
- profile_data = None
121
- if config.profile:
122
- profile_data = config.get_available_profiles()[config.profile]
123
-
124
- # Display generation parameters if verbose mode is enabled
125
- if verbose:
126
- display_generation_params(temp_to_use, profile_data, temperature)
127
-
128
- # Create config_params dictionary with generation parameters
129
- config_params = {
130
- "temperature": temp_to_use
131
- }
132
-
133
- # Add top_k and top_p from profile if available
134
- if profile_data:
135
- if "top_k" in profile_data and profile_data["top_k"] != 0:
136
- config_params["top_k"] = profile_data["top_k"]
137
- if "top_p" in profile_data and profile_data["top_p"] != 0.0:
138
- config_params["top_p"] = profile_data["top_p"]
139
-
140
- # Initialize the agent
141
- if get_config().no_tools:
142
- # If no_tools mode is enabled, don't pass any tools to the agent
143
- agent = claudine.Agent(
144
- api_key=api_key,
145
- system_prompt=instructions,
146
- callbacks={"text": text_callback},
147
- verbose=verbose,
148
- max_tokens=8126,
149
- max_tool_rounds=100,
150
- config_params=config_params,
151
- # Don't pass any tools, including text_editor_tool and bash_tool
152
- )
153
- else:
154
- # Normal mode with tools
155
- agent = claudine.Agent(
156
- api_key=api_key,
157
- system_prompt=instructions,
158
- callbacks={"text": text_callback},
159
- text_editor_tool=str_replace_editor,
160
- bash_tool=bash_tool,
161
- tools=tools_list,
162
- verbose=verbose,
163
- max_tokens=8126,
164
- max_tool_rounds=100,
165
- config_params=config_params,
166
- )
167
-
168
- return agent
janito/cli/agent/query.py DELETED
@@ -1,112 +0,0 @@
1
- """
2
- Query handling functionality for Janito CLI.
3
- """
4
- import sys
5
- import traceback
6
- from typing import Optional
7
- from rich.console import Console
8
- import anthropic
9
-
10
- from janito.token_report import generate_token_report
11
- from janito.tools import print_usage_stats
12
- from janito.cli.agent.initialization import initialize_agent
13
- from janito.cli.agent.conversation import load_messages, save_messages
14
- from janito.config import Config
15
-
16
- console = Console()
17
-
18
- def handle_query(query: str, temperature: float, verbose: bool, show_tokens: bool, continue_conversation: Optional[str] = None, system_instructions: Optional[str] = None) -> None:
19
- """
20
- Handle a query by initializing the agent and sending the query.
21
-
22
- Args:
23
- query: The query to send to the agent
24
- temperature: Temperature value for model generation
25
- verbose: Whether to enable verbose mode
26
- show_tokens: Whether to show detailed token usage
27
- continue_conversation: Optional message ID to continue a specific conversation
28
- system_instructions: Optional custom system instructions to use instead of loading from file
29
- """
30
- # Initialize the agent
31
- agent = initialize_agent(temperature, verbose, system_instructions)
32
-
33
- # Load previous messages if continuing conversation
34
- if continue_conversation is not None:
35
- # If continue_conversation is an empty string (from flag with no value), use default behavior
36
- message_id = None if continue_conversation == "" else continue_conversation
37
- messages = load_messages(message_id)
38
- if messages:
39
- agent.set_messages(messages)
40
- if message_id:
41
- console.print(f"[bold blue]🔄 Continuing conversation with ID: {message_id}[/bold blue]")
42
- else:
43
- console.print("[bold blue]🔄 Continuing most recent conversation[/bold blue]")
44
-
45
- # Provide information about the conversation being continued
46
- if verbose and len(messages) > 0:
47
- # Get the number of messages
48
- num_messages = len(messages)
49
- # Get the last user message if available
50
- last_user_message = next((msg.get("content", "") for msg in reversed(messages)
51
- if msg.get("role") == "user"), "")
52
- if last_user_message:
53
- console.print(f"[dim]📝 Last query: \"{last_user_message[:60]}{'...' if len(last_user_message) > 60 else ''}\"[/dim]")
54
- else:
55
- console.print("[bold yellow]⚠️ No previous conversation found to continue[/bold yellow]")
56
-
57
- # Send the query to the agent
58
- try:
59
- agent.query(query)
60
-
61
- # Save messages after successful query and get the message ID
62
- message_id = save_messages(agent)
63
-
64
- # Check if usage reports should be shown
65
- if Config().show_usage_report:
66
- # Print token usage report
67
- if show_tokens:
68
- generate_token_report(agent, verbose=True, interrupted=False)
69
- else:
70
- # Show basic token usage
71
- generate_token_report(agent, verbose=False, interrupted=False)
72
-
73
- # Print tool usage statistics
74
- print_usage_stats()
75
-
76
-
77
-
78
- except KeyboardInterrupt:
79
- # Handle Ctrl+C by printing token and tool usage information
80
- console.print("\n[bold yellow]⚠️ Query interrupted by user (Ctrl+C)[/bold yellow]")
81
-
82
- # Save messages even if interrupted
83
- message_id = save_messages(agent)
84
-
85
- # Check if usage reports should be shown
86
- if Config().show_usage_report:
87
- # Print token usage report (even if interrupted)
88
- try:
89
- if show_tokens:
90
- generate_token_report(agent, verbose=True, interrupted=True)
91
- else:
92
- # Show basic token usage
93
- generate_token_report(agent, verbose=False, interrupted=True)
94
-
95
- # Print tool usage statistics
96
- print_usage_stats()
97
-
98
- except Exception as e:
99
- console.print(f"[bold red]❌ Error generating usage report:[/bold red] {str(e)}")
100
- if verbose:
101
- console.print(traceback.format_exc())
102
-
103
- # Exit with non-zero status to indicate interruption
104
- sys.exit(130) # 130 is the standard exit code for SIGINT
105
-
106
- except anthropic.APIError as e:
107
- console.print(f"[bold red]❌ Anthropic API Error:[/bold red] {str(e)}")
108
-
109
- except Exception as e:
110
- console.print(f"[bold red]❌ Error:[/bold red] {str(e)}")
111
- if verbose:
112
- console.print(traceback.format_exc())
janito/cli/agent.py DELETED
@@ -1,12 +0,0 @@
1
- """
2
- Agent initialization and query handling for Janito CLI.
3
-
4
- This file is a compatibility layer that imports from the new module structure.
5
- """
6
-
7
- # Import the public API from the new module structure
8
- from janito.cli.agent.query import handle_query
9
- from janito.cli.agent.conversation import load_messages, save_messages
10
-
11
- # Export the public API
12
- __all__ = ["handle_query", "load_messages", "save_messages"]