tunacode-cli 0.0.55__py3-none-any.whl → 0.0.57__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.
Potentially problematic release.
This version of tunacode-cli might be problematic. Click here for more details.
- tunacode/cli/commands/implementations/plan.py +50 -0
- tunacode/cli/commands/registry.py +3 -0
- tunacode/cli/repl.py +327 -186
- tunacode/cli/repl_components/command_parser.py +37 -4
- tunacode/cli/repl_components/error_recovery.py +79 -1
- tunacode/cli/repl_components/output_display.py +21 -1
- tunacode/cli/repl_components/tool_executor.py +12 -0
- tunacode/configuration/defaults.py +8 -0
- tunacode/constants.py +10 -2
- tunacode/core/agents/agent_components/agent_config.py +212 -22
- tunacode/core/agents/agent_components/node_processor.py +46 -40
- tunacode/core/code_index.py +83 -29
- tunacode/core/state.py +44 -0
- tunacode/core/token_usage/usage_tracker.py +2 -2
- tunacode/core/tool_handler.py +20 -0
- tunacode/prompts/system.md +117 -490
- tunacode/services/mcp.py +29 -7
- tunacode/tools/base.py +110 -0
- tunacode/tools/bash.py +96 -1
- tunacode/tools/exit_plan_mode.py +273 -0
- tunacode/tools/glob.py +366 -33
- tunacode/tools/grep.py +226 -77
- tunacode/tools/grep_components/result_formatter.py +98 -4
- tunacode/tools/list_dir.py +132 -2
- tunacode/tools/present_plan.py +288 -0
- tunacode/tools/read_file.py +91 -0
- tunacode/tools/run_command.py +99 -0
- tunacode/tools/schema_assembler.py +167 -0
- tunacode/tools/todo.py +108 -1
- tunacode/tools/update_file.py +94 -0
- tunacode/tools/write_file.py +86 -0
- tunacode/types.py +58 -0
- tunacode/ui/input.py +14 -2
- tunacode/ui/keybindings.py +25 -4
- tunacode/ui/panels.py +53 -8
- tunacode/ui/prompt_manager.py +25 -2
- tunacode/ui/tool_ui.py +3 -2
- tunacode/utils/json_utils.py +206 -0
- tunacode/utils/message_utils.py +14 -4
- tunacode/utils/ripgrep.py +332 -9
- {tunacode_cli-0.0.55.dist-info → tunacode_cli-0.0.57.dist-info}/METADATA +8 -3
- {tunacode_cli-0.0.55.dist-info → tunacode_cli-0.0.57.dist-info}/RECORD +46 -42
- tunacode/tools/read_file_async_poc.py +0 -196
- {tunacode_cli-0.0.55.dist-info → tunacode_cli-0.0.57.dist-info}/WHEEL +0 -0
- {tunacode_cli-0.0.55.dist-info → tunacode_cli-0.0.57.dist-info}/entry_points.txt +0 -0
- {tunacode_cli-0.0.55.dist-info → tunacode_cli-0.0.57.dist-info}/licenses/LICENSE +0 -0
- {tunacode_cli-0.0.55.dist-info → tunacode_cli-0.0.57.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"""Tool for presenting a structured plan and exiting plan mode."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
import defusedxml.ElementTree as ET
|
|
8
|
+
|
|
9
|
+
from tunacode.tools.base import BaseTool
|
|
10
|
+
from tunacode.types import PlanDoc, PlanPhase, ToolResult
|
|
11
|
+
from tunacode.ui import console as ui
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PresentPlanTool(BaseTool):
|
|
17
|
+
"""Present a structured implementation plan and request user approval."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, state_manager, ui_logger=None):
|
|
20
|
+
"""Initialize the present plan tool.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
state_manager: StateManager instance for controlling plan mode state
|
|
24
|
+
ui_logger: UI logger instance for displaying messages
|
|
25
|
+
"""
|
|
26
|
+
super().__init__(ui_logger)
|
|
27
|
+
self.state_manager = state_manager
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def tool_name(self) -> str:
|
|
31
|
+
return "present_plan"
|
|
32
|
+
|
|
33
|
+
def _get_base_prompt(self) -> str:
|
|
34
|
+
"""Load and return the base prompt from XML file.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
str: The loaded prompt from XML or a default prompt
|
|
38
|
+
"""
|
|
39
|
+
try:
|
|
40
|
+
# Load prompt from XML file
|
|
41
|
+
prompt_file = Path(__file__).parent / "prompts" / "present_plan_prompt.xml"
|
|
42
|
+
if prompt_file.exists():
|
|
43
|
+
tree = ET.parse(prompt_file)
|
|
44
|
+
root = tree.getroot()
|
|
45
|
+
description = root.find("description")
|
|
46
|
+
if description is not None:
|
|
47
|
+
return description.text.strip()
|
|
48
|
+
except Exception as e:
|
|
49
|
+
logger.warning(f"Failed to load XML prompt for present_plan: {e}")
|
|
50
|
+
|
|
51
|
+
# Fallback to default prompt
|
|
52
|
+
return """Present a plan to the user for approval before execution"""
|
|
53
|
+
|
|
54
|
+
def _get_parameters_schema(self) -> Dict[str, Any]:
|
|
55
|
+
"""Get the parameters schema for present_plan tool.
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
Dict containing the JSON schema for tool parameters
|
|
59
|
+
"""
|
|
60
|
+
# Try to load from XML first
|
|
61
|
+
try:
|
|
62
|
+
prompt_file = Path(__file__).parent / "prompts" / "present_plan_prompt.xml"
|
|
63
|
+
if prompt_file.exists():
|
|
64
|
+
tree = ET.parse(prompt_file)
|
|
65
|
+
root = tree.getroot()
|
|
66
|
+
parameters = root.find("parameters")
|
|
67
|
+
if parameters is not None:
|
|
68
|
+
schema: Dict[str, Any] = {"type": "object", "properties": {}, "required": []}
|
|
69
|
+
required_fields: List[str] = []
|
|
70
|
+
|
|
71
|
+
for param in parameters.findall("parameter"):
|
|
72
|
+
name = param.get("name")
|
|
73
|
+
required = param.get("required", "false").lower() == "true"
|
|
74
|
+
param_type = param.find("type")
|
|
75
|
+
description = param.find("description")
|
|
76
|
+
|
|
77
|
+
if name and param_type is not None:
|
|
78
|
+
prop = {
|
|
79
|
+
"type": param_type.text.strip(),
|
|
80
|
+
"description": description.text.strip()
|
|
81
|
+
if description is not None
|
|
82
|
+
else "",
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
schema["properties"][name] = prop
|
|
86
|
+
if required:
|
|
87
|
+
required_fields.append(name)
|
|
88
|
+
|
|
89
|
+
schema["required"] = required_fields
|
|
90
|
+
return schema
|
|
91
|
+
except Exception as e:
|
|
92
|
+
logger.warning(f"Failed to load parameters from XML for present_plan: {e}")
|
|
93
|
+
|
|
94
|
+
# Fallback to hardcoded schema
|
|
95
|
+
return {
|
|
96
|
+
"type": "object",
|
|
97
|
+
"properties": {
|
|
98
|
+
"plan": {
|
|
99
|
+
"type": "string",
|
|
100
|
+
"description": "The plan to present to the user",
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
"required": ["plan"],
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async def _execute(
|
|
107
|
+
self,
|
|
108
|
+
title: str,
|
|
109
|
+
overview: str,
|
|
110
|
+
steps: List[str],
|
|
111
|
+
files_to_modify: List[str] = None,
|
|
112
|
+
files_to_create: List[str] = None,
|
|
113
|
+
risks: List[str] = None,
|
|
114
|
+
tests: List[str] = None,
|
|
115
|
+
rollback: Optional[str] = None,
|
|
116
|
+
open_questions: List[str] = None,
|
|
117
|
+
success_criteria: List[str] = None,
|
|
118
|
+
references: List[str] = None,
|
|
119
|
+
) -> ToolResult:
|
|
120
|
+
"""Present the implementation plan for user approval."""
|
|
121
|
+
|
|
122
|
+
# Create PlanDoc from parameters
|
|
123
|
+
plan_doc = PlanDoc(
|
|
124
|
+
title=title,
|
|
125
|
+
overview=overview,
|
|
126
|
+
steps=steps,
|
|
127
|
+
files_to_modify=files_to_modify or [],
|
|
128
|
+
files_to_create=files_to_create or [],
|
|
129
|
+
risks=risks or [],
|
|
130
|
+
tests=tests or [],
|
|
131
|
+
rollback=rollback,
|
|
132
|
+
open_questions=open_questions or [],
|
|
133
|
+
success_criteria=success_criteria or [],
|
|
134
|
+
references=references or [],
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# Validate the plan
|
|
138
|
+
is_valid, missing_sections = plan_doc.validate()
|
|
139
|
+
if not is_valid:
|
|
140
|
+
return f"❌ Plan incomplete. Missing sections: {', '.join(missing_sections)}. Continue researching and refining your plan."
|
|
141
|
+
|
|
142
|
+
# Set plan phase to PLAN_READY and store the plan
|
|
143
|
+
# The REPL will handle displaying the plan when it detects PLAN_READY phase
|
|
144
|
+
self.state_manager.session.plan_phase = PlanPhase.PLAN_READY
|
|
145
|
+
self.state_manager.session.current_plan = plan_doc
|
|
146
|
+
|
|
147
|
+
return "Plan ready for review. The system will now present it to the user for approval."
|
|
148
|
+
|
|
149
|
+
async def _present_plan(self, plan_doc: PlanDoc) -> None:
|
|
150
|
+
"""Present the plan in a formatted way."""
|
|
151
|
+
output = []
|
|
152
|
+
output.append("")
|
|
153
|
+
output.append("╭─────────────────────────────────────────────────────────╮")
|
|
154
|
+
output.append("│ 📋 IMPLEMENTATION PLAN │")
|
|
155
|
+
output.append("╰─────────────────────────────────────────────────────────╯")
|
|
156
|
+
output.append("")
|
|
157
|
+
output.append(f"🎯 **{plan_doc.title}**")
|
|
158
|
+
output.append("")
|
|
159
|
+
|
|
160
|
+
if plan_doc.overview:
|
|
161
|
+
output.append(f"📝 **Overview:** {plan_doc.overview}")
|
|
162
|
+
output.append("")
|
|
163
|
+
|
|
164
|
+
# Files section
|
|
165
|
+
if plan_doc.files_to_modify:
|
|
166
|
+
output.append("📝 **Files to Modify:**")
|
|
167
|
+
for f in plan_doc.files_to_modify:
|
|
168
|
+
output.append(f" • {f}")
|
|
169
|
+
output.append("")
|
|
170
|
+
|
|
171
|
+
if plan_doc.files_to_create:
|
|
172
|
+
output.append("📄 **Files to Create:**")
|
|
173
|
+
for f in plan_doc.files_to_create:
|
|
174
|
+
output.append(f" • {f}")
|
|
175
|
+
output.append("")
|
|
176
|
+
|
|
177
|
+
# Implementation steps
|
|
178
|
+
output.append("🔧 **Implementation Steps:**")
|
|
179
|
+
for i, step in enumerate(plan_doc.steps, 1):
|
|
180
|
+
output.append(f" {i}. {step}")
|
|
181
|
+
output.append("")
|
|
182
|
+
|
|
183
|
+
# Testing approach
|
|
184
|
+
if plan_doc.tests:
|
|
185
|
+
output.append("🧪 **Testing Approach:**")
|
|
186
|
+
for test in plan_doc.tests:
|
|
187
|
+
output.append(f" • {test}")
|
|
188
|
+
output.append("")
|
|
189
|
+
|
|
190
|
+
# Success criteria
|
|
191
|
+
if plan_doc.success_criteria:
|
|
192
|
+
output.append("✅ **Success Criteria:**")
|
|
193
|
+
for criteria in plan_doc.success_criteria:
|
|
194
|
+
output.append(f" • {criteria}")
|
|
195
|
+
output.append("")
|
|
196
|
+
|
|
197
|
+
# Risks and considerations
|
|
198
|
+
if plan_doc.risks:
|
|
199
|
+
output.append("⚠️ **Risks & Considerations:**")
|
|
200
|
+
for risk in plan_doc.risks:
|
|
201
|
+
output.append(f" • {risk}")
|
|
202
|
+
output.append("")
|
|
203
|
+
|
|
204
|
+
# Open questions
|
|
205
|
+
if plan_doc.open_questions:
|
|
206
|
+
output.append("❓ **Open Questions:**")
|
|
207
|
+
for question in plan_doc.open_questions:
|
|
208
|
+
output.append(f" • {question}")
|
|
209
|
+
output.append("")
|
|
210
|
+
|
|
211
|
+
# References
|
|
212
|
+
if plan_doc.references:
|
|
213
|
+
output.append("📚 **References:**")
|
|
214
|
+
for ref in plan_doc.references:
|
|
215
|
+
output.append(f" • {ref}")
|
|
216
|
+
output.append("")
|
|
217
|
+
|
|
218
|
+
# Rollback plan
|
|
219
|
+
if plan_doc.rollback:
|
|
220
|
+
output.append(f"🔄 **Rollback Plan:** {plan_doc.rollback}")
|
|
221
|
+
output.append("")
|
|
222
|
+
|
|
223
|
+
# Print everything at once
|
|
224
|
+
await ui.info("\n".join(output))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def create_present_plan_tool(state_manager):
|
|
228
|
+
"""
|
|
229
|
+
Factory function to create present_plan tool with the correct state manager.
|
|
230
|
+
|
|
231
|
+
Args:
|
|
232
|
+
state_manager: The StateManager instance to use
|
|
233
|
+
|
|
234
|
+
Returns:
|
|
235
|
+
Callable: The present_plan function bound to the provided state manager
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
async def present_plan(
|
|
239
|
+
title: str,
|
|
240
|
+
overview: str,
|
|
241
|
+
steps: List[str],
|
|
242
|
+
files_to_modify: List[str] = None,
|
|
243
|
+
files_to_create: List[str] = None,
|
|
244
|
+
risks: List[str] = None,
|
|
245
|
+
tests: List[str] = None,
|
|
246
|
+
rollback: Optional[str] = None,
|
|
247
|
+
open_questions: List[str] = None,
|
|
248
|
+
success_criteria: List[str] = None,
|
|
249
|
+
references: List[str] = None,
|
|
250
|
+
) -> str:
|
|
251
|
+
"""
|
|
252
|
+
Present a structured implementation plan for user approval.
|
|
253
|
+
|
|
254
|
+
This tool should ONLY be called when you have a complete, well-researched plan.
|
|
255
|
+
All required sections must be filled out before calling this tool.
|
|
256
|
+
|
|
257
|
+
Args:
|
|
258
|
+
title: Brief, descriptive title for the implementation plan
|
|
259
|
+
overview: High-level summary of what needs to be implemented and why
|
|
260
|
+
steps: Ordered list of specific implementation steps (required)
|
|
261
|
+
files_to_modify: List of existing files that need to be modified
|
|
262
|
+
files_to_create: List of new files that need to be created
|
|
263
|
+
risks: Potential risks, challenges, or considerations
|
|
264
|
+
tests: Testing approach and test cases to validate implementation
|
|
265
|
+
rollback: Plan for reverting changes if needed
|
|
266
|
+
open_questions: Any remaining questions or uncertainties
|
|
267
|
+
success_criteria: Specific criteria for considering the task complete
|
|
268
|
+
references: External resources, documentation, or research sources
|
|
269
|
+
|
|
270
|
+
Returns:
|
|
271
|
+
str: Status message about plan presentation
|
|
272
|
+
"""
|
|
273
|
+
tool = PresentPlanTool(state_manager=state_manager)
|
|
274
|
+
return await tool._execute(
|
|
275
|
+
title=title,
|
|
276
|
+
overview=overview,
|
|
277
|
+
steps=steps,
|
|
278
|
+
files_to_modify=files_to_modify,
|
|
279
|
+
files_to_create=files_to_create,
|
|
280
|
+
risks=risks,
|
|
281
|
+
tests=tests,
|
|
282
|
+
rollback=rollback,
|
|
283
|
+
open_questions=open_questions,
|
|
284
|
+
success_criteria=success_criteria,
|
|
285
|
+
references=references,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
return present_plan
|
tunacode/tools/read_file.py
CHANGED
|
@@ -6,7 +6,13 @@ Provides safe file reading with size limits and proper error handling.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
import asyncio
|
|
9
|
+
import logging
|
|
9
10
|
import os
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Dict, List
|
|
14
|
+
|
|
15
|
+
import defusedxml.ElementTree as ET
|
|
10
16
|
|
|
11
17
|
from tunacode.constants import (
|
|
12
18
|
ERROR_FILE_DECODE,
|
|
@@ -20,6 +26,8 @@ from tunacode.exceptions import ToolExecutionError
|
|
|
20
26
|
from tunacode.tools.base import FileBasedTool
|
|
21
27
|
from tunacode.types import ToolResult
|
|
22
28
|
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
23
31
|
|
|
24
32
|
class ReadFileTool(FileBasedTool):
|
|
25
33
|
"""Tool for reading file contents."""
|
|
@@ -28,6 +36,89 @@ class ReadFileTool(FileBasedTool):
|
|
|
28
36
|
def tool_name(self) -> str:
|
|
29
37
|
return "Read"
|
|
30
38
|
|
|
39
|
+
@lru_cache(maxsize=1)
|
|
40
|
+
def _get_base_prompt(self) -> str:
|
|
41
|
+
"""Load and return the base prompt from XML file.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
str: The loaded prompt from XML or a default prompt
|
|
45
|
+
"""
|
|
46
|
+
try:
|
|
47
|
+
# Load prompt from XML file
|
|
48
|
+
prompt_file = Path(__file__).parent / "prompts" / "read_file_prompt.xml"
|
|
49
|
+
if prompt_file.exists():
|
|
50
|
+
tree = ET.parse(prompt_file)
|
|
51
|
+
root = tree.getroot()
|
|
52
|
+
description = root.find("description")
|
|
53
|
+
if description is not None:
|
|
54
|
+
return description.text.strip()
|
|
55
|
+
except Exception as e:
|
|
56
|
+
logger.warning(f"Failed to load XML prompt for read_file: {e}")
|
|
57
|
+
|
|
58
|
+
# Fallback to default prompt
|
|
59
|
+
return """Reads a file from the local filesystem"""
|
|
60
|
+
|
|
61
|
+
@lru_cache(maxsize=1)
|
|
62
|
+
def _get_parameters_schema(self) -> Dict[str, Any]:
|
|
63
|
+
"""Get the parameters schema for read_file tool.
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
Dict containing the JSON schema for tool parameters
|
|
67
|
+
"""
|
|
68
|
+
# Try to load from XML first
|
|
69
|
+
try:
|
|
70
|
+
prompt_file = Path(__file__).parent / "prompts" / "read_file_prompt.xml"
|
|
71
|
+
if prompt_file.exists():
|
|
72
|
+
tree = ET.parse(prompt_file)
|
|
73
|
+
root = tree.getroot()
|
|
74
|
+
parameters = root.find("parameters")
|
|
75
|
+
if parameters is not None:
|
|
76
|
+
schema: Dict[str, Any] = {"type": "object", "properties": {}, "required": []}
|
|
77
|
+
required_fields: List[str] = []
|
|
78
|
+
|
|
79
|
+
for param in parameters.findall("parameter"):
|
|
80
|
+
name = param.get("name")
|
|
81
|
+
required = param.get("required", "false").lower() == "true"
|
|
82
|
+
param_type = param.find("type")
|
|
83
|
+
description = param.find("description")
|
|
84
|
+
|
|
85
|
+
if name and param_type is not None:
|
|
86
|
+
prop = {
|
|
87
|
+
"type": param_type.text.strip(),
|
|
88
|
+
"description": description.text.strip()
|
|
89
|
+
if description is not None
|
|
90
|
+
else "",
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
schema["properties"][name] = prop
|
|
94
|
+
if required:
|
|
95
|
+
required_fields.append(name)
|
|
96
|
+
|
|
97
|
+
schema["required"] = required_fields
|
|
98
|
+
return schema
|
|
99
|
+
except Exception as e:
|
|
100
|
+
logger.warning(f"Failed to load parameters from XML for read_file: {e}")
|
|
101
|
+
|
|
102
|
+
# Fallback to hardcoded schema
|
|
103
|
+
return {
|
|
104
|
+
"type": "object",
|
|
105
|
+
"properties": {
|
|
106
|
+
"file_path": {
|
|
107
|
+
"type": "string",
|
|
108
|
+
"description": "The absolute path to the file to read",
|
|
109
|
+
},
|
|
110
|
+
"offset": {
|
|
111
|
+
"type": "number",
|
|
112
|
+
"description": "The line number to start reading from",
|
|
113
|
+
},
|
|
114
|
+
"limit": {
|
|
115
|
+
"type": "number",
|
|
116
|
+
"description": "The number of lines to read",
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
"required": ["file_path"],
|
|
120
|
+
}
|
|
121
|
+
|
|
31
122
|
async def _execute(self, filepath: str) -> ToolResult:
|
|
32
123
|
"""Read the contents of a file.
|
|
33
124
|
|
tunacode/tools/run_command.py
CHANGED
|
@@ -5,7 +5,13 @@ Command execution tool for agent operations in the TunaCode application.
|
|
|
5
5
|
Provides controlled shell command execution with output capture and truncation.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
+
import logging
|
|
8
9
|
import subprocess
|
|
10
|
+
from functools import lru_cache
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Dict, List
|
|
13
|
+
|
|
14
|
+
import defusedxml.ElementTree as ET
|
|
9
15
|
|
|
10
16
|
from tunacode.constants import (
|
|
11
17
|
CMD_OUTPUT_FORMAT,
|
|
@@ -23,10 +29,103 @@ from tunacode.tools.base import BaseTool
|
|
|
23
29
|
from tunacode.types import ToolResult
|
|
24
30
|
from tunacode.utils.security import CommandSecurityError, safe_subprocess_popen
|
|
25
31
|
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
26
34
|
|
|
27
35
|
class RunCommandTool(BaseTool):
|
|
28
36
|
"""Tool for running shell commands."""
|
|
29
37
|
|
|
38
|
+
@lru_cache(maxsize=1)
|
|
39
|
+
def _get_base_prompt(self) -> str:
|
|
40
|
+
"""Load and return the base prompt from XML file.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
str: The loaded prompt from XML or a default prompt
|
|
44
|
+
"""
|
|
45
|
+
try:
|
|
46
|
+
# Load prompt from XML file
|
|
47
|
+
prompt_file = Path(__file__).parent / "prompts" / "run_command_prompt.xml"
|
|
48
|
+
if prompt_file.exists():
|
|
49
|
+
tree = ET.parse(prompt_file)
|
|
50
|
+
root = tree.getroot()
|
|
51
|
+
description = root.find("description")
|
|
52
|
+
if description is not None:
|
|
53
|
+
return description.text.strip()
|
|
54
|
+
except Exception as e:
|
|
55
|
+
logger.warning(f"Failed to load XML prompt for run_command: {e}")
|
|
56
|
+
|
|
57
|
+
# Fallback to default prompt
|
|
58
|
+
return """Executes system commands with enhanced control and monitoring capabilities"""
|
|
59
|
+
|
|
60
|
+
@lru_cache(maxsize=1)
|
|
61
|
+
def _get_parameters_schema(self) -> Dict[str, Any]:
|
|
62
|
+
"""Get the parameters schema for run_command tool.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
Dict containing the JSON schema for tool parameters
|
|
66
|
+
"""
|
|
67
|
+
# Try to load from XML first
|
|
68
|
+
try:
|
|
69
|
+
prompt_file = Path(__file__).parent / "prompts" / "run_command_prompt.xml"
|
|
70
|
+
if prompt_file.exists():
|
|
71
|
+
tree = ET.parse(prompt_file)
|
|
72
|
+
root = tree.getroot()
|
|
73
|
+
parameters = root.find("parameters")
|
|
74
|
+
if parameters is not None:
|
|
75
|
+
schema: Dict[str, Any] = {"type": "object", "properties": {}, "required": []}
|
|
76
|
+
required_fields: List[str] = []
|
|
77
|
+
|
|
78
|
+
for param in parameters.findall("parameter"):
|
|
79
|
+
name = param.get("name")
|
|
80
|
+
required = param.get("required", "false").lower() == "true"
|
|
81
|
+
param_type = param.find("type")
|
|
82
|
+
description = param.find("description")
|
|
83
|
+
|
|
84
|
+
if name and param_type is not None:
|
|
85
|
+
prop = {
|
|
86
|
+
"type": param_type.text.strip(),
|
|
87
|
+
"description": description.text.strip()
|
|
88
|
+
if description is not None
|
|
89
|
+
else "",
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
schema["properties"][name] = prop
|
|
93
|
+
if required:
|
|
94
|
+
required_fields.append(name)
|
|
95
|
+
|
|
96
|
+
schema["required"] = required_fields
|
|
97
|
+
return schema
|
|
98
|
+
except Exception as e:
|
|
99
|
+
logger.warning(f"Failed to load parameters from XML for run_command: {e}")
|
|
100
|
+
|
|
101
|
+
# Fallback to hardcoded schema
|
|
102
|
+
return {
|
|
103
|
+
"type": "object",
|
|
104
|
+
"properties": {
|
|
105
|
+
"command": {
|
|
106
|
+
"type": "string",
|
|
107
|
+
"description": "The command to execute",
|
|
108
|
+
},
|
|
109
|
+
"cwd": {
|
|
110
|
+
"type": "string",
|
|
111
|
+
"description": "Working directory for the command",
|
|
112
|
+
},
|
|
113
|
+
"env": {
|
|
114
|
+
"type": "object",
|
|
115
|
+
"description": "Additional environment variables",
|
|
116
|
+
},
|
|
117
|
+
"timeout": {
|
|
118
|
+
"type": "integer",
|
|
119
|
+
"description": "Command timeout in seconds",
|
|
120
|
+
},
|
|
121
|
+
"capture_output": {
|
|
122
|
+
"type": "boolean",
|
|
123
|
+
"description": "Whether to capture stdout/stderr",
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
"required": ["command"],
|
|
127
|
+
}
|
|
128
|
+
|
|
30
129
|
@property
|
|
31
130
|
def tool_name(self) -> str:
|
|
32
131
|
return "Shell"
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Tool Schema Assembler for API Integration.
|
|
2
|
+
|
|
3
|
+
This module handles the assembly of tool schemas for API calls,
|
|
4
|
+
converting tool prompts and parameters into OpenAI-compatible function schemas.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, List, Optional, Type
|
|
8
|
+
|
|
9
|
+
from tunacode.tools.base import BaseTool
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ToolSchemaAssembler:
|
|
13
|
+
"""Assembles tool schemas for API integration."""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
"""Initialize the schema assembler."""
|
|
17
|
+
self._context: Dict[str, Any] = {}
|
|
18
|
+
self._tool_instances: Dict[str, BaseTool] = {}
|
|
19
|
+
|
|
20
|
+
def set_context(self, context: Dict[str, Any]) -> None:
|
|
21
|
+
"""Set the context for all tools.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
context: Context including model, permissions, environment, etc.
|
|
25
|
+
"""
|
|
26
|
+
self._context = context
|
|
27
|
+
# Update context for all registered tools
|
|
28
|
+
for tool in self._tool_instances.values():
|
|
29
|
+
tool._context.update(context)
|
|
30
|
+
|
|
31
|
+
def register_tool(self, tool: BaseTool) -> None:
|
|
32
|
+
"""Register a tool instance.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
tool: The tool instance to register
|
|
36
|
+
"""
|
|
37
|
+
self._tool_instances[tool.tool_name] = tool
|
|
38
|
+
# Apply current context to the new tool
|
|
39
|
+
if self._context:
|
|
40
|
+
tool._context.update(self._context)
|
|
41
|
+
|
|
42
|
+
def register_tool_class(self, tool_class: Type[BaseTool], *args, **kwargs) -> None:
|
|
43
|
+
"""Register a tool by instantiating its class.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
tool_class: The tool class to instantiate
|
|
47
|
+
*args, **kwargs: Arguments for tool instantiation
|
|
48
|
+
"""
|
|
49
|
+
tool = tool_class(*args, **kwargs)
|
|
50
|
+
self.register_tool(tool)
|
|
51
|
+
|
|
52
|
+
def get_tool_schema(self, tool_name: str) -> Optional[Dict[str, Any]]:
|
|
53
|
+
"""Get the schema for a specific tool.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
tool_name: Name of the tool
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Tool schema in OpenAI function format, or None if not found
|
|
60
|
+
"""
|
|
61
|
+
tool = self._tool_instances.get(tool_name)
|
|
62
|
+
if not tool:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
return tool.get_tool_schema()
|
|
66
|
+
|
|
67
|
+
def get_all_schemas(self) -> List[Dict[str, Any]]:
|
|
68
|
+
"""Get schemas for all registered tools.
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
List of tool schemas in OpenAI function format
|
|
72
|
+
"""
|
|
73
|
+
schemas = []
|
|
74
|
+
for tool in self._tool_instances.values():
|
|
75
|
+
schema = tool.get_tool_schema()
|
|
76
|
+
if schema:
|
|
77
|
+
schemas.append(schema)
|
|
78
|
+
return schemas
|
|
79
|
+
|
|
80
|
+
def get_schemas_for_model(self, model: str) -> List[Dict[str, Any]]:
|
|
81
|
+
"""Get schemas optimized for a specific model.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
model: The model identifier (e.g., 'claude-3', 'gpt-4')
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
List of tool schemas optimized for the model
|
|
88
|
+
"""
|
|
89
|
+
# Update context with model
|
|
90
|
+
self.set_context({"model": model, **self._context})
|
|
91
|
+
|
|
92
|
+
# Get all schemas with model-specific prompts
|
|
93
|
+
return self.get_all_schemas()
|
|
94
|
+
|
|
95
|
+
def get_schemas_with_permissions(self, permissions: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
96
|
+
"""Get schemas filtered by permissions.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
permissions: Permission settings
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
List of tool schemas filtered by permissions
|
|
103
|
+
"""
|
|
104
|
+
# Update context with permissions
|
|
105
|
+
self.set_context({"permissions": permissions, **self._context})
|
|
106
|
+
|
|
107
|
+
# Filter tools based on permissions
|
|
108
|
+
schemas = []
|
|
109
|
+
for tool_name, tool in self._tool_instances.items():
|
|
110
|
+
# Check if tool is allowed based on permissions
|
|
111
|
+
if self._is_tool_allowed(tool_name, permissions):
|
|
112
|
+
schema = tool.get_tool_schema()
|
|
113
|
+
if schema:
|
|
114
|
+
schemas.append(schema)
|
|
115
|
+
|
|
116
|
+
return schemas
|
|
117
|
+
|
|
118
|
+
def _is_tool_allowed(self, tool_name: str, permissions: Dict[str, Any]) -> bool:
|
|
119
|
+
"""Check if a tool is allowed based on permissions.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
tool_name: Name of the tool
|
|
123
|
+
permissions: Permission settings
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
True if the tool is allowed
|
|
127
|
+
"""
|
|
128
|
+
# Default implementation - can be extended
|
|
129
|
+
if permissions.get("restricted", False):
|
|
130
|
+
# In restricted mode, only allow safe tools
|
|
131
|
+
safe_tools = ["read_file", "list_dir", "grep", "glob"]
|
|
132
|
+
return tool_name in safe_tools
|
|
133
|
+
|
|
134
|
+
# Check for explicit tool permissions
|
|
135
|
+
allowed_tools = permissions.get("allowed_tools")
|
|
136
|
+
if allowed_tools:
|
|
137
|
+
return tool_name in allowed_tools
|
|
138
|
+
|
|
139
|
+
blocked_tools = permissions.get("blocked_tools", [])
|
|
140
|
+
return tool_name not in blocked_tools
|
|
141
|
+
|
|
142
|
+
def refresh_prompts(self) -> None:
|
|
143
|
+
"""Refresh prompts for all tools based on current context."""
|
|
144
|
+
for tool in self._tool_instances.values():
|
|
145
|
+
# Clear prompt cache to force regeneration
|
|
146
|
+
tool._prompt_cache = None
|
|
147
|
+
|
|
148
|
+
def update_environment(self, env_vars: Dict[str, Any]) -> None:
|
|
149
|
+
"""Update environment variables in context.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
env_vars: Environment variables to update
|
|
153
|
+
"""
|
|
154
|
+
current_env = self._context.get("environment", {})
|
|
155
|
+
current_env.update(env_vars)
|
|
156
|
+
self.set_context({"environment": current_env, **self._context})
|
|
157
|
+
|
|
158
|
+
def get_tool_by_name(self, tool_name: str) -> Optional[BaseTool]:
|
|
159
|
+
"""Get a tool instance by name.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
tool_name: Name of the tool
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
Tool instance or None if not found
|
|
166
|
+
"""
|
|
167
|
+
return self._tool_instances.get(tool_name)
|