tunacode-cli 0.0.40__py3-none-any.whl → 0.0.42__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.

Files changed (50) hide show
  1. tunacode/cli/commands/__init__.py +2 -0
  2. tunacode/cli/commands/implementations/__init__.py +3 -0
  3. tunacode/cli/commands/implementations/debug.py +1 -1
  4. tunacode/cli/commands/implementations/todo.py +217 -0
  5. tunacode/cli/commands/registry.py +2 -0
  6. tunacode/cli/main.py +12 -5
  7. tunacode/cli/repl.py +205 -136
  8. tunacode/configuration/defaults.py +2 -0
  9. tunacode/configuration/models.py +6 -0
  10. tunacode/constants.py +27 -3
  11. tunacode/context.py +7 -3
  12. tunacode/core/agents/dspy_integration.py +223 -0
  13. tunacode/core/agents/dspy_tunacode.py +458 -0
  14. tunacode/core/agents/main.py +182 -12
  15. tunacode/core/agents/utils.py +54 -6
  16. tunacode/core/recursive/__init__.py +18 -0
  17. tunacode/core/recursive/aggregator.py +467 -0
  18. tunacode/core/recursive/budget.py +414 -0
  19. tunacode/core/recursive/decomposer.py +398 -0
  20. tunacode/core/recursive/executor.py +467 -0
  21. tunacode/core/recursive/hierarchy.py +487 -0
  22. tunacode/core/setup/config_setup.py +5 -0
  23. tunacode/core/state.py +91 -1
  24. tunacode/core/token_usage/api_response_parser.py +44 -0
  25. tunacode/core/token_usage/cost_calculator.py +58 -0
  26. tunacode/core/token_usage/usage_tracker.py +98 -0
  27. tunacode/exceptions.py +23 -0
  28. tunacode/prompts/dspy_task_planning.md +45 -0
  29. tunacode/prompts/dspy_tool_selection.md +58 -0
  30. tunacode/prompts/system.md +69 -5
  31. tunacode/tools/todo.py +343 -0
  32. tunacode/types.py +20 -1
  33. tunacode/ui/console.py +1 -1
  34. tunacode/ui/input.py +1 -1
  35. tunacode/ui/output.py +38 -1
  36. tunacode/ui/panels.py +4 -1
  37. tunacode/ui/recursive_progress.py +380 -0
  38. tunacode/ui/tool_ui.py +24 -6
  39. tunacode/ui/utils.py +1 -1
  40. tunacode/utils/message_utils.py +17 -0
  41. tunacode/utils/retry.py +163 -0
  42. tunacode/utils/token_counter.py +78 -8
  43. {tunacode_cli-0.0.40.dist-info → tunacode_cli-0.0.42.dist-info}/METADATA +4 -1
  44. {tunacode_cli-0.0.40.dist-info → tunacode_cli-0.0.42.dist-info}/RECORD +48 -32
  45. tunacode/cli/textual_app.py +0 -420
  46. tunacode/cli/textual_bridge.py +0 -161
  47. {tunacode_cli-0.0.40.dist-info → tunacode_cli-0.0.42.dist-info}/WHEEL +0 -0
  48. {tunacode_cli-0.0.40.dist-info → tunacode_cli-0.0.42.dist-info}/entry_points.txt +0 -0
  49. {tunacode_cli-0.0.40.dist-info → tunacode_cli-0.0.42.dist-info}/licenses/LICENSE +0 -0
  50. {tunacode_cli-0.0.40.dist-info → tunacode_cli-0.0.42.dist-info}/top_level.txt +0 -0
tunacode/context.py CHANGED
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import subprocess
2
3
  from pathlib import Path
3
4
  from typing import Dict, List
@@ -5,6 +6,8 @@ from typing import Dict, List
5
6
  from tunacode.utils.ripgrep import ripgrep
6
7
  from tunacode.utils.system import list_cwd
7
8
 
9
+ logger = logging.getLogger(__name__)
10
+
8
11
 
9
12
  async def get_git_status() -> Dict[str, object]:
10
13
  """Return git branch and dirty state information."""
@@ -29,7 +32,8 @@ async def get_git_status() -> Dict[str, object]:
29
32
  behind = int(part.split("behind")[1].strip().strip(" ]"))
30
33
  dirty = any(line for line in lines[1:])
31
34
  return {"branch": branch, "ahead": ahead, "behind": behind, "dirty": dirty}
32
- except Exception:
35
+ except Exception as e:
36
+ logger.warning(f"Failed to get git status: {e}")
33
37
  return {}
34
38
 
35
39
 
@@ -54,8 +58,8 @@ async def get_code_style() -> str:
54
58
  if file.exists():
55
59
  try:
56
60
  parts.append(file.read_text(encoding="utf-8"))
57
- except Exception:
58
- pass
61
+ except Exception as e:
62
+ logger.debug(f"Failed to read TUNACODE.md at {file}: {e}")
59
63
  if current == current.parent:
60
64
  break
61
65
  current = current.parent
@@ -0,0 +1,223 @@
1
+ """DSPy Integration for TunaCode - Enhanced Tool Selection and Task Planning.
2
+
3
+ This module integrates DSPy's optimized prompts and tool selection logic
4
+ into TunaCode's agent system for 3x performance improvements.
5
+ """
6
+
7
+ import logging
8
+ import os
9
+ import re
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ from tunacode.core.state import StateManager
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class DSPyIntegration:
19
+ """Integrates DSPy optimization into TunaCode's agent system."""
20
+
21
+ def __init__(self, state_manager: StateManager):
22
+ self.state_manager = state_manager
23
+ self._dspy_agent = None
24
+ self._tool_selection_prompt = None
25
+ self._task_planning_prompt = None
26
+ self._load_prompts()
27
+
28
+ def _load_prompts(self):
29
+ """Load DSPy-optimized prompts from files."""
30
+ prompts_dir = Path(__file__).parent.parent.parent / "prompts"
31
+
32
+ try:
33
+ # Load tool selection prompt
34
+ tool_selection_path = prompts_dir / "dspy_tool_selection.md"
35
+ if tool_selection_path.exists():
36
+ self._tool_selection_prompt = tool_selection_path.read_text(encoding="utf-8")
37
+ logger.debug("Loaded DSPy tool selection prompt")
38
+
39
+ # Load task planning prompt
40
+ task_planning_path = prompts_dir / "dspy_task_planning.md"
41
+ if task_planning_path.exists():
42
+ self._task_planning_prompt = task_planning_path.read_text(encoding="utf-8")
43
+ logger.debug("Loaded DSPy task planning prompt")
44
+ except Exception as e:
45
+ logger.error(f"Failed to load DSPy prompts: {e}")
46
+
47
+ def get_dspy_agent(self, api_key: Optional[str] = None):
48
+ """Get or create the DSPy agent instance."""
49
+ if self._dspy_agent is None:
50
+ try:
51
+ # Import DSPy components
52
+ from tunacode.core.agents.dspy_tunacode import create_optimized_agent
53
+
54
+ # Use API key from environment or config
55
+ if not api_key:
56
+ api_key = os.getenv(
57
+ "OPENROUTER_API_KEY"
58
+ ) or self.state_manager.session.user_config.get("env", {}).get(
59
+ "OPENROUTER_API_KEY"
60
+ )
61
+
62
+ if api_key:
63
+ self._dspy_agent = create_optimized_agent(api_key)
64
+ logger.info("DSPy agent initialized successfully")
65
+ else:
66
+ logger.warning("No OpenRouter API key found for DSPy optimization")
67
+ except Exception as e:
68
+ logger.error(f"Failed to initialize DSPy agent: {e}")
69
+
70
+ return self._dspy_agent
71
+
72
+ def enhance_system_prompt(self, base_prompt: str) -> str:
73
+ """Enhance the system prompt with DSPy optimizations."""
74
+ if not self._tool_selection_prompt:
75
+ return base_prompt
76
+
77
+ # Extract the learned patterns from DSPy prompts
78
+ enhanced_sections = []
79
+
80
+ # Add DSPy tool selection insights
81
+ enhanced_sections.append("\n\n# DSPy-Optimized Tool Selection Patterns\n")
82
+ enhanced_sections.append("**Based on learned optimization patterns:**\n")
83
+ enhanced_sections.append("- Always batch 3-4 read-only tools for parallel execution")
84
+ enhanced_sections.append("- Group grep, list_dir, glob, read_file operations together")
85
+ enhanced_sections.append("- Execute write/modify operations sequentially")
86
+ enhanced_sections.append("- Use Chain of Thought reasoning for tool selection\n")
87
+
88
+ # Add specific examples from DSPy prompt
89
+ if "Example" in self._tool_selection_prompt:
90
+ enhanced_sections.append("\n## Optimal Tool Batching Examples:\n")
91
+ # Extract examples section
92
+ examples_match = re.search(
93
+ r"### Example.*?(?=###|\Z)", self._tool_selection_prompt, re.DOTALL
94
+ )
95
+ if examples_match:
96
+ enhanced_sections.append(examples_match.group(0))
97
+
98
+ return base_prompt + "".join(enhanced_sections)
99
+
100
+ def should_use_task_planner(self, user_request: str) -> bool:
101
+ """Determine if the request is complex enough for task planning."""
102
+ complex_indicators = [
103
+ "implement",
104
+ "create",
105
+ "build",
106
+ "refactor",
107
+ "add feature",
108
+ "fix all",
109
+ "update multiple",
110
+ "migrate",
111
+ "integrate",
112
+ "debug",
113
+ "optimize performance",
114
+ "authentication",
115
+ "setup",
116
+ ]
117
+
118
+ request_lower = user_request.lower()
119
+
120
+ # Check for multiple files
121
+ file_pattern = r"\b\w+\.\w+\b"
122
+ files_mentioned = len(re.findall(file_pattern, user_request)) > 2
123
+
124
+ # Check for complex keywords
125
+ has_complex_keyword = any(indicator in request_lower for indicator in complex_indicators)
126
+
127
+ # Check for multiple operations
128
+ operation_words = ["and", "then", "also", "after", "before", "plus"]
129
+ has_multiple_ops = sum(1 for word in operation_words if word in request_lower) >= 2
130
+
131
+ return files_mentioned or has_complex_keyword or has_multiple_ops
132
+
133
+ def optimize_tool_selection(
134
+ self, user_request: str, tools_to_execute: List[Dict[str, Any]]
135
+ ) -> List[List[Dict[str, Any]]]:
136
+ """Optimize tool selection using DSPy patterns.
137
+
138
+ Returns tool calls organized in optimal batches for parallel execution.
139
+ """
140
+ if not tools_to_execute:
141
+ return []
142
+
143
+ # Try to use DSPy agent if available
144
+ dspy_agent = self.get_dspy_agent()
145
+ if dspy_agent:
146
+ try:
147
+ result = dspy_agent(user_request, self.state_manager.session.cwd or ".")
148
+ if hasattr(result, "tool_batches") and result.tool_batches:
149
+ return result.tool_batches
150
+ except Exception as e:
151
+ logger.debug(f"DSPy optimization failed, using fallback: {e}")
152
+
153
+ # Fallback: Apply DSPy-learned patterns manually
154
+ return self._apply_dspy_patterns(tools_to_execute)
155
+
156
+ def _apply_dspy_patterns(self, tools: List[Dict[str, Any]]) -> List[List[Dict[str, Any]]]:
157
+ """Apply DSPy-learned batching patterns manually."""
158
+ from tunacode.constants import READ_ONLY_TOOLS
159
+
160
+ batches = []
161
+ current_batch = []
162
+
163
+ for tool in tools:
164
+ tool_name = tool.get("tool", "")
165
+
166
+ if tool_name in READ_ONLY_TOOLS:
167
+ current_batch.append(tool)
168
+ # Optimal batch size is 3-4 tools
169
+ if len(current_batch) >= 4:
170
+ batches.append(current_batch)
171
+ current_batch = []
172
+ else:
173
+ # Flush current batch if any
174
+ if current_batch:
175
+ batches.append(current_batch)
176
+ current_batch = []
177
+ # Add write/execute tool as single batch
178
+ batches.append([tool])
179
+
180
+ # Add remaining tools
181
+ if current_batch:
182
+ batches.append(current_batch)
183
+
184
+ return batches
185
+
186
+ def get_task_breakdown(self, complex_request: str) -> Optional[Dict[str, Any]]:
187
+ """Get task breakdown for complex requests using DSPy."""
188
+ dspy_agent = self.get_dspy_agent()
189
+ if not dspy_agent:
190
+ return None
191
+
192
+ try:
193
+ result = dspy_agent(complex_request, self.state_manager.session.cwd or ".")
194
+ if result.get("is_complex") and result.get("subtasks"):
195
+ return {
196
+ "subtasks": result["subtasks"],
197
+ "total_tool_calls": result.get("total_tool_calls", 0),
198
+ "requires_todo": result.get("requires_todo", False),
199
+ "parallelization_opportunities": result.get("parallelization_opportunities", 0),
200
+ }
201
+ except Exception as e:
202
+ logger.error(f"Failed to get task breakdown: {e}")
203
+
204
+ return None
205
+
206
+ def format_chain_of_thought(self, request: str, tools: List[str]) -> str:
207
+ """Format a Chain of Thought reasoning for tool selection."""
208
+ reasoning = f"Let's think step by step about '{request}':\n"
209
+
210
+ if "search" in request.lower() or "find" in request.lower():
211
+ reasoning += "1. This requires searching for information\n"
212
+ reasoning += "2. I'll use grep for content search and glob for file patterns\n"
213
+ reasoning += "3. These read-only tools can be executed in parallel\n"
214
+ elif "read" in request.lower() or "show" in request.lower():
215
+ reasoning += "1. This requires reading file contents\n"
216
+ reasoning += "2. I'll batch multiple read_file operations together\n"
217
+ reasoning += "3. All reads can happen in parallel for speed\n"
218
+ elif "fix" in request.lower() or "update" in request.lower():
219
+ reasoning += "1. First, I need to understand the current state\n"
220
+ reasoning += "2. I'll search and read relevant files in parallel\n"
221
+ reasoning += "3. Then make modifications sequentially for safety\n"
222
+
223
+ return reasoning