ripperdoc 0.2.6__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 (107) hide show
  1. ripperdoc/__init__.py +3 -0
  2. ripperdoc/__main__.py +20 -0
  3. ripperdoc/cli/__init__.py +1 -0
  4. ripperdoc/cli/cli.py +405 -0
  5. ripperdoc/cli/commands/__init__.py +82 -0
  6. ripperdoc/cli/commands/agents_cmd.py +263 -0
  7. ripperdoc/cli/commands/base.py +19 -0
  8. ripperdoc/cli/commands/clear_cmd.py +18 -0
  9. ripperdoc/cli/commands/compact_cmd.py +23 -0
  10. ripperdoc/cli/commands/config_cmd.py +31 -0
  11. ripperdoc/cli/commands/context_cmd.py +144 -0
  12. ripperdoc/cli/commands/cost_cmd.py +82 -0
  13. ripperdoc/cli/commands/doctor_cmd.py +221 -0
  14. ripperdoc/cli/commands/exit_cmd.py +19 -0
  15. ripperdoc/cli/commands/help_cmd.py +20 -0
  16. ripperdoc/cli/commands/mcp_cmd.py +70 -0
  17. ripperdoc/cli/commands/memory_cmd.py +202 -0
  18. ripperdoc/cli/commands/models_cmd.py +413 -0
  19. ripperdoc/cli/commands/permissions_cmd.py +302 -0
  20. ripperdoc/cli/commands/resume_cmd.py +98 -0
  21. ripperdoc/cli/commands/status_cmd.py +167 -0
  22. ripperdoc/cli/commands/tasks_cmd.py +278 -0
  23. ripperdoc/cli/commands/todos_cmd.py +69 -0
  24. ripperdoc/cli/commands/tools_cmd.py +19 -0
  25. ripperdoc/cli/ui/__init__.py +1 -0
  26. ripperdoc/cli/ui/context_display.py +298 -0
  27. ripperdoc/cli/ui/helpers.py +22 -0
  28. ripperdoc/cli/ui/rich_ui.py +1557 -0
  29. ripperdoc/cli/ui/spinner.py +49 -0
  30. ripperdoc/cli/ui/thinking_spinner.py +128 -0
  31. ripperdoc/cli/ui/tool_renderers.py +298 -0
  32. ripperdoc/core/__init__.py +1 -0
  33. ripperdoc/core/agents.py +486 -0
  34. ripperdoc/core/commands.py +33 -0
  35. ripperdoc/core/config.py +559 -0
  36. ripperdoc/core/default_tools.py +88 -0
  37. ripperdoc/core/permissions.py +252 -0
  38. ripperdoc/core/providers/__init__.py +47 -0
  39. ripperdoc/core/providers/anthropic.py +250 -0
  40. ripperdoc/core/providers/base.py +265 -0
  41. ripperdoc/core/providers/gemini.py +615 -0
  42. ripperdoc/core/providers/openai.py +487 -0
  43. ripperdoc/core/query.py +1058 -0
  44. ripperdoc/core/query_utils.py +622 -0
  45. ripperdoc/core/skills.py +295 -0
  46. ripperdoc/core/system_prompt.py +431 -0
  47. ripperdoc/core/tool.py +240 -0
  48. ripperdoc/sdk/__init__.py +9 -0
  49. ripperdoc/sdk/client.py +333 -0
  50. ripperdoc/tools/__init__.py +1 -0
  51. ripperdoc/tools/ask_user_question_tool.py +431 -0
  52. ripperdoc/tools/background_shell.py +389 -0
  53. ripperdoc/tools/bash_output_tool.py +98 -0
  54. ripperdoc/tools/bash_tool.py +1016 -0
  55. ripperdoc/tools/dynamic_mcp_tool.py +428 -0
  56. ripperdoc/tools/enter_plan_mode_tool.py +226 -0
  57. ripperdoc/tools/exit_plan_mode_tool.py +153 -0
  58. ripperdoc/tools/file_edit_tool.py +346 -0
  59. ripperdoc/tools/file_read_tool.py +203 -0
  60. ripperdoc/tools/file_write_tool.py +205 -0
  61. ripperdoc/tools/glob_tool.py +179 -0
  62. ripperdoc/tools/grep_tool.py +370 -0
  63. ripperdoc/tools/kill_bash_tool.py +136 -0
  64. ripperdoc/tools/ls_tool.py +471 -0
  65. ripperdoc/tools/mcp_tools.py +591 -0
  66. ripperdoc/tools/multi_edit_tool.py +456 -0
  67. ripperdoc/tools/notebook_edit_tool.py +386 -0
  68. ripperdoc/tools/skill_tool.py +205 -0
  69. ripperdoc/tools/task_tool.py +379 -0
  70. ripperdoc/tools/todo_tool.py +494 -0
  71. ripperdoc/tools/tool_search_tool.py +380 -0
  72. ripperdoc/utils/__init__.py +1 -0
  73. ripperdoc/utils/bash_constants.py +51 -0
  74. ripperdoc/utils/bash_output_utils.py +43 -0
  75. ripperdoc/utils/coerce.py +34 -0
  76. ripperdoc/utils/context_length_errors.py +252 -0
  77. ripperdoc/utils/exit_code_handlers.py +241 -0
  78. ripperdoc/utils/file_watch.py +135 -0
  79. ripperdoc/utils/git_utils.py +274 -0
  80. ripperdoc/utils/json_utils.py +27 -0
  81. ripperdoc/utils/log.py +176 -0
  82. ripperdoc/utils/mcp.py +560 -0
  83. ripperdoc/utils/memory.py +253 -0
  84. ripperdoc/utils/message_compaction.py +676 -0
  85. ripperdoc/utils/messages.py +519 -0
  86. ripperdoc/utils/output_utils.py +258 -0
  87. ripperdoc/utils/path_ignore.py +677 -0
  88. ripperdoc/utils/path_utils.py +46 -0
  89. ripperdoc/utils/permissions/__init__.py +27 -0
  90. ripperdoc/utils/permissions/path_validation_utils.py +174 -0
  91. ripperdoc/utils/permissions/shell_command_validation.py +552 -0
  92. ripperdoc/utils/permissions/tool_permission_utils.py +279 -0
  93. ripperdoc/utils/prompt.py +17 -0
  94. ripperdoc/utils/safe_get_cwd.py +31 -0
  95. ripperdoc/utils/sandbox_utils.py +38 -0
  96. ripperdoc/utils/session_history.py +260 -0
  97. ripperdoc/utils/session_usage.py +117 -0
  98. ripperdoc/utils/shell_token_utils.py +95 -0
  99. ripperdoc/utils/shell_utils.py +159 -0
  100. ripperdoc/utils/todo.py +203 -0
  101. ripperdoc/utils/token_estimation.py +34 -0
  102. ripperdoc-0.2.6.dist-info/METADATA +193 -0
  103. ripperdoc-0.2.6.dist-info/RECORD +107 -0
  104. ripperdoc-0.2.6.dist-info/WHEEL +5 -0
  105. ripperdoc-0.2.6.dist-info/entry_points.txt +3 -0
  106. ripperdoc-0.2.6.dist-info/licenses/LICENSE +53 -0
  107. ripperdoc-0.2.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,431 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import subprocess
6
+ from datetime import date
7
+ from pathlib import Path
8
+ from textwrap import dedent
9
+ from typing import Any, Dict, Iterable, List, Optional
10
+
11
+ from ripperdoc.core.agents import (
12
+ ASK_USER_QUESTION_TOOL_NAME,
13
+ BASH_TOOL_NAME,
14
+ FILE_EDIT_TOOL_NAME,
15
+ FILE_WRITE_TOOL_NAME,
16
+ TASK_TOOL_NAME,
17
+ TODO_WRITE_TOOL_NAME,
18
+ TOOL_SEARCH_TOOL_NAME,
19
+ VIEW_TOOL_NAME,
20
+ clear_agent_cache,
21
+ load_agent_definitions,
22
+ summarize_agent,
23
+ )
24
+ from ripperdoc.core.tool import Tool
25
+ from ripperdoc.utils.log import get_logger
26
+
27
+
28
+ logger = get_logger()
29
+
30
+ APP_NAME = "Ripperdoc"
31
+ DEFENSIVE_SECURITY_GUIDELINE = (
32
+ "IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. "
33
+ "Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation."
34
+ )
35
+ FEEDBACK_URL = "https://github.com/quantmew/Ripperdoc/issues"
36
+
37
+
38
+ def _detect_git_repo(cwd: Path) -> bool:
39
+ try:
40
+ result = subprocess.run(
41
+ ["git", "rev-parse", "--is-inside-work-tree"],
42
+ cwd=str(cwd),
43
+ stdout=subprocess.PIPE,
44
+ stderr=subprocess.PIPE,
45
+ text=True,
46
+ check=False,
47
+ )
48
+ return result.returncode == 0 and result.stdout.strip().lower() == "true"
49
+ except (OSError, subprocess.SubprocessError) as exc:
50
+ logger.warning(
51
+ "[system_prompt] Failed to detect git repository: %s: %s",
52
+ type(exc).__name__, exc,
53
+ extra={"cwd": str(cwd)},
54
+ )
55
+ return False
56
+
57
+
58
+ def build_environment_prompt(cwd: Optional[Path] = None) -> str:
59
+ path = cwd or Path.cwd()
60
+ is_git_repo = _detect_git_repo(path)
61
+ today = date.today().isoformat()
62
+ os_version = platform.version()
63
+ platform_name = platform.system()
64
+
65
+ return dedent(
66
+ f"""\
67
+ Here is useful information about the environment you are running in:
68
+ <env>
69
+ Working directory: {path}
70
+ Is directory a git repo: {"Yes" if is_git_repo else "No"}
71
+ Platform: {platform_name}
72
+ OS Version: {os_version}
73
+ Today's date: {today}
74
+ </env>"""
75
+ ).strip()
76
+
77
+
78
+ def _include_co_authored_signature() -> bool:
79
+ flag = os.getenv("INCLUDE_CO_AUTHORED_BY")
80
+ if flag is None:
81
+ return True
82
+ return flag.strip().lower() not in {"0", "false", "no"}
83
+
84
+
85
+ def get_git_signature() -> Dict[str, str]:
86
+ """Return commit/PR signatures for Coding Agent."""
87
+ if not _include_co_authored_signature():
88
+ return {"commit": "", "pr": ""}
89
+
90
+ signature = "Generated with Ripperdoc"
91
+ return {
92
+ "commit": f"{signature}\n\n Co-Authored-By: Ripperdoc",
93
+ "pr": signature,
94
+ }
95
+
96
+
97
+ def build_commit_workflow_prompt(
98
+ bash_tool_name: str, todo_tool_name: str, task_tool_name: str
99
+ ) -> str:
100
+ """Build instructions for committing and creating pull requests."""
101
+ signatures = get_git_signature()
102
+ commit_signature = signatures.get("commit") or ""
103
+ pr_signature = signatures.get("pr") or ""
104
+
105
+ commit_message_suffix = "."
106
+ if commit_signature:
107
+ commit_message_suffix = f" ending with:\n {commit_signature}"
108
+
109
+ commit_heredoc_signature = f"\n\n {commit_signature}" if commit_signature else ""
110
+ pr_signature_block = f"\n\n{pr_signature}" if pr_signature else ""
111
+
112
+ return dedent(
113
+ f"""\
114
+ # Committing changes with git
115
+
116
+ When the user asks you to create a new git commit, follow these steps carefully:
117
+
118
+ 1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel, each using the {bash_tool_name} tool:
119
+ - Run a git status command to see all untracked files.
120
+ - Run a git diff command to see both staged and unstaged changes that will be committed.
121
+ - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
122
+ 2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:
123
+ - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.).
124
+ - Check for any sensitive information that shouldn't be committed
125
+ - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
126
+ - Ensure it accurately reflects the changes and their purpose
127
+ 3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
128
+ - Add relevant untracked files to the staging area.
129
+ - Create the commit with a message{commit_message_suffix}
130
+ - Run git status to make sure the commit succeeded.
131
+ 4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
132
+
133
+ Important notes:
134
+ - NEVER update the git config
135
+ - NEVER run additional commands to read or explore code, besides git bash commands
136
+ - NEVER use the {todo_tool_name} or {task_tool_name} tools
137
+ - DO NOT push to the remote repository unless the user explicitly asks you to do so
138
+ - IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
139
+ - If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
140
+ - In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
141
+ <example>
142
+ git commit -m "$(cat <<'EOF'
143
+ Commit message here.{commit_heredoc_signature}
144
+ EOF
145
+ )"
146
+ </example>
147
+
148
+ # Creating pull requests
149
+ Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
150
+
151
+ IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
152
+
153
+ 1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel using the {bash_tool_name} tool, in order to understand the current state of the branch since it diverged from the main branch:
154
+ - Run a git status command to see all untracked files
155
+ - Run a git diff command to see both staged and unstaged changes that will be committed
156
+ - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
157
+ - Run a git log command and `git diff [base-branch]...HEAD` to understand the full commit history for the current branch (from the time it diverged from the base branch)
158
+ 2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary
159
+ 3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
160
+ - Create new branch if needed
161
+ - Push to remote with -u flag if needed
162
+ - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
163
+ <example>
164
+ gh pr create --title "the pr title" --body "$(cat <<'EOF'
165
+ ## Summary
166
+ <1-3 bullet points>
167
+
168
+ ## Test plan
169
+ [Checklist of TODOs for testing the pull request...]{pr_signature_block}
170
+ EOF
171
+ )"
172
+ </example>
173
+
174
+ Important:
175
+ - NEVER update the git config
176
+ - DO NOT use the {todo_tool_name} or {task_tool_name} tools
177
+ - Return the PR URL when you're done, so the user can see it
178
+
179
+ # Other common operations
180
+ - View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments"""
181
+ ).strip()
182
+
183
+
184
+ def build_system_prompt(
185
+ tools: List[Tool[Any, Any]],
186
+ user_prompt: str = "",
187
+ context: Optional[Dict[str, str]] = None,
188
+ additional_instructions: Optional[Iterable[str]] = None,
189
+ mcp_instructions: Optional[str] = None,
190
+ ) -> str:
191
+ _ = user_prompt, context
192
+ tool_names = {tool.name for tool in tools}
193
+ todo_tool_name = TODO_WRITE_TOOL_NAME
194
+ todo_available = todo_tool_name in tool_names
195
+ task_available = TASK_TOOL_NAME in tool_names
196
+ ask_tool_name = ASK_USER_QUESTION_TOOL_NAME
197
+ ask_available = ask_tool_name in tool_names
198
+ view_tool_name = VIEW_TOOL_NAME
199
+ file_edit_tool_name = FILE_EDIT_TOOL_NAME
200
+ file_write_tool_name = FILE_WRITE_TOOL_NAME
201
+ shell_tool_name = next(
202
+ (tool.name for tool in tools if tool.name.lower() == BASH_TOOL_NAME.lower()),
203
+ BASH_TOOL_NAME,
204
+ )
205
+
206
+ main_prompt = dedent(
207
+ f"""\
208
+ You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
209
+
210
+ {DEFENSIVE_SECURITY_GUIDELINE}
211
+ IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
212
+
213
+ If the user asks for help or wants to give feedback inform them of the following:
214
+ - /help: Get help with using {APP_NAME}
215
+ - To give feedback, users should report the issue at {FEEDBACK_URL}
216
+
217
+ # Looking up your own documentation
218
+ When the user asks what {APP_NAME} can do, how to use it (hooks, slash commands, MCP, SDKs), or requests SDK code samples, use the {TASK_TOOL_NAME} tool with a documentation-focused subagent (for example, subagent_type="docs") if available to consult official docs before answering.
219
+
220
+ # Tone and style
221
+ - Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
222
+ - Your output will be displayed on a command line interface. Your responses should be short and concise. You can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
223
+ - Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like {BASH_TOOL_NAME} or code comments as means to communicate with the user during the session.
224
+ - NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. This includes markdown files.
225
+
226
+ # Professional objectivity
227
+ Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if you honestly apply the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs. Avoid using over-the-top validation or excessive praise when responding to users such as "You're absolutely right" or similar phrases.
228
+
229
+ # Planning without timelines
230
+ When planning tasks, provide concrete implementation steps without time estimates. Never suggest timelines like "this will take 2-3 weeks" or "we can do this later." Focus on what needs to be done, not when. Break work into actionable steps and let users decide scheduling.
231
+
232
+ # Explain Your Code: Bash Command Transparency
233
+ When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
234
+ Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
235
+ If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
236
+
237
+ # Proactiveness
238
+ You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
239
+ - Doing the right thing when asked, including taking actions and follow-up actions
240
+ - Not surprising the user with actions you take without asking
241
+ For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
242
+
243
+ # Following conventions
244
+ When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
245
+ - NEVER assume that a given library is available, even if it is well known. Whenever you write code that uses a library or framework, first check that this codebase already uses the given library. For example, you might look at neighboring files, or check the package.json (or cargo.toml, and so on depending on the language).
246
+ - When you create a new component, first look at existing components to see how they're written; then consider framework choice, naming conventions, typing, and other conventions.
247
+ - When you edit a piece of code, first look at the code's surrounding context (especially its imports) to understand the code's choice of frameworks and libraries. Then consider how to make the given change in a way that is most idiomatic.
248
+ - Always follow security best practices. Never introduce code that exposes or logs secrets and keys. Never commit secrets or keys to the repository.
249
+
250
+ # Code style
251
+ - Only add comments when the logic is not self-evident and within code you changed. Do not add docstrings, comments, or type annotations to code you did not modify."""
252
+ ).strip()
253
+
254
+ if mcp_instructions:
255
+ main_prompt += "\n\n# MCP\n" + mcp_instructions.strip()
256
+
257
+ task_management_section = ""
258
+ if todo_available:
259
+ task_management_section = dedent(
260
+ f"""\
261
+ # Task Management
262
+ You have access to the {todo_tool_name} tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
263
+ These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
264
+
265
+ It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
266
+
267
+ Examples:
268
+
269
+ <example>
270
+ user: Run the build and fix any type errors
271
+ assistant: I'm going to use the {todo_tool_name} tool to write the following items to the todo list:
272
+ - Run the build
273
+ - Fix any type errors
274
+
275
+ I'm now going to run the build using {shell_tool_name}.
276
+
277
+ Looks like I found 10 type errors. I'm going to use the {todo_tool_name} tool to write 10 items to the todo list.
278
+
279
+ marking the first todo as in_progress
280
+
281
+ Let me start working on the first item...
282
+
283
+ The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
284
+ ..
285
+ ..
286
+ </example>
287
+ In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.
288
+
289
+ <example>
290
+ user: Help me write a new feature that allows users to track their usage metrics and export them to various formats
291
+
292
+ assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the {todo_tool_name} tool to plan this task.
293
+ Adding the following todos to the todo list:
294
+ 1. Research existing metrics tracking in the codebase
295
+ 2. Design the metrics collection system
296
+ 3. Implement core metrics tracking functionality
297
+ 4. Create export functionality for different formats
298
+
299
+ Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.
300
+
301
+ I'm going to search for any existing metrics or telemetry code in the project.
302
+
303
+ I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...
304
+
305
+ [Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
306
+ </example>"""
307
+ ).strip()
308
+
309
+ ask_questions_section = ""
310
+ if ask_available:
311
+ ask_questions_section = dedent(
312
+ f"""\
313
+ # Asking questions as you work
314
+
315
+ You have access to the {ask_tool_name} tool to ask the user questions when you need clarification, want to validate assumptions, or need to make a decision you're unsure about. When presenting options or plans, do not include time estimates—focus on what each option involves."""
316
+ ).strip()
317
+
318
+ hooks_section = dedent(
319
+ """\
320
+ Users may configure 'hooks', shell commands that execute in response to events like tool calls, in settings. Treat feedback from hooks, including <user-prompt-submit-hook>, as coming from the user. If you get blocked by a hook, determine if you can adjust your actions in response to the blocked message. If not, ask the user to check their hooks configuration."""
321
+ ).strip()
322
+
323
+ doing_tasks_lines = [
324
+ "# Doing tasks",
325
+ "The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:",
326
+ ]
327
+ if todo_available:
328
+ doing_tasks_lines.append(f"- Use the {todo_tool_name} tool to plan the task if required")
329
+ if ask_available:
330
+ doing_tasks_lines.append(
331
+ f"- Use the {ask_tool_name} tool to ask questions, clarify, and gather information as needed."
332
+ )
333
+ doing_tasks_lines.extend(
334
+ [
335
+ "- NEVER propose changes to code you haven't read. If a user asks about or wants you to modify a file, read it first.",
336
+ "- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.",
337
+ "- When exploring the codebase beyond a needle query, prefer using the Task tool with an exploration subagent if available instead of running raw search commands directly.",
338
+ "- Implement the solution using all tools available to you.",
339
+ "- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities. If you notice that you wrote insecure code, immediately fix it.",
340
+ "- Avoid over-engineering. Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.",
341
+ " - Don't add features, refactor code, or make improvements beyond what was asked. Don't add docstrings, comments, or type annotations to code you didn't change. Only add comments where the logic isn't self-evident.",
342
+ " - Don't add error handling, fallbacks, or validation for scenarios that can't happen. Validate only at system boundaries (user input, external APIs).",
343
+ " - Don't create helpers, utilities, or abstractions for one-time operations. Avoid feature flags or backwards-compatibility shims when a direct change is sufficient. If something is unused, delete it completely.",
344
+ "- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.",
345
+ f"- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with {shell_tool_name} if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.",
346
+ "NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.",
347
+ "- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.",
348
+ "- The conversation has unlimited context through automatic summarization. Complete tasks fully; do not stop mid-task or claim context limits.",
349
+ ]
350
+ )
351
+ doing_tasks_section = "\n".join(doing_tasks_lines)
352
+
353
+ tool_usage_lines = [
354
+ "# Tool usage policy",
355
+ '- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.',
356
+ "- If the user asks to run tools in parallel and there are no dependencies, include multiple tool calls in a single message; sequence dependent calls instead of guessing values.",
357
+ f"- Use specialized tools instead of bash when possible: use {view_tool_name} for reading files, {file_edit_tool_name} for editing, and {file_write_tool_name} for creating files. Do not use bash echo or other command-line tools to communicate with the user; reply in text.",
358
+ "You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.",
359
+ ]
360
+ if task_available:
361
+ tool_usage_lines.insert(
362
+ 1,
363
+ "- Use the Task tool with configured subagents when the task matches an agent's description. Always set subagent_type.",
364
+ )
365
+ if TOOL_SEARCH_TOOL_NAME in tool_names:
366
+ tool_usage_lines.insert(
367
+ 1,
368
+ "- Use the ToolSearch tool to discover and activate deferred or MCP tools. Keep searches focused and load only 3-5 relevant tools.",
369
+ )
370
+ tool_usage_section = "\n".join(tool_usage_lines)
371
+
372
+ always_use_todo = ""
373
+ if todo_available:
374
+ always_use_todo = f"IMPORTANT: Always use the {todo_tool_name} tool to plan and track tasks throughout the conversation."
375
+
376
+ agent_section = ""
377
+ if task_available:
378
+ clear_agent_cache()
379
+ try:
380
+ agent_definitions = load_agent_definitions()
381
+ if agent_definitions.active_agents:
382
+ agent_lines = "\n".join(
383
+ summarize_agent(agent) for agent in agent_definitions.active_agents
384
+ )
385
+ agent_section = dedent(
386
+ f"""\
387
+ # Subagents
388
+ Use the Task tool to delegate work to a specialized agent. Set `subagent_type` to one of:
389
+ {agent_lines}
390
+
391
+ Provide detailed prompts so the agent can work autonomously and return a concise report."""
392
+ ).strip()
393
+ except (OSError, ValueError, RuntimeError) as exc:
394
+ logger.warning(
395
+ "Failed to load agent definitions: %s: %s",
396
+ type(exc).__name__, exc,
397
+ )
398
+ agent_section = (
399
+ "# Subagents\nTask tool available, but agent definitions could not be loaded."
400
+ )
401
+
402
+ code_references = dedent(
403
+ """\
404
+ # Code References
405
+
406
+ When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
407
+
408
+ <example>
409
+ user: Where are errors from the client handled?
410
+ assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
411
+ </example>"""
412
+ ).strip()
413
+
414
+ sections: List[str] = [
415
+ main_prompt,
416
+ task_management_section,
417
+ ask_questions_section,
418
+ hooks_section,
419
+ doing_tasks_section,
420
+ tool_usage_section,
421
+ agent_section,
422
+ build_environment_prompt(),
423
+ always_use_todo,
424
+ build_commit_workflow_prompt(shell_tool_name, todo_tool_name, TASK_TOOL_NAME),
425
+ code_references,
426
+ ]
427
+
428
+ if additional_instructions:
429
+ sections.extend([text for text in additional_instructions if text])
430
+
431
+ return "\n\n".join(section for section in sections if section.strip())
ripperdoc/core/tool.py ADDED
@@ -0,0 +1,240 @@
1
+ """Base Tool interface for Ripperdoc.
2
+
3
+ This module provides the abstract base class for all tools in the system.
4
+ Tools are the primary way that the AI agent interacts with the environment.
5
+ """
6
+
7
+ import json
8
+ from abc import ABC, abstractmethod
9
+ from typing import Annotated, Any, AsyncGenerator, Dict, List, Optional, TypeVar, Generic, Union
10
+ from pydantic import BaseModel, ConfigDict, Field, SkipValidation
11
+ from ripperdoc.utils.file_watch import FileSnapshot
12
+ from ripperdoc.utils.log import get_logger
13
+
14
+
15
+ logger = get_logger()
16
+
17
+
18
+ class ToolResult(BaseModel):
19
+ """Result from a tool execution."""
20
+
21
+ type: str = "result"
22
+ data: Any
23
+ result_for_assistant: Optional[str] = None
24
+
25
+
26
+ class ToolProgress(BaseModel):
27
+ """Progress update from a tool execution."""
28
+
29
+ type: str = "progress"
30
+ content: Any
31
+ normalized_messages: list = []
32
+ tools: list = []
33
+
34
+
35
+ class ToolUseContext(BaseModel):
36
+ """Context for tool execution."""
37
+
38
+ message_id: Optional[str] = None
39
+ agent_id: Optional[str] = None
40
+ safe_mode: bool = False
41
+ verbose: bool = False
42
+ permission_checker: Optional[Any] = None
43
+ read_file_timestamps: Dict[str, float] = Field(default_factory=dict)
44
+ # SkipValidation prevents Pydantic from copying the dict during validation,
45
+ # ensuring View/Read and Edit tools share the same cache instance
46
+ file_state_cache: Annotated[Dict[str, FileSnapshot], SkipValidation] = Field(default_factory=dict)
47
+ tool_registry: Optional[Any] = None
48
+ abort_signal: Optional[Any] = None
49
+ # UI control callbacks for tools that need user interaction
50
+ pause_ui: Optional[Any] = Field(default=None, description="Callback to pause UI spinner")
51
+ resume_ui: Optional[Any] = Field(default=None, description="Callback to resume UI spinner")
52
+ # Plan mode control callback
53
+ on_exit_plan_mode: Optional[Any] = Field(
54
+ default=None, description="Callback invoked when exiting plan mode"
55
+ )
56
+ model_config = ConfigDict(arbitrary_types_allowed=True)
57
+
58
+
59
+ class ValidationResult(BaseModel):
60
+ """Result of input validation."""
61
+
62
+ result: bool
63
+ message: Optional[str] = None
64
+ error_code: Optional[int] = None
65
+ meta: Optional[Dict[str, Any]] = None
66
+
67
+
68
+ class ToolUseExample(BaseModel):
69
+ """Example of how to call a tool to guide the model."""
70
+
71
+ example: Dict[str, Any] = Field(validation_alias="input")
72
+ description: Optional[str] = None
73
+ model_config = ConfigDict(
74
+ validate_by_alias=True,
75
+ validate_by_name=True,
76
+ serialization_aliases={"example": "input"}, # type: ignore[typeddict-item]
77
+ )
78
+
79
+
80
+ TInput = TypeVar("TInput", bound=BaseModel)
81
+ TOutput = TypeVar("TOutput")
82
+ ToolOutput = Union[ToolResult, ToolProgress]
83
+
84
+
85
+ class Tool(ABC, Generic[TInput, TOutput]):
86
+ """Abstract base class for all tools.
87
+
88
+ Each tool must implement the core methods for describing itself,
89
+ validating input, and executing the tool's functionality.
90
+ """
91
+
92
+ def __init__(self) -> None:
93
+ self._name = self.__class__.__name__
94
+
95
+ @property
96
+ @abstractmethod
97
+ def name(self) -> str:
98
+ """Get the tool's name."""
99
+ pass
100
+
101
+ @abstractmethod
102
+ async def description(self) -> str:
103
+ """Get the tool's description for the AI model."""
104
+ pass
105
+
106
+ @property
107
+ @abstractmethod
108
+ def input_schema(self) -> type[BaseModel]:
109
+ """Get the Pydantic model for input validation."""
110
+ pass
111
+
112
+ @abstractmethod
113
+ async def prompt(self, safe_mode: bool = False) -> str:
114
+ """Get the system prompt for this tool."""
115
+ pass
116
+
117
+ def user_facing_name(self) -> str:
118
+ """Get the user-facing name of the tool."""
119
+ return self.name
120
+
121
+ async def is_enabled(self) -> bool:
122
+ """Check if this tool is enabled."""
123
+ return True
124
+
125
+ def is_read_only(self) -> bool:
126
+ """Check if this tool only reads data (doesn't modify state)."""
127
+ return False
128
+
129
+ def is_concurrency_safe(self) -> bool:
130
+ """Check if this tool can be run concurrently with others."""
131
+ return self.is_read_only()
132
+
133
+ def needs_permissions(self, input_data: Optional[TInput] = None) -> bool:
134
+ """Check if this tool needs permission to execute."""
135
+ return not self.is_read_only()
136
+
137
+ def defer_loading(self) -> bool:
138
+ """Whether this tool should be omitted from the initial tool list.
139
+
140
+ Deferred tools can be surfaced later via tool search to save tokens
141
+ when there are many available tools.
142
+ """
143
+ return False
144
+
145
+ def input_examples(self) -> List[ToolUseExample]:
146
+ """Optional examples that demonstrate correct tool usage."""
147
+ return []
148
+
149
+ async def validate_input(
150
+ self, input_data: TInput, context: Optional[ToolUseContext] = None
151
+ ) -> ValidationResult:
152
+ """Validate the input before execution."""
153
+ return ValidationResult(result=True)
154
+
155
+ @abstractmethod
156
+ def render_result_for_assistant(self, output: TOutput) -> str:
157
+ """Render the tool output for the AI assistant."""
158
+ pass
159
+
160
+ @abstractmethod
161
+ def render_tool_use_message(self, input_data: TInput, verbose: bool = False) -> str:
162
+ """Render the tool use message for display."""
163
+ pass
164
+
165
+ @abstractmethod
166
+ async def call(
167
+ self, input_data: TInput, context: ToolUseContext
168
+ ) -> AsyncGenerator[ToolOutput, None]:
169
+ """Execute the tool with the given input.
170
+
171
+ Yields progress updates and finally the result.
172
+ """
173
+ pass
174
+ # This is an abstract method, subclasses must implement
175
+ yield ToolResult(data=None) # type: ignore
176
+
177
+
178
+ def create_tool_schema(tool: Tool[Any, Any]) -> Dict[str, Any]:
179
+ """Create a JSON schema for the tool that can be sent to the AI model."""
180
+ return {
181
+ "name": tool.name,
182
+ "description": "", # Will be populated async
183
+ "input_schema": tool.input_schema.model_json_schema(),
184
+ }
185
+
186
+
187
+ async def build_tool_description(
188
+ tool: Tool[Any, Any], *, include_examples: bool = False, max_examples: int = 3
189
+ ) -> str:
190
+ """Return the tool description with optional input examples appended."""
191
+
192
+ description_text = await tool.description()
193
+
194
+ if not include_examples:
195
+ return description_text
196
+
197
+ examples = tool.input_examples()
198
+ if not examples:
199
+ return description_text
200
+
201
+ try:
202
+ parts = []
203
+ for idx, example in enumerate(examples[:max_examples], start=1):
204
+ payload = json.dumps(example.example, ensure_ascii=False, indent=2)
205
+ prefix = f"{idx}."
206
+ if example.description:
207
+ parts.append(f"{prefix} {example.description}\n{payload}")
208
+ else:
209
+ parts.append(f"{prefix} {payload}")
210
+
211
+ if parts:
212
+ return f"{description_text}\n\nInput examples:\n" + "\n\n".join(parts)
213
+ except (TypeError, ValueError, AttributeError, KeyError) as exc:
214
+ logger.warning(
215
+ "[tool] Failed to build input example section: %s: %s",
216
+ type(exc).__name__, exc,
217
+ extra={"tool": getattr(tool, "name", None)},
218
+ )
219
+ return description_text
220
+
221
+ return description_text
222
+
223
+
224
+ def tool_input_examples(tool: Tool[Any, Any], limit: int = 5) -> List[Dict[str, Any]]:
225
+ """Return raw input example objects formatted for the model."""
226
+ results: List[Dict[str, Any]] = []
227
+ examples = tool.input_examples()
228
+ if not examples:
229
+ return results
230
+ for example in examples[:limit]:
231
+ try:
232
+ results.append(example.example)
233
+ except (TypeError, ValueError, AttributeError) as exc:
234
+ logger.warning(
235
+ "[tool] Failed to format tool input example: %s: %s",
236
+ type(exc).__name__, exc,
237
+ extra={"tool": getattr(tool, "name", None)},
238
+ )
239
+ continue
240
+ return results