ripperdoc 0.2.3__py3-none-any.whl → 0.2.4__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.
- ripperdoc/__init__.py +1 -1
- ripperdoc/cli/commands/context_cmd.py +3 -3
- ripperdoc/cli/ui/rich_ui.py +35 -2
- ripperdoc/core/agents.py +160 -0
- ripperdoc/core/default_tools.py +6 -0
- ripperdoc/core/providers/__init__.py +31 -15
- ripperdoc/core/providers/anthropic.py +15 -4
- ripperdoc/core/providers/base.py +63 -14
- ripperdoc/core/providers/gemini.py +415 -91
- ripperdoc/core/providers/openai.py +125 -14
- ripperdoc/core/query.py +7 -1
- ripperdoc/core/query_utils.py +1 -1
- ripperdoc/core/system_prompt.py +67 -61
- ripperdoc/core/tool.py +7 -0
- ripperdoc/tools/ask_user_question_tool.py +433 -0
- ripperdoc/tools/background_shell.py +70 -20
- ripperdoc/tools/enter_plan_mode_tool.py +223 -0
- ripperdoc/tools/exit_plan_mode_tool.py +150 -0
- ripperdoc/tools/mcp_tools.py +113 -4
- ripperdoc/tools/task_tool.py +88 -5
- ripperdoc/utils/mcp.py +49 -10
- ripperdoc/utils/message_compaction.py +3 -5
- ripperdoc/utils/token_estimation.py +33 -0
- {ripperdoc-0.2.3.dist-info → ripperdoc-0.2.4.dist-info}/METADATA +3 -1
- {ripperdoc-0.2.3.dist-info → ripperdoc-0.2.4.dist-info}/RECORD +29 -25
- {ripperdoc-0.2.3.dist-info → ripperdoc-0.2.4.dist-info}/WHEEL +0 -0
- {ripperdoc-0.2.3.dist-info → ripperdoc-0.2.4.dist-info}/entry_points.txt +0 -0
- {ripperdoc-0.2.3.dist-info → ripperdoc-0.2.4.dist-info}/licenses/LICENSE +0 -0
- {ripperdoc-0.2.3.dist-info → ripperdoc-0.2.4.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Enter plan mode tool for complex task planning.
|
|
2
|
+
|
|
3
|
+
This tool allows the AI to request entering plan mode for complex tasks
|
|
4
|
+
that require careful exploration and design before implementation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from textwrap import dedent
|
|
10
|
+
from typing import AsyncGenerator, Optional
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel
|
|
13
|
+
|
|
14
|
+
from ripperdoc.core.tool import (
|
|
15
|
+
Tool,
|
|
16
|
+
ToolOutput,
|
|
17
|
+
ToolResult,
|
|
18
|
+
ToolUseContext,
|
|
19
|
+
ValidationResult,
|
|
20
|
+
)
|
|
21
|
+
from ripperdoc.utils.log import get_logger
|
|
22
|
+
|
|
23
|
+
logger = get_logger()
|
|
24
|
+
|
|
25
|
+
TOOL_NAME = "EnterPlanMode"
|
|
26
|
+
ASK_USER_QUESTION_TOOL = "AskUserQuestion"
|
|
27
|
+
|
|
28
|
+
ENTER_PLAN_MODE_PROMPT = dedent(
|
|
29
|
+
"""\
|
|
30
|
+
Use this tool when you encounter a complex task that requires careful planning and exploration before implementation. This tool transitions you into plan mode where you can thoroughly explore the codebase and design an implementation approach.
|
|
31
|
+
|
|
32
|
+
## When to Use This Tool
|
|
33
|
+
|
|
34
|
+
Use EnterPlanMode when ANY of these conditions apply:
|
|
35
|
+
|
|
36
|
+
1. **Multiple Valid Approaches**: The task can be solved in several different ways, each with trade-offs
|
|
37
|
+
- Example: "Add caching to the API" - could use Redis, in-memory, file-based, etc.
|
|
38
|
+
- Example: "Improve performance" - many optimization strategies possible
|
|
39
|
+
|
|
40
|
+
2. **Significant Architectural Decisions**: The task requires choosing between architectural patterns
|
|
41
|
+
- Example: "Add real-time updates" - WebSockets vs SSE vs polling
|
|
42
|
+
- Example: "Implement state management" - Redux vs Context vs custom solution
|
|
43
|
+
|
|
44
|
+
3. **Large-Scale Changes**: The task touches many files or systems
|
|
45
|
+
- Example: "Refactor the authentication system"
|
|
46
|
+
- Example: "Migrate from REST to GraphQL"
|
|
47
|
+
|
|
48
|
+
4. **Unclear Requirements**: You need to explore before understanding the full scope
|
|
49
|
+
- Example: "Make the app faster" - need to profile and identify bottlenecks
|
|
50
|
+
- Example: "Fix the bug in checkout" - need to investigate root cause
|
|
51
|
+
|
|
52
|
+
5. **User Input Needed**: You'll need to ask clarifying questions before starting
|
|
53
|
+
- If you would use {ask_tool} to clarify the approach, consider EnterPlanMode instead
|
|
54
|
+
- Plan mode lets you explore first, then present options with context
|
|
55
|
+
|
|
56
|
+
## When NOT to Use This Tool
|
|
57
|
+
|
|
58
|
+
Do NOT use EnterPlanMode for:
|
|
59
|
+
- Simple, straightforward tasks with obvious implementation
|
|
60
|
+
- Small bug fixes where the solution is clear
|
|
61
|
+
- Adding a single function or small feature
|
|
62
|
+
- Tasks you're already confident how to implement
|
|
63
|
+
- Research-only tasks (use the Task tool with explore agent instead)
|
|
64
|
+
|
|
65
|
+
## What Happens in Plan Mode
|
|
66
|
+
|
|
67
|
+
In plan mode, you'll:
|
|
68
|
+
1. Thoroughly explore the codebase using Glob, Grep, and Read tools
|
|
69
|
+
2. Understand existing patterns and architecture
|
|
70
|
+
3. Design an implementation approach
|
|
71
|
+
4. Present your plan to the user for approval
|
|
72
|
+
5. Use {ask_tool} if you need to clarify approaches
|
|
73
|
+
6. Exit plan mode with ExitPlanMode when ready to implement
|
|
74
|
+
|
|
75
|
+
## Examples
|
|
76
|
+
|
|
77
|
+
### GOOD - Use EnterPlanMode:
|
|
78
|
+
User: "Add user authentication to the app"
|
|
79
|
+
- This requires architectural decisions (session vs JWT, where to store tokens, middleware structure)
|
|
80
|
+
|
|
81
|
+
User: "Optimize the database queries"
|
|
82
|
+
- Multiple approaches possible, need to profile first, significant impact
|
|
83
|
+
|
|
84
|
+
User: "Implement dark mode"
|
|
85
|
+
- Architectural decision on theme system, affects many components
|
|
86
|
+
|
|
87
|
+
### BAD - Don't use EnterPlanMode:
|
|
88
|
+
User: "Fix the typo in the README"
|
|
89
|
+
- Straightforward, no planning needed
|
|
90
|
+
|
|
91
|
+
User: "Add a console.log to debug this function"
|
|
92
|
+
- Simple, obvious implementation
|
|
93
|
+
|
|
94
|
+
User: "What files handle routing?"
|
|
95
|
+
- Research task, not implementation planning
|
|
96
|
+
|
|
97
|
+
## Important Notes
|
|
98
|
+
|
|
99
|
+
- This tool REQUIRES user approval - they must consent to entering plan mode
|
|
100
|
+
- Be thoughtful about when to use it - unnecessary plan mode slows down simple tasks
|
|
101
|
+
- If unsure whether to use it, err on the side of starting implementation
|
|
102
|
+
- You can always ask the user "Would you like me to plan this out first?"
|
|
103
|
+
"""
|
|
104
|
+
).format(ask_tool=ASK_USER_QUESTION_TOOL)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
PLAN_MODE_INSTRUCTIONS = dedent(
|
|
108
|
+
"""\
|
|
109
|
+
In plan mode, you should:
|
|
110
|
+
1. Thoroughly explore the codebase to understand existing patterns
|
|
111
|
+
2. Identify similar features and architectural approaches
|
|
112
|
+
3. Consider multiple approaches and their trade-offs
|
|
113
|
+
4. Use AskUserQuestion if you need to clarify the approach
|
|
114
|
+
5. Design a concrete implementation strategy
|
|
115
|
+
6. When ready, use ExitPlanMode to present your plan for approval
|
|
116
|
+
|
|
117
|
+
Remember: DO NOT write or edit any files yet. This is a read-only exploration and planning phase."""
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class EnterPlanModeToolInput(BaseModel):
|
|
122
|
+
"""Input for the EnterPlanMode tool.
|
|
123
|
+
|
|
124
|
+
This tool takes no input parameters - it simply requests to enter plan mode.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class EnterPlanModeToolOutput(BaseModel):
|
|
131
|
+
"""Output from the EnterPlanMode tool."""
|
|
132
|
+
|
|
133
|
+
message: str
|
|
134
|
+
entered: bool = True
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class EnterPlanModeTool(Tool[EnterPlanModeToolInput, EnterPlanModeToolOutput]):
|
|
138
|
+
"""Tool for entering plan mode for complex tasks."""
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def name(self) -> str:
|
|
142
|
+
return TOOL_NAME
|
|
143
|
+
|
|
144
|
+
async def description(self) -> str:
|
|
145
|
+
return (
|
|
146
|
+
"Requests permission to enter plan mode for complex tasks "
|
|
147
|
+
"requiring exploration and design"
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def input_schema(self) -> type[EnterPlanModeToolInput]:
|
|
152
|
+
return EnterPlanModeToolInput
|
|
153
|
+
|
|
154
|
+
async def prompt(self, safe_mode: bool = False) -> str: # noqa: ARG002
|
|
155
|
+
return ENTER_PLAN_MODE_PROMPT
|
|
156
|
+
|
|
157
|
+
def user_facing_name(self) -> str:
|
|
158
|
+
return ""
|
|
159
|
+
|
|
160
|
+
def is_read_only(self) -> bool:
|
|
161
|
+
return True
|
|
162
|
+
|
|
163
|
+
def is_concurrency_safe(self) -> bool:
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
def needs_permissions(
|
|
167
|
+
self, input_data: Optional[EnterPlanModeToolInput] = None # noqa: ARG002
|
|
168
|
+
) -> bool:
|
|
169
|
+
return True
|
|
170
|
+
|
|
171
|
+
async def validate_input(
|
|
172
|
+
self,
|
|
173
|
+
input_data: EnterPlanModeToolInput,
|
|
174
|
+
context: Optional[ToolUseContext] = None,
|
|
175
|
+
) -> ValidationResult:
|
|
176
|
+
"""Validate that this tool is not being used in an agent context."""
|
|
177
|
+
if context and context.agent_id:
|
|
178
|
+
return ValidationResult(
|
|
179
|
+
result=False,
|
|
180
|
+
message="EnterPlanMode tool cannot be used in agent contexts",
|
|
181
|
+
)
|
|
182
|
+
return ValidationResult(result=True)
|
|
183
|
+
|
|
184
|
+
def render_result_for_assistant(self, output: EnterPlanModeToolOutput) -> str:
|
|
185
|
+
"""Render the tool output for the AI assistant."""
|
|
186
|
+
if not output.entered:
|
|
187
|
+
return "User declined to enter plan mode. Continue with normal implementation."
|
|
188
|
+
return f"{output.message}\n\n{PLAN_MODE_INSTRUCTIONS}"
|
|
189
|
+
|
|
190
|
+
def render_tool_use_message(
|
|
191
|
+
self, input_data: EnterPlanModeToolInput, verbose: bool = False # noqa: ARG002
|
|
192
|
+
) -> str:
|
|
193
|
+
"""Render the tool use message for display."""
|
|
194
|
+
return "Requesting to enter plan mode"
|
|
195
|
+
|
|
196
|
+
async def call(
|
|
197
|
+
self,
|
|
198
|
+
input_data: EnterPlanModeToolInput, # noqa: ARG002
|
|
199
|
+
context: ToolUseContext,
|
|
200
|
+
) -> AsyncGenerator[ToolOutput, None]:
|
|
201
|
+
"""Execute the tool to enter plan mode."""
|
|
202
|
+
if context.agent_id:
|
|
203
|
+
output = EnterPlanModeToolOutput(
|
|
204
|
+
message="EnterPlanMode tool cannot be used in agent contexts",
|
|
205
|
+
entered=False,
|
|
206
|
+
)
|
|
207
|
+
yield ToolResult(
|
|
208
|
+
data=output,
|
|
209
|
+
result_for_assistant=self.render_result_for_assistant(output),
|
|
210
|
+
)
|
|
211
|
+
return
|
|
212
|
+
|
|
213
|
+
output = EnterPlanModeToolOutput(
|
|
214
|
+
message=(
|
|
215
|
+
"Entered plan mode. You should now focus on exploring "
|
|
216
|
+
"the codebase and designing an implementation approach."
|
|
217
|
+
),
|
|
218
|
+
entered=True,
|
|
219
|
+
)
|
|
220
|
+
yield ToolResult(
|
|
221
|
+
data=output,
|
|
222
|
+
result_for_assistant=self.render_result_for_assistant(output),
|
|
223
|
+
)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Exit plan mode tool for presenting implementation plans.
|
|
2
|
+
|
|
3
|
+
This tool allows the AI to exit plan mode and present an implementation
|
|
4
|
+
plan to the user for approval before starting to code.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from textwrap import dedent
|
|
10
|
+
from typing import AsyncGenerator, Optional
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel, Field
|
|
13
|
+
|
|
14
|
+
from ripperdoc.core.tool import (
|
|
15
|
+
Tool,
|
|
16
|
+
ToolOutput,
|
|
17
|
+
ToolResult,
|
|
18
|
+
ToolUseContext,
|
|
19
|
+
ValidationResult,
|
|
20
|
+
)
|
|
21
|
+
from ripperdoc.utils.log import get_logger
|
|
22
|
+
|
|
23
|
+
logger = get_logger()
|
|
24
|
+
|
|
25
|
+
TOOL_NAME = "ExitPlanMode"
|
|
26
|
+
|
|
27
|
+
EXIT_PLAN_MODE_PROMPT = dedent(
|
|
28
|
+
"""\
|
|
29
|
+
Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
|
|
30
|
+
|
|
31
|
+
## How This Tool Works
|
|
32
|
+
- You should have already written your plan to the plan file specified in the plan mode system message
|
|
33
|
+
- This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
|
|
34
|
+
- This tool simply signals that you're done planning and ready for the user to review and approve
|
|
35
|
+
- The user will see the contents of your plan file when they review it
|
|
36
|
+
|
|
37
|
+
## When to Use This Tool
|
|
38
|
+
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
|
|
39
|
+
|
|
40
|
+
## Handling Ambiguity in Plans
|
|
41
|
+
Before using this tool, ensure your plan is clear and unambiguous. If there are multiple valid approaches or unclear requirements:
|
|
42
|
+
1. Use the AskUserQuestion tool to clarify with the user
|
|
43
|
+
2. Ask about specific implementation choices (e.g., architectural patterns, which library to use)
|
|
44
|
+
3. Clarify any assumptions that could affect the implementation
|
|
45
|
+
4. Edit your plan file to incorporate user feedback
|
|
46
|
+
5. Only proceed with ExitPlanMode after resolving ambiguities and updating the plan file
|
|
47
|
+
|
|
48
|
+
## Examples
|
|
49
|
+
|
|
50
|
+
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
|
|
51
|
+
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
|
|
52
|
+
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
|
|
53
|
+
"""
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ExitPlanModeToolInput(BaseModel):
|
|
58
|
+
"""Input for the ExitPlanMode tool."""
|
|
59
|
+
|
|
60
|
+
plan: str = Field(
|
|
61
|
+
description="The plan you came up with, that you want to run by the user for approval. "
|
|
62
|
+
"Supports markdown. The plan should be pretty concise."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ExitPlanModeToolOutput(BaseModel):
|
|
67
|
+
"""Output from the ExitPlanMode tool."""
|
|
68
|
+
|
|
69
|
+
plan: str
|
|
70
|
+
is_agent: bool = False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ExitPlanModeTool(Tool[ExitPlanModeToolInput, ExitPlanModeToolOutput]):
|
|
74
|
+
"""Tool for exiting plan mode and presenting a plan for approval."""
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def name(self) -> str:
|
|
78
|
+
return TOOL_NAME
|
|
79
|
+
|
|
80
|
+
async def description(self) -> str:
|
|
81
|
+
return "Prompts the user to exit plan mode and start coding"
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def input_schema(self) -> type[ExitPlanModeToolInput]:
|
|
85
|
+
return ExitPlanModeToolInput
|
|
86
|
+
|
|
87
|
+
async def prompt(self, safe_mode: bool = False) -> str: # noqa: ARG002
|
|
88
|
+
return EXIT_PLAN_MODE_PROMPT
|
|
89
|
+
|
|
90
|
+
def user_facing_name(self) -> str:
|
|
91
|
+
return "Exit plan mode"
|
|
92
|
+
|
|
93
|
+
def is_read_only(self) -> bool:
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
def is_concurrency_safe(self) -> bool:
|
|
97
|
+
return True
|
|
98
|
+
|
|
99
|
+
def needs_permissions(
|
|
100
|
+
self, input_data: Optional[ExitPlanModeToolInput] = None # noqa: ARG002
|
|
101
|
+
) -> bool:
|
|
102
|
+
return True
|
|
103
|
+
|
|
104
|
+
async def validate_input(
|
|
105
|
+
self,
|
|
106
|
+
input_data: ExitPlanModeToolInput,
|
|
107
|
+
context: Optional[ToolUseContext] = None, # noqa: ARG002
|
|
108
|
+
) -> ValidationResult:
|
|
109
|
+
"""Validate that plan is not empty."""
|
|
110
|
+
if not input_data.plan or not input_data.plan.strip():
|
|
111
|
+
return ValidationResult(
|
|
112
|
+
result=False,
|
|
113
|
+
message="Plan cannot be empty",
|
|
114
|
+
)
|
|
115
|
+
return ValidationResult(result=True)
|
|
116
|
+
|
|
117
|
+
def render_result_for_assistant(self, output: ExitPlanModeToolOutput) -> str:
|
|
118
|
+
"""Render the tool output for the AI assistant."""
|
|
119
|
+
return f"Exit plan mode and start coding now. Plan:\n{output.plan}"
|
|
120
|
+
|
|
121
|
+
def render_tool_use_message(
|
|
122
|
+
self, input_data: ExitPlanModeToolInput, verbose: bool = False # noqa: ARG002
|
|
123
|
+
) -> str:
|
|
124
|
+
"""Render the tool use message for display."""
|
|
125
|
+
plan = input_data.plan
|
|
126
|
+
snippet = f"{plan[:77]}..." if len(plan) > 80 else plan
|
|
127
|
+
return f"Share plan for approval: {snippet}"
|
|
128
|
+
|
|
129
|
+
async def call(
|
|
130
|
+
self,
|
|
131
|
+
input_data: ExitPlanModeToolInput,
|
|
132
|
+
context: ToolUseContext,
|
|
133
|
+
) -> AsyncGenerator[ToolOutput, None]:
|
|
134
|
+
"""Execute the tool to exit plan mode."""
|
|
135
|
+
# Invoke the exit plan mode callback if available
|
|
136
|
+
if context.on_exit_plan_mode:
|
|
137
|
+
try:
|
|
138
|
+
context.on_exit_plan_mode()
|
|
139
|
+
except Exception:
|
|
140
|
+
logger.debug("[exit_plan_mode_tool] Failed to call on_exit_plan_mode")
|
|
141
|
+
|
|
142
|
+
is_agent = bool(context.agent_id)
|
|
143
|
+
output = ExitPlanModeToolOutput(
|
|
144
|
+
plan=input_data.plan,
|
|
145
|
+
is_agent=is_agent,
|
|
146
|
+
)
|
|
147
|
+
yield ToolResult(
|
|
148
|
+
data=output,
|
|
149
|
+
result_for_assistant=self.render_result_for_assistant(output),
|
|
150
|
+
)
|
ripperdoc/tools/mcp_tools.py
CHANGED
|
@@ -30,6 +30,7 @@ from ripperdoc.utils.mcp import (
|
|
|
30
30
|
load_mcp_servers_async,
|
|
31
31
|
shutdown_mcp_runtime,
|
|
32
32
|
)
|
|
33
|
+
from ripperdoc.utils.token_estimation import estimate_tokens
|
|
33
34
|
|
|
34
35
|
|
|
35
36
|
logger = get_logger()
|
|
@@ -40,6 +41,55 @@ except Exception: # pragma: no cover - SDK may be missing at runtime
|
|
|
40
41
|
mcp_types = None # type: ignore[assignment]
|
|
41
42
|
logger.exception("[mcp_tools] MCP SDK unavailable during import")
|
|
42
43
|
|
|
44
|
+
DEFAULT_MAX_MCP_OUTPUT_TOKENS = 25_000
|
|
45
|
+
MIN_MCP_OUTPUT_TOKENS = 1_000
|
|
46
|
+
DEFAULT_MCP_WARNING_FRACTION = 0.8
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get_mcp_token_limits() -> tuple[int, int]:
|
|
50
|
+
"""Compute warning and hard limits for MCP output size."""
|
|
51
|
+
max_tokens = os.getenv("RIPPERDOC_MCP_MAX_OUTPUT_TOKENS")
|
|
52
|
+
try:
|
|
53
|
+
max_tokens_int = int(max_tokens) if max_tokens else DEFAULT_MAX_MCP_OUTPUT_TOKENS
|
|
54
|
+
except (TypeError, ValueError):
|
|
55
|
+
max_tokens_int = DEFAULT_MAX_MCP_OUTPUT_TOKENS
|
|
56
|
+
max_tokens_int = max(MIN_MCP_OUTPUT_TOKENS, max_tokens_int)
|
|
57
|
+
|
|
58
|
+
warn_env = os.getenv("RIPPERDOC_MCP_WARNING_TOKENS")
|
|
59
|
+
try:
|
|
60
|
+
warn_tokens_int = int(warn_env) if warn_env else int(max_tokens_int * DEFAULT_MCP_WARNING_FRACTION)
|
|
61
|
+
except (TypeError, ValueError):
|
|
62
|
+
warn_tokens_int = int(max_tokens_int * DEFAULT_MCP_WARNING_FRACTION)
|
|
63
|
+
warn_tokens_int = max(MIN_MCP_OUTPUT_TOKENS, min(warn_tokens_int, max_tokens_int))
|
|
64
|
+
return warn_tokens_int, max_tokens_int
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _evaluate_mcp_output_size(
|
|
68
|
+
result_text: Optional[str],
|
|
69
|
+
server_name: str,
|
|
70
|
+
tool_name: str,
|
|
71
|
+
) -> tuple[Optional[str], Optional[str], int]:
|
|
72
|
+
"""Return (warning, error, token_estimate) for an MCP result text."""
|
|
73
|
+
warn_tokens, max_tokens = _get_mcp_token_limits()
|
|
74
|
+
token_estimate = estimate_tokens(result_text or "")
|
|
75
|
+
|
|
76
|
+
if token_estimate > max_tokens:
|
|
77
|
+
error_text = (
|
|
78
|
+
f"MCP response from {server_name}:{tool_name} is ~{token_estimate:,} tokens, "
|
|
79
|
+
f"which exceeds the configured limit of {max_tokens}. "
|
|
80
|
+
"Refine the request (pagination/filtering) or raise RIPPERDOC_MCP_MAX_OUTPUT_TOKENS."
|
|
81
|
+
)
|
|
82
|
+
return None, error_text, token_estimate
|
|
83
|
+
|
|
84
|
+
warning_text = None
|
|
85
|
+
if result_text and token_estimate >= warn_tokens:
|
|
86
|
+
line_count = result_text.count("\n") + 1
|
|
87
|
+
warning_text = (
|
|
88
|
+
f"WARNING: Large MCP response (~{token_estimate:,} tokens, {line_count:,} lines). "
|
|
89
|
+
"This can fill the context quickly; consider pagination or filters."
|
|
90
|
+
)
|
|
91
|
+
return warning_text, None, token_estimate
|
|
92
|
+
|
|
43
93
|
|
|
44
94
|
def _content_block_to_text(block: Any) -> str:
|
|
45
95
|
block_type = getattr(block, "type", None) or (
|
|
@@ -370,6 +420,9 @@ class ReadMcpResourceOutput(BaseModel):
|
|
|
370
420
|
uri: str
|
|
371
421
|
content: Optional[str] = None
|
|
372
422
|
contents: List[ResourceContentPart] = Field(default_factory=list)
|
|
423
|
+
token_estimate: Optional[int] = None
|
|
424
|
+
warning: Optional[str] = None
|
|
425
|
+
is_error: bool = False
|
|
373
426
|
|
|
374
427
|
|
|
375
428
|
class McpToolCallOutput(BaseModel):
|
|
@@ -382,6 +435,8 @@ class McpToolCallOutput(BaseModel):
|
|
|
382
435
|
content_blocks: Optional[List[Any]] = None
|
|
383
436
|
structured_content: Optional[dict] = None
|
|
384
437
|
is_error: bool = False
|
|
438
|
+
token_estimate: Optional[int] = None
|
|
439
|
+
warning: Optional[str] = None
|
|
385
440
|
|
|
386
441
|
|
|
387
442
|
class ReadMcpResourceTool(Tool[ReadMcpResourceInput, ReadMcpResourceOutput]):
|
|
@@ -552,9 +607,35 @@ class ReadMcpResourceTool(Tool[ReadMcpResourceInput, ReadMcpResourceOutput]):
|
|
|
552
607
|
read_result: Any = ReadMcpResourceOutput(
|
|
553
608
|
server=input_data.server, uri=input_data.uri, content=content_text, contents=parts
|
|
554
609
|
)
|
|
610
|
+
assistant_text = self.render_result_for_assistant(read_result) # type: ignore[arg-type]
|
|
611
|
+
warning_text, error_text, token_estimate = _evaluate_mcp_output_size(
|
|
612
|
+
assistant_text, input_data.server, f"resource:{input_data.uri}"
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
if error_text:
|
|
616
|
+
limited_result = ReadMcpResourceOutput(
|
|
617
|
+
server=input_data.server,
|
|
618
|
+
uri=input_data.uri,
|
|
619
|
+
content=None,
|
|
620
|
+
contents=[],
|
|
621
|
+
token_estimate=token_estimate,
|
|
622
|
+
warning=None,
|
|
623
|
+
is_error=True,
|
|
624
|
+
)
|
|
625
|
+
yield ToolResult(data=limited_result, result_for_assistant=error_text)
|
|
626
|
+
return
|
|
627
|
+
|
|
628
|
+
annotated_result = read_result.model_copy(
|
|
629
|
+
update={"token_estimate": token_estimate, "warning": warning_text}
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
final_text = assistant_text or ""
|
|
633
|
+
if not final_text and warning_text:
|
|
634
|
+
final_text = warning_text
|
|
635
|
+
|
|
555
636
|
yield ToolResult(
|
|
556
|
-
data=
|
|
557
|
-
result_for_assistant=
|
|
637
|
+
data=annotated_result,
|
|
638
|
+
result_for_assistant=final_text, # type: ignore[arg-type]
|
|
558
639
|
)
|
|
559
640
|
|
|
560
641
|
|
|
@@ -715,9 +796,37 @@ class DynamicMcpTool(Tool[BaseModel, McpToolCallOutput]):
|
|
|
715
796
|
structured_content=structured,
|
|
716
797
|
is_error=getattr(call_result, "isError", False),
|
|
717
798
|
)
|
|
799
|
+
base_result_text = self.render_result_for_assistant(output)
|
|
800
|
+
warning_text, error_text, token_estimate = _evaluate_mcp_output_size(
|
|
801
|
+
base_result_text, self.server_name, self.tool_info.name
|
|
802
|
+
)
|
|
803
|
+
|
|
804
|
+
if error_text:
|
|
805
|
+
limited_output = McpToolCallOutput(
|
|
806
|
+
server=self.server_name,
|
|
807
|
+
tool=self.tool_info.name,
|
|
808
|
+
content=None,
|
|
809
|
+
text=None,
|
|
810
|
+
content_blocks=None,
|
|
811
|
+
structured_content=None,
|
|
812
|
+
is_error=True,
|
|
813
|
+
token_estimate=token_estimate,
|
|
814
|
+
warning=None,
|
|
815
|
+
)
|
|
816
|
+
yield ToolResult(data=limited_output, result_for_assistant=error_text)
|
|
817
|
+
return
|
|
818
|
+
|
|
819
|
+
annotated_output = output.model_copy(
|
|
820
|
+
update={"token_estimate": token_estimate, "warning": warning_text}
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
final_text = base_result_text or ""
|
|
824
|
+
if not final_text and warning_text:
|
|
825
|
+
final_text = warning_text
|
|
826
|
+
|
|
718
827
|
yield ToolResult(
|
|
719
|
-
data=
|
|
720
|
-
result_for_assistant=
|
|
828
|
+
data=annotated_output,
|
|
829
|
+
result_for_assistant=final_text,
|
|
721
830
|
)
|
|
722
831
|
except Exception as exc: # pragma: no cover - runtime errors
|
|
723
832
|
output = McpToolCallOutput(
|
ripperdoc/tools/task_tool.py
CHANGED
|
@@ -10,6 +10,9 @@ from pydantic import BaseModel, Field
|
|
|
10
10
|
from ripperdoc.core.agents import (
|
|
11
11
|
AgentDefinition,
|
|
12
12
|
AgentLoadResult,
|
|
13
|
+
FILE_EDIT_TOOL_NAME,
|
|
14
|
+
GREP_TOOL_NAME,
|
|
15
|
+
VIEW_TOOL_NAME,
|
|
13
16
|
clear_agent_cache,
|
|
14
17
|
load_agent_definitions,
|
|
15
18
|
resolve_agent_tools,
|
|
@@ -70,12 +73,92 @@ class TaskTool(Tool[TaskToolInput, TaskToolOutput]):
|
|
|
70
73
|
del safe_mode
|
|
71
74
|
clear_agent_cache()
|
|
72
75
|
agents: AgentLoadResult = load_agent_definitions()
|
|
73
|
-
|
|
76
|
+
|
|
77
|
+
agent_lines: List[str] = []
|
|
78
|
+
for agent in agents.active_agents:
|
|
79
|
+
properties = (
|
|
80
|
+
"Properties: access to current context; "
|
|
81
|
+
if getattr(agent, "fork_context", False)
|
|
82
|
+
else ""
|
|
83
|
+
)
|
|
84
|
+
tools_label = "All tools"
|
|
85
|
+
if getattr(agent, "tools", None):
|
|
86
|
+
tools_label = (
|
|
87
|
+
"All tools" if "*" in agent.tools else ", ".join(agent.tools)
|
|
88
|
+
)
|
|
89
|
+
agent_lines.append(
|
|
90
|
+
f"- {agent.agent_type}: {agent.when_to_use} ({properties}Tools: {tools_label})"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
agent_block = "\n".join(agent_lines) or "- general-purpose (built-in)"
|
|
94
|
+
|
|
95
|
+
task_tool_name = self.name
|
|
96
|
+
file_read_tool_name = VIEW_TOOL_NAME
|
|
97
|
+
search_tool_name = GREP_TOOL_NAME
|
|
98
|
+
code_tool_name = FILE_EDIT_TOOL_NAME
|
|
99
|
+
background_fetch_tool_name = task_tool_name
|
|
100
|
+
|
|
74
101
|
return (
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"
|
|
78
|
-
f"
|
|
102
|
+
f"Launch a new agent to handle complex, multi-step tasks autonomously. \n\n"
|
|
103
|
+
f"The {task_tool_name} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.\n\n"
|
|
104
|
+
f"Available agent types and the tools they have access to:\n"
|
|
105
|
+
f"{agent_block}\n\n"
|
|
106
|
+
f"When using the {task_tool_name} tool, you must specify a subagent_type parameter to select which agent type to use.\n\n"
|
|
107
|
+
f"When NOT to use the {task_tool_name} tool:\n"
|
|
108
|
+
f"- If you want to read a specific file path, use the {file_read_tool_name} or {search_tool_name} tool instead of the {task_tool_name} tool, to find the match more quickly\n"
|
|
109
|
+
f'- If you are searching for a specific class definition like "class Foo", use the {search_tool_name} tool instead, to find the match more quickly\n'
|
|
110
|
+
f"- If you are searching for code within a specific file or set of 2-3 files, use the {file_read_tool_name} tool instead of the {task_tool_name} tool, to find the match more quickly\n"
|
|
111
|
+
"- Other tasks that are not related to the agent descriptions above\n"
|
|
112
|
+
"\n"
|
|
113
|
+
"\n"
|
|
114
|
+
"Usage notes:\n"
|
|
115
|
+
"- Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n"
|
|
116
|
+
"- When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n"
|
|
117
|
+
f"- You can optionally run agents in the background using the run_in_background parameter. When an agent runs in the background, you will need to use {background_fetch_tool_name} to retrieve its results once it's done. You can continue to work while background agents run - When you need their results to continue you can use {background_fetch_tool_name} in blocking mode to pause and wait for their results.\n"
|
|
118
|
+
"- Agents can be resumed using the `resume` parameter by passing the agent ID from a previous invocation. When resumed, the agent continues with its full previous context preserved. When NOT resuming, each invocation starts fresh and you should provide a detailed task description with all necessary context.\n"
|
|
119
|
+
"- When the agent is done, it will return a single message back to you along with its agent ID. You can use this ID to resume the agent later if needed for follow-up work.\n"
|
|
120
|
+
"- Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.\n"
|
|
121
|
+
'- Agents with "access to current context" can see the full conversation history before the tool call. When using these agents, you can write concise prompts that reference earlier context (e.g., "investigate the error discussed above") instead of repeating information. The agent will receive all prior messages and understand the context.\n'
|
|
122
|
+
"- The agent's outputs should generally be trusted\n"
|
|
123
|
+
"- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n"
|
|
124
|
+
"- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n"
|
|
125
|
+
f'- If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple {task_tool_name} tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.\n'
|
|
126
|
+
"\n"
|
|
127
|
+
"Example usage:\n"
|
|
128
|
+
"\n"
|
|
129
|
+
"<example_agent_descriptions>\n"
|
|
130
|
+
'"code-reviewer": use this agent after you are done writing a signficant piece of code\n'
|
|
131
|
+
'"greeting-responder": use this agent when to respond to user greetings with a friendly joke\n'
|
|
132
|
+
"</example_agent_description>\n"
|
|
133
|
+
"\n"
|
|
134
|
+
"<example>\n"
|
|
135
|
+
'user: "Please write a function that checks if a number is prime"\n'
|
|
136
|
+
"assistant: Sure let me write a function that checks if a number is prime\n"
|
|
137
|
+
f"assistant: First let me use the {code_tool_name} tool to write a function that checks if a number is prime\n"
|
|
138
|
+
f"assistant: I'm going to use the {code_tool_name} tool to write the following code:\n"
|
|
139
|
+
"<code>\n"
|
|
140
|
+
"function isPrime(n) {\n"
|
|
141
|
+
" if (n <= 1) return false\n"
|
|
142
|
+
" for (let i = 2; i * i <= n; i++) {\n"
|
|
143
|
+
" if (n % i === 0) return false\n"
|
|
144
|
+
" }\n"
|
|
145
|
+
" return true\n"
|
|
146
|
+
"}\n"
|
|
147
|
+
"</code>\n"
|
|
148
|
+
"<commentary>\n"
|
|
149
|
+
"Since a signficant piece of code was written and the task was completed, now use the code-reviewer agent to review the code\n"
|
|
150
|
+
"</commentary>\n"
|
|
151
|
+
"assistant: Now let me use the code-reviewer agent to review the code\n"
|
|
152
|
+
f"assistant: Uses the {task_tool_name} tool to launch the code-reviewer agent \n"
|
|
153
|
+
"</example>\n"
|
|
154
|
+
"\n"
|
|
155
|
+
"<example>\n"
|
|
156
|
+
'user: "Hello"\n'
|
|
157
|
+
"<commentary>\n"
|
|
158
|
+
"Since the user is greeting, use the greeting-responder agent to respond with a friendly joke\n"
|
|
159
|
+
"</commentary>\n"
|
|
160
|
+
f'assistant: "I\'m going to use the {task_tool_name} tool to launch the greeting-responder agent\"\n'
|
|
161
|
+
"</example>"
|
|
79
162
|
)
|
|
80
163
|
|
|
81
164
|
def is_read_only(self) -> bool:
|