janito 0.14.0__py3-none-any.whl → 1.0.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 (98) 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 +135 -0
  34. janito/cli_chat_shell/__init__.py +1 -0
  35. janito/cli_chat_shell/chat_loop.py +147 -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 +36 -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.0.dist-info/METADATA +144 -0
  47. janito-1.0.0.dist-info/RECORD +51 -0
  48. {janito-0.14.0.dist-info → janito-1.0.0.dist-info}/WHEEL +2 -1
  49. janito-1.0.0.dist-info/entry_points.txt +2 -0
  50. {janito-0.14.0.dist-info → janito-1.0.0.dist-info}/licenses/LICENSE +2 -2
  51. janito-1.0.0.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 -172
  56. janito/cli/agent/query.py +0 -108
  57. janito/cli/agent.py +0 -12
  58. janito/cli/app.py +0 -182
  59. janito/cli/commands/__init__.py +0 -12
  60. janito/cli/commands/config.py +0 -242
  61. janito/cli/commands/history.py +0 -119
  62. janito/cli/commands/profile.py +0 -72
  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.py +0 -375
  69. janito/data/instructions_template.txt +0 -31
  70. janito/token_report.py +0 -154
  71. janito/tools/__init__.py +0 -44
  72. janito/tools/bash/bash.py +0 -84
  73. janito/tools/bash/unix_persistent_bash.py +0 -184
  74. janito/tools/bash/win_persistent_bash.py +0 -308
  75. janito/tools/decorators.py +0 -90
  76. janito/tools/delete_file.py +0 -65
  77. janito/tools/fetch_webpage/__init__.py +0 -23
  78. janito/tools/fetch_webpage/core.py +0 -182
  79. janito/tools/find_files.py +0 -220
  80. janito/tools/move_file.py +0 -72
  81. janito/tools/prompt_user.py +0 -57
  82. janito/tools/replace_file.py +0 -63
  83. janito/tools/rich_console.py +0 -176
  84. janito/tools/search_text.py +0 -226
  85. janito/tools/str_replace_editor/__init__.py +0 -6
  86. janito/tools/str_replace_editor/editor.py +0 -55
  87. janito/tools/str_replace_editor/handlers/__init__.py +0 -16
  88. janito/tools/str_replace_editor/handlers/create.py +0 -60
  89. janito/tools/str_replace_editor/handlers/insert.py +0 -100
  90. janito/tools/str_replace_editor/handlers/str_replace.py +0 -94
  91. janito/tools/str_replace_editor/handlers/undo.py +0 -64
  92. janito/tools/str_replace_editor/handlers/view.py +0 -159
  93. janito/tools/str_replace_editor/utils.py +0 -33
  94. janito/tools/think.py +0 -37
  95. janito/tools/usage_tracker.py +0 -137
  96. janito-0.14.0.dist-info/METADATA +0 -396
  97. janito-0.14.0.dist-info/RECORD +0 -53
  98. janito-0.14.0.dist-info/entry_points.txt +0 -2
@@ -0,0 +1,51 @@
1
+ janito/__init__.py,sha256=ZhzQKWZ8RFrTIkj7z87B144DI95e8LMfA5w8NDWQDtg,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=OWQ1i1FsrojBRiahoTIKcx4fChHv2qXzDjF7hhvD7lg,5228
35
+ janito/cli_chat_shell/__init__.py,sha256=PDGl7xK_vgkROoXvUxGZqVQFfuL9U4TjdexpP8E2JKg,41
36
+ janito/cli_chat_shell/chat_loop.py,sha256=ySuwJ9JPkYDTZ8Ls2moxNDB1h9dtIHVpEOsIkcn5lyg,5173
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=CZatXq9HGwcg4tjMhI91etDILAvLsI5mw8wiXO3zTSk,1725
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.0.dist-info/licenses/LICENSE,sha256=sHBqv0bvtrb29H7WRR-Z603YHm9pLtJIo3nHU_9cmgE,1091
47
+ janito-1.0.0.dist-info/METADATA,sha256=ZKWmFtrHsA4zxTjv9BcuT1QJCZylN4MEBBV5YmONkZU,5103
48
+ janito-1.0.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
49
+ janito-1.0.0.dist-info/entry_points.txt,sha256=wIo5zZxbmu4fC-ZMrsKD0T0vq7IqkOOLYhrqRGypkx4,48
50
+ janito-1.0.0.dist-info/top_level.txt,sha256=m0NaVCq0-ivxbazE2-ND0EA9Hmuijj_OGkmCbnBcCig,7
51
+ janito-1.0.0.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,172 +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, environment variable, or user input.
24
-
25
- Returns:
26
- str: The API key
27
- """
28
- # Get API key from global config, environment variable, or ask the user
29
- api_key = Config.get_api_key()
30
-
31
- # If not found in global config, try environment variable
32
- if not api_key:
33
- api_key = os.environ.get("ANTHROPIC_API_KEY")
34
-
35
- # If still not found, prompt the user
36
- if not api_key:
37
- console.print("[bold yellow]⚠️ Warning:[/bold yellow] API key not found in global config or ANTHROPIC_API_KEY environment variable.")
38
- console.print("🔑 Please set it using --set-api-key or provide your API key now:")
39
- api_key = typer.prompt("Anthropic API Key", hide_input=True)
40
-
41
- return api_key
42
-
43
- def load_instructions() -> str:
44
- """
45
- Load instructions template and render it with variables.
46
-
47
- Returns:
48
- str: The rendered instructions
49
- """
50
- try:
51
- # For Python 3.9+
52
- try:
53
- from importlib.resources import files
54
- template_content = files('janito.data').joinpath('instructions_template.txt').read_text(encoding='utf-8')
55
- # Fallback for older Python versions
56
- except (ImportError, AttributeError):
57
- template_content = pkg_resources.read_text('janito.data', 'instructions_template.txt', encoding='utf-8')
58
-
59
- # Create template variables
60
- template_variables = {
61
- 'platform': platform.system(),
62
- 'role': get_config().role,
63
- # Add any other variables you want to pass to the template here
64
- }
65
-
66
- # Create template and render
67
- template = Template(template_content)
68
- instructions = template.render(**template_variables)
69
-
70
- except Exception as e:
71
- console.print(f"[bold red]❌ Error loading instructions template:[/bold red] {str(e)}")
72
- # Try to fall back to regular instructions.txt
73
- try:
74
- # For Python 3.9+
75
- try:
76
- from importlib.resources import files
77
- instructions = files('janito.data').joinpath('instructions.txt').read_text(encoding='utf-8')
78
- # Fallback for older Python versions
79
- except (ImportError, AttributeError):
80
- instructions = pkg_resources.read_text('janito.data', 'instructions.txt', encoding='utf-8')
81
- except Exception as e2:
82
- console.print(f"[bold red]❌ Error loading fallback instructions:[/bold red] {str(e2)}")
83
- instructions = "You are Janito, an AI assistant."
84
-
85
- return instructions
86
-
87
- def initialize_agent(temperature: float, verbose: bool, system_instructions: Optional[str] = None) -> claudine.Agent:
88
- """
89
- Initialize the Claude agent with tools and configuration.
90
-
91
- Args:
92
- temperature: Temperature value for model generation
93
- verbose: Whether to enable verbose mode
94
- system_instructions: Optional custom system instructions to use instead of loading from file
95
-
96
- Returns:
97
- claudine.Agent: The initialized agent
98
- """
99
- # Get API key
100
- api_key = get_api_key()
101
-
102
- # Load instructions or use provided system instructions
103
- if system_instructions:
104
- instructions = system_instructions
105
- if verbose:
106
- console.print("[bold blue]🔄 Using custom system instructions provided via --system parameter[/bold blue]")
107
- # Print the first 50 characters of the instructions for verification
108
- preview = system_instructions[:50] + "..." if len(system_instructions) > 50 else system_instructions
109
- console.print(f"[dim]System instructions preview: {preview}[/dim]")
110
- else:
111
- instructions = load_instructions()
112
-
113
- # Get tools
114
- tools_list = get_tools()
115
-
116
- # Reset usage tracker before each query
117
- reset_tracker()
118
-
119
- # Use command line parameters if provided (not default values), otherwise use config
120
- temp_to_use = temperature if temperature != 0.0 else get_config().temperature
121
-
122
- # Get profile parameters if a profile is set
123
- config = get_config()
124
- profile_data = None
125
- if config.profile:
126
- profile_data = config.get_available_profiles()[config.profile]
127
-
128
- # Display generation parameters if verbose mode is enabled
129
- if verbose:
130
- display_generation_params(temp_to_use, profile_data, temperature)
131
-
132
- # Create config_params dictionary with generation parameters
133
- config_params = {
134
- "temperature": temp_to_use
135
- }
136
-
137
- # Add top_k and top_p from profile if available
138
- if profile_data:
139
- if "top_k" in profile_data and profile_data["top_k"] != 0:
140
- config_params["top_k"] = profile_data["top_k"]
141
- if "top_p" in profile_data and profile_data["top_p"] != 0.0:
142
- config_params["top_p"] = profile_data["top_p"]
143
-
144
- # Initialize the agent
145
- if get_config().no_tools:
146
- # If no_tools mode is enabled, don't pass any tools to the agent
147
- agent = claudine.Agent(
148
- api_key=api_key,
149
- system_prompt=instructions,
150
- callbacks={"text": text_callback},
151
- verbose=verbose,
152
- max_tokens=8126,
153
- max_tool_rounds=100,
154
- config_params=config_params,
155
- # Don't pass any tools, including text_editor_tool and bash_tool
156
- )
157
- else:
158
- # Normal mode with tools
159
- agent = claudine.Agent(
160
- api_key=api_key,
161
- system_prompt=instructions,
162
- callbacks={"text": text_callback},
163
- text_editor_tool=str_replace_editor,
164
- bash_tool=bash_tool,
165
- tools=tools_list,
166
- verbose=verbose,
167
- max_tokens=8126,
168
- max_tool_rounds=100,
169
- config_params=config_params,
170
- )
171
-
172
- return agent
janito/cli/agent/query.py DELETED
@@ -1,108 +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
-
15
- console = Console()
16
-
17
- def handle_query(query: str, temperature: float, verbose: bool, show_tokens: bool, continue_conversation: Optional[str] = None, system_instructions: Optional[str] = None) -> None:
18
- """
19
- Handle a query by initializing the agent and sending the query.
20
-
21
- Args:
22
- query: The query to send to the agent
23
- temperature: Temperature value for model generation
24
- verbose: Whether to enable verbose mode
25
- show_tokens: Whether to show detailed token usage
26
- continue_conversation: Optional message ID to continue a specific conversation
27
- system_instructions: Optional custom system instructions to use instead of loading from file
28
- """
29
- # Initialize the agent
30
- agent = initialize_agent(temperature, verbose, system_instructions)
31
-
32
- # Load previous messages if continuing conversation
33
- if continue_conversation is not None:
34
- # If continue_conversation is an empty string (from flag with no value), use default behavior
35
- message_id = None if continue_conversation == "" else continue_conversation
36
- messages = load_messages(message_id)
37
- if messages:
38
- agent.set_messages(messages)
39
- if message_id:
40
- console.print(f"[bold blue]🔄 Continuing conversation with ID: {message_id}[/bold blue]")
41
- else:
42
- console.print("[bold blue]🔄 Continuing most recent conversation[/bold blue]")
43
-
44
- # Provide information about the conversation being continued
45
- if verbose and len(messages) > 0:
46
- # Get the number of messages
47
- num_messages = len(messages)
48
- # Get the last user message if available
49
- last_user_message = next((msg.get("content", "") for msg in reversed(messages)
50
- if msg.get("role") == "user"), "")
51
- if last_user_message:
52
- console.print(f"[dim]📝 Last query: \"{last_user_message[:60]}{'...' if len(last_user_message) > 60 else ''}\"[/dim]")
53
- else:
54
- console.print("[bold yellow]⚠️ No previous conversation found to continue[/bold yellow]")
55
-
56
- # Send the query to the agent
57
- try:
58
- agent.query(query)
59
-
60
- # Save messages after successful query and get the message ID
61
- message_id = save_messages(agent)
62
-
63
- # Print token usage report
64
- if show_tokens:
65
- generate_token_report(agent, verbose=True, interrupted=False)
66
- else:
67
- # Show basic token usage
68
- generate_token_report(agent, verbose=False, interrupted=False)
69
-
70
- # Print tool usage statistics
71
- print_usage_stats()
72
-
73
-
74
-
75
- except KeyboardInterrupt:
76
- # Handle Ctrl+C by printing token and tool usage information
77
- console.print("\n[bold yellow]⚠️ Query interrupted by user (Ctrl+C)[/bold yellow]")
78
-
79
- # Save messages even if interrupted
80
- message_id = save_messages(agent)
81
-
82
- # Print token usage report (even if interrupted)
83
- try:
84
- if show_tokens:
85
- generate_token_report(agent, verbose=True, interrupted=True)
86
- else:
87
- # Show basic token usage
88
- generate_token_report(agent, verbose=False, interrupted=True)
89
-
90
- # Print tool usage statistics
91
- print_usage_stats()
92
-
93
-
94
- except Exception as e:
95
- console.print(f"[bold red]❌ Error generating usage report:[/bold red] {str(e)}")
96
- if verbose:
97
- console.print(traceback.format_exc())
98
-
99
- # Exit with non-zero status to indicate interruption
100
- sys.exit(130) # 130 is the standard exit code for SIGINT
101
-
102
- except anthropic.APIError as e:
103
- console.print(f"[bold red]❌ Anthropic API Error:[/bold red] {str(e)}")
104
-
105
- except Exception as e:
106
- console.print(f"[bold red]❌ Error:[/bold red] {str(e)}")
107
- if verbose:
108
- 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"]