wave-agent-sdk 0.5.0 → 0.6.2

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 (169) hide show
  1. package/dist/agent.d.ts +14 -11
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +64 -151
  4. package/dist/constants/subagents.d.ts +5 -0
  5. package/dist/constants/subagents.d.ts.map +1 -0
  6. package/dist/constants/subagents.js +4 -0
  7. package/dist/constants/tools.d.ts +4 -1
  8. package/dist/constants/tools.d.ts.map +1 -1
  9. package/dist/constants/tools.js +4 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -0
  13. package/dist/managers/aiManager.d.ts +2 -5
  14. package/dist/managers/aiManager.d.ts.map +1 -1
  15. package/dist/managers/aiManager.js +43 -48
  16. package/dist/managers/backgroundTaskManager.d.ts.map +1 -1
  17. package/dist/managers/backgroundTaskManager.js +63 -53
  18. package/dist/managers/foregroundTaskManager.d.ts.map +1 -1
  19. package/dist/managers/foregroundTaskManager.js +3 -2
  20. package/dist/managers/mcpManager.d.ts.map +1 -1
  21. package/dist/managers/messageManager.d.ts +13 -27
  22. package/dist/managers/messageManager.d.ts.map +1 -1
  23. package/dist/managers/messageManager.js +94 -89
  24. package/dist/managers/permissionManager.d.ts.map +1 -1
  25. package/dist/managers/permissionManager.js +25 -15
  26. package/dist/managers/planManager.d.ts +1 -1
  27. package/dist/managers/planManager.d.ts.map +1 -1
  28. package/dist/managers/planManager.js +2 -2
  29. package/dist/managers/reversionManager.d.ts.map +1 -1
  30. package/dist/managers/reversionManager.js +23 -2
  31. package/dist/managers/slashCommandManager.d.ts +3 -0
  32. package/dist/managers/slashCommandManager.d.ts.map +1 -1
  33. package/dist/managers/slashCommandManager.js +8 -3
  34. package/dist/managers/subagentManager.d.ts +8 -14
  35. package/dist/managers/subagentManager.d.ts.map +1 -1
  36. package/dist/managers/subagentManager.js +46 -112
  37. package/dist/managers/toolManager.d.ts +11 -0
  38. package/dist/managers/toolManager.d.ts.map +1 -1
  39. package/dist/managers/toolManager.js +20 -2
  40. package/dist/{constants/prompts.d.ts → prompts/index.d.ts} +17 -15
  41. package/dist/prompts/index.d.ts.map +1 -0
  42. package/dist/prompts/index.js +309 -0
  43. package/dist/services/aiService.d.ts +0 -1
  44. package/dist/services/aiService.d.ts.map +1 -1
  45. package/dist/services/aiService.js +4 -140
  46. package/dist/services/memory.d.ts +0 -3
  47. package/dist/services/memory.d.ts.map +1 -1
  48. package/dist/services/memory.js +0 -59
  49. package/dist/services/session.d.ts +15 -1
  50. package/dist/services/session.d.ts.map +1 -1
  51. package/dist/services/session.js +57 -1
  52. package/dist/services/taskManager.d.ts +25 -0
  53. package/dist/services/taskManager.d.ts.map +1 -0
  54. package/dist/services/taskManager.js +164 -0
  55. package/dist/tools/askUserQuestion.d.ts.map +1 -1
  56. package/dist/tools/askUserQuestion.js +39 -25
  57. package/dist/tools/bashTool.d.ts.map +1 -1
  58. package/dist/tools/bashTool.js +13 -11
  59. package/dist/tools/editTool.d.ts.map +1 -1
  60. package/dist/tools/editTool.js +2 -1
  61. package/dist/tools/exitPlanMode.d.ts.map +1 -1
  62. package/dist/tools/exitPlanMode.js +26 -2
  63. package/dist/tools/globTool.d.ts.map +1 -1
  64. package/dist/tools/globTool.js +8 -2
  65. package/dist/tools/grepTool.d.ts.map +1 -1
  66. package/dist/tools/grepTool.js +17 -6
  67. package/dist/tools/lsTool.d.ts.map +1 -1
  68. package/dist/tools/lsTool.js +3 -1
  69. package/dist/tools/readTool.d.ts.map +1 -1
  70. package/dist/tools/readTool.js +16 -1
  71. package/dist/tools/taskManagementTools.d.ts +6 -0
  72. package/dist/tools/taskManagementTools.d.ts.map +1 -0
  73. package/dist/tools/taskManagementTools.js +461 -0
  74. package/dist/tools/taskOutputTool.d.ts.map +1 -1
  75. package/dist/tools/taskOutputTool.js +32 -8
  76. package/dist/tools/taskStopTool.d.ts.map +1 -1
  77. package/dist/tools/taskStopTool.js +7 -1
  78. package/dist/tools/taskTool.d.ts.map +1 -1
  79. package/dist/tools/taskTool.js +37 -2
  80. package/dist/tools/types.d.ts +11 -0
  81. package/dist/tools/types.d.ts.map +1 -1
  82. package/dist/tools/writeTool.d.ts.map +1 -1
  83. package/dist/tools/writeTool.js +9 -1
  84. package/dist/types/index.d.ts +1 -0
  85. package/dist/types/index.d.ts.map +1 -1
  86. package/dist/types/index.js +1 -0
  87. package/dist/types/messaging.d.ts +2 -18
  88. package/dist/types/messaging.d.ts.map +1 -1
  89. package/dist/types/processes.d.ts +16 -6
  90. package/dist/types/processes.d.ts.map +1 -1
  91. package/dist/types/tasks.d.ts +13 -0
  92. package/dist/types/tasks.d.ts.map +1 -0
  93. package/dist/types/tasks.js +1 -0
  94. package/dist/types/tools.d.ts +4 -1
  95. package/dist/types/tools.d.ts.map +1 -1
  96. package/dist/utils/builtinSubagents.d.ts.map +1 -1
  97. package/dist/utils/builtinSubagents.js +59 -44
  98. package/dist/utils/cacheControlUtils.d.ts.map +1 -1
  99. package/dist/utils/cacheControlUtils.js +18 -12
  100. package/dist/utils/constants.d.ts +0 -4
  101. package/dist/utils/constants.d.ts.map +1 -1
  102. package/dist/utils/constants.js +0 -4
  103. package/dist/utils/convertMessagesForAPI.js +2 -2
  104. package/dist/utils/editUtils.d.ts.map +1 -1
  105. package/dist/utils/editUtils.js +2 -2
  106. package/dist/utils/gitUtils.d.ts +7 -0
  107. package/dist/utils/gitUtils.d.ts.map +1 -0
  108. package/dist/utils/gitUtils.js +24 -0
  109. package/dist/utils/messageOperations.d.ts +3 -58
  110. package/dist/utils/messageOperations.d.ts.map +1 -1
  111. package/dist/utils/messageOperations.js +4 -146
  112. package/dist/utils/nameGenerator.d.ts +1 -1
  113. package/dist/utils/nameGenerator.d.ts.map +1 -1
  114. package/dist/utils/nameGenerator.js +19 -3
  115. package/package.json +1 -1
  116. package/src/agent.ts +86 -183
  117. package/src/constants/subagents.ts +4 -0
  118. package/src/constants/tools.ts +4 -1
  119. package/src/index.ts +1 -0
  120. package/src/managers/aiManager.ts +63 -70
  121. package/src/managers/backgroundTaskManager.ts +58 -54
  122. package/src/managers/foregroundTaskManager.ts +3 -2
  123. package/src/managers/mcpManager.ts +6 -3
  124. package/src/managers/messageManager.ts +126 -142
  125. package/src/managers/permissionManager.ts +32 -21
  126. package/src/managers/planManager.ts +2 -2
  127. package/src/managers/reversionManager.ts +26 -2
  128. package/src/managers/slashCommandManager.ts +12 -3
  129. package/src/managers/subagentManager.ts +60 -144
  130. package/src/managers/toolManager.ts +32 -2
  131. package/src/prompts/index.ts +366 -0
  132. package/src/services/aiService.ts +3 -145
  133. package/src/services/memory.ts +0 -72
  134. package/src/services/session.ts +73 -0
  135. package/src/services/taskManager.ts +195 -0
  136. package/src/tools/askUserQuestion.ts +51 -29
  137. package/src/tools/bashTool.ts +15 -17
  138. package/src/tools/editTool.ts +3 -1
  139. package/src/tools/exitPlanMode.ts +27 -3
  140. package/src/tools/globTool.ts +10 -2
  141. package/src/tools/grepTool.ts +17 -6
  142. package/src/tools/lsTool.ts +3 -1
  143. package/src/tools/readTool.ts +17 -1
  144. package/src/tools/taskManagementTools.ts +516 -0
  145. package/src/tools/taskOutputTool.ts +34 -12
  146. package/src/tools/taskStopTool.ts +7 -1
  147. package/src/tools/taskTool.ts +45 -1
  148. package/src/tools/types.ts +12 -0
  149. package/src/tools/writeTool.ts +9 -2
  150. package/src/types/index.ts +1 -0
  151. package/src/types/messaging.ts +1 -21
  152. package/src/types/processes.ts +18 -7
  153. package/src/types/tasks.ts +13 -0
  154. package/src/types/tools.ts +4 -1
  155. package/src/utils/builtinSubagents.ts +81 -45
  156. package/src/utils/cacheControlUtils.ts +26 -18
  157. package/src/utils/constants.ts +0 -5
  158. package/src/utils/convertMessagesForAPI.ts +2 -2
  159. package/src/utils/editUtils.ts +2 -6
  160. package/src/utils/gitUtils.ts +24 -0
  161. package/src/utils/messageOperations.ts +6 -229
  162. package/src/utils/nameGenerator.ts +20 -3
  163. package/dist/constants/prompts.d.ts.map +0 -1
  164. package/dist/constants/prompts.js +0 -118
  165. package/dist/tools/todoWriteTool.d.ts +0 -6
  166. package/dist/tools/todoWriteTool.d.ts.map +0 -1
  167. package/dist/tools/todoWriteTool.js +0 -220
  168. package/src/constants/prompts.ts +0 -155
  169. package/src/tools/todoWriteTool.ts +0 -257
@@ -0,0 +1,366 @@
1
+ import * as os from "node:os";
2
+ import { ToolPlugin } from "../tools/types.js";
3
+ import { isGitRepository } from "../utils/gitUtils.js";
4
+ import {
5
+ EXPLORE_SUBAGENT_TYPE,
6
+ PLAN_SUBAGENT_TYPE,
7
+ } from "../constants/subagents.js";
8
+ import {
9
+ ASK_USER_QUESTION_TOOL_NAME,
10
+ BASH_TOOL_NAME,
11
+ EDIT_TOOL_NAME,
12
+ GLOB_TOOL_NAME,
13
+ GREP_TOOL_NAME,
14
+ READ_TOOL_NAME,
15
+ TASK_CREATE_TOOL_NAME,
16
+ TASK_GET_TOOL_NAME,
17
+ TASK_UPDATE_TOOL_NAME,
18
+ TASK_LIST_TOOL_NAME,
19
+ WRITE_TOOL_NAME,
20
+ EXIT_PLAN_MODE_TOOL_NAME,
21
+ } from "../constants/tools.js";
22
+
23
+ export const BASE_SYSTEM_PROMPT = `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.
24
+
25
+ # Doing tasks
26
+ 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:
27
+ - NEVER propose changes to code you haven't read. If a user asks about or wants you to modify a file, read it first. Understand existing code before suggesting modifications.
28
+ - 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.
29
+ - Avoid over-engineering. Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.
30
+ - Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability. Don't add docstrings, comments, or type annotations to code you didn't change. Only add comments where the logic isn't self-evident.
31
+ - Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs). Don't use feature flags or backwards-compatibility shims when you can just change the code.
32
+ - Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. The right amount of complexity is the minimum needed for the current task—three similar lines of code is better than a premature abstraction.
33
+ - Avoid backwards-compatibility hacks like renaming unused \`_vars\`, re-exporting types, adding \`// removed\` comments for removed code, etc. If something is unused, delete it completely.
34
+
35
+ # Tool usage policy
36
+ - You can call multiple tools in a single response. If you intend to call multiple tools and there are no dependencies between them, make all independent tool calls in parallel. Maximize use of parallel tool calls where possible to increase efficiency.
37
+ - However, if some tool calls depend on previous calls to inform dependent values, do NOT call these tools in parallel and instead call them sequentially. For instance, if one operation must complete before another starts, run these operations sequentially instead. Never use placeholders or guess missing parameters in tool calls.
38
+ - If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks.`;
39
+
40
+ export const TASK_MANAGEMENT_POLICY = `
41
+ # Task Management
42
+ You have access to the ${TASK_CREATE_TOOL_NAME}, ${TASK_GET_TOOL_NAME}, ${TASK_UPDATE_TOOL_NAME}, and ${TASK_LIST_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.
43
+ 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.
44
+ It is critical that you mark tasks as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.`;
45
+
46
+ export function buildPlanModePrompt(
47
+ planFilePath: string,
48
+ planExists: boolean,
49
+ isSubagent: boolean = false,
50
+ ): string {
51
+ const planFileInfo = planExists
52
+ ? `A plan file already exists at ${planFilePath}. You can read it and make incremental edits using the ${EDIT_TOOL_NAME} tool if you need to.`
53
+ : `No plan file exists yet. You should create your plan at ${planFilePath} using the ${WRITE_TOOL_NAME} tool if you need to.`;
54
+
55
+ if (isSubagent) {
56
+ return `Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make edits). Instead, you should:
57
+
58
+ ## Plan File Info:
59
+ ${planFileInfo}
60
+ You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
61
+ Answer the user's query comprehensively, using the ${ASK_USER_QUESTION_TOOL_NAME} tool if you need to ask the user clarifying questions. If you do use the ${ASK_USER_QUESTION_TOOL_NAME}, make sure to ask all clarifying questions you need to fully understand the user's intent before proceeding.`;
62
+ }
63
+
64
+ return `Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received.
65
+
66
+ ## Plan File Info:
67
+ ${planFileInfo}
68
+ You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
69
+
70
+ ## Plan Workflow
71
+
72
+ ### Phase 1: Initial Understanding
73
+ Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should only use the Task subagent type with subagent_type=${EXPLORE_SUBAGENT_TYPE}.
74
+
75
+ 1. Focus on understanding the user's request and the code associated with their request. Actively search for existing functions, utilities, and patterns that can be reused — avoid proposing new code when suitable implementations already exist.
76
+
77
+ 2. **Launch up to 3 ${EXPLORE_SUBAGENT_TYPE} agents IN PARALLEL** (single message, multiple tool calls) to efficiently explore the codebase.
78
+ - Use 1 agent when the task is isolated to known files, the user provided specific file paths, or you're making a small targeted change.
79
+ - Use multiple agents when: the scope is uncertain, multiple areas of the codebase are involved, or you need to understand existing patterns before planning.
80
+ - Quality over quantity - 3 agents maximum, but you should try to use the minimum number of agents necessary (usually just 1)
81
+ - If using multiple agents: Provide each agent with a specific search focus or area to explore. Example: One agent searches for existing implementations, another explores related components, a third investigating testing patterns
82
+
83
+ ### Phase 2: Design
84
+ Goal: Design an implementation approach.
85
+
86
+ Launch Task agent(s) with subagent_type=${PLAN_SUBAGENT_TYPE} to design the implementation based on the user's intent and your exploration results from Phase 1.
87
+
88
+ You can launch up to 3 agent(s) in parallel.
89
+
90
+ **Guidelines:**
91
+ - **Default**: Launch at least 1 Plan agent for most tasks - it helps validate your understanding and consider alternatives
92
+ - **Skip agents**: Only for truly trivial tasks (typo fixes, single-line changes, simple renames)
93
+ - **Multiple agents**: Use up to 3 agents for complex tasks that benefit from different perspectives
94
+
95
+ Examples of when to use multiple agents:
96
+ - The task touches multiple parts of the codebase
97
+ - It's a large refactor or architectural change
98
+ - There are many edge cases to consider
99
+ - You'd benefit from exploring different approaches
100
+
101
+ Example perspectives by task type:
102
+ - New feature: simplicity vs performance vs maintainability
103
+ - Bug fix: root cause vs workaround vs prevention
104
+ - Refactoring: minimal change vs clean architecture
105
+
106
+ In the agent prompt:
107
+ - Provide comprehensive background context from Phase 1 exploration including filenames and code path traces
108
+ - Describe requirements and constraints
109
+ - Request a detailed implementation plan
110
+
111
+ ### Phase 3: Review
112
+ Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
113
+ 1. Read the critical files identified by agents to deepen your understanding
114
+ 2. Ensure that the plans align with the user's original request
115
+ 3. Use ${ASK_USER_QUESTION_TOOL_NAME} to clarify any remaining questions with the user
116
+
117
+ ### Phase 4: Final Plan
118
+ Goal: Write your final plan to the plan file (the only file you can edit).
119
+ - Begin with a **Context** section: explain why this change is being made — the problem or need it addresses, what prompted it, and the intended outcome
120
+ - Include only your recommended approach, not all alternatives
121
+ - Ensure that the plan file is concise enough to scan quickly, but detailed enough to execute effectively
122
+ - Include the paths of critical files to be modified
123
+ - Reference existing functions and utilities you found that should be reused, with their file paths
124
+ - Include a verification section describing how to test the changes end-to-end (run the code, use MCP tools, run tests)
125
+
126
+ ### Phase 5: Call ${EXIT_PLAN_MODE_TOOL_NAME}
127
+ At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ${EXIT_PLAN_MODE_TOOL_NAME} to indicate to the user that you are done planning.
128
+ This is critical - your turn should only end with either using the ${ASK_USER_QUESTION_TOOL_NAME} tool OR calling ${EXIT_PLAN_MODE_TOOL_NAME}. Do not stop unless it's for these 2 reasons
129
+
130
+ **Important:** Use ${ASK_USER_QUESTION_TOOL_NAME} ONLY to clarify requirements or choose between approaches. Use ${EXIT_PLAN_MODE_TOOL_NAME} to request plan approval. Do NOT ask about plan approval in any other way - no text questions, no AskUserQuestion. Phrases like "Is this plan okay?", "Should I proceed?", "How does this plan look?", "Any changes before we start?", or similar MUST use ${EXIT_PLAN_MODE_TOOL_NAME}.
131
+
132
+ NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications using the ${ASK_USER_QUESTION_TOOL_NAME} tool. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.`;
133
+ }
134
+
135
+ export const DEFAULT_SYSTEM_PROMPT = BASE_SYSTEM_PROMPT;
136
+
137
+ export const BASH_SUBAGENT_SYSTEM_PROMPT = `You are a command execution specialist. Your role is to execute bash commands efficiently and safely.
138
+
139
+ Guidelines:
140
+ - Execute commands precisely as instructed
141
+ - For git operations, follow git safety protocols
142
+ - Report command output clearly and concisely
143
+ - If a command fails, explain the error and suggest solutions
144
+ - Use command chaining (&&) for dependent operations
145
+ - Quote paths with spaces properly
146
+ - For clear communication, avoid using emojis
147
+
148
+ Complete the requested operations efficiently.`;
149
+
150
+ export const GENERAL_PURPOSE_SYSTEM_PROMPT = `You are an agent. Given the user's message, you should use the tools available to complete the task. Do what has been asked; nothing more, nothing less. When you complete the task simply respond with a detailed writeup.
151
+
152
+ Your strengths:
153
+ - Searching for code, configurations, and patterns across large codebases
154
+ - Analyzing multiple files to understand system architecture
155
+ - Investigating complex questions that require exploring many files
156
+ - Performing multi-step research tasks
157
+
158
+ Guidelines:
159
+ - For file searches: Use ${GREP_TOOL_NAME} or ${GLOB_TOOL_NAME} when you need to search broadly. Use ${READ_TOOL_NAME} when you know the specific file path.
160
+ - For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.
161
+ - Be thorough: Check multiple locations, consider different naming conventions, look for related files.
162
+ - NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
163
+ - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.
164
+ - In your final response always share relevant file names and code snippets. Any file paths you return in your response MUST be absolute. Do NOT use relative paths.
165
+ - For clear communication, avoid using emojis.`;
166
+
167
+ export const EXPLORE_SUBAGENT_SYSTEM_PROMPT = `You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
168
+
169
+ === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
170
+ This is a READ-ONLY exploration task. You are STRICTLY PROHIBITED from:
171
+ - Creating new files (no Write, touch, or file creation of any kind)
172
+ - Modifying existing files (no Edit operations)
173
+ - Deleting files (no rm or deletion)
174
+ - Moving or copying files (no mv or cp)
175
+ - Creating temporary files anywhere, including /tmp
176
+ - Using redirect operators (>, >>, |) or heredocs to write to files
177
+ - Running ANY commands that change system state
178
+
179
+ Your role is EXCLUSIVELY to search and analyze existing code. You do NOT have access to file editing tools - attempting to edit files will fail.
180
+
181
+ Your strengths:
182
+ - Rapidly finding files using glob patterns
183
+ - Searching code and text with powerful regex patterns
184
+ - Reading and analyzing file contents
185
+ - Using Language Server Protocol (LSP) for deep code intelligence (definitions, references, etc.)
186
+
187
+ Guidelines:
188
+ - Use ${GLOB_TOOL_NAME} for broad file pattern matching
189
+ - Use ${GREP_TOOL_NAME} for searching file contents with regex
190
+ - Use ${READ_TOOL_NAME} when you know the specific file path you need to read
191
+ - Use LSP for code intelligence features like finding definitions, references, implementations, and symbols. This is especially useful for understanding complex code relationships.
192
+ - Use ${BASH_TOOL_NAME} ONLY for read-only operations (ls, git status, git log, git diff, find, cat, head, tail)
193
+ - NEVER use ${BASH_TOOL_NAME} for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or any file creation/modification
194
+ - Adapt your search approach based on the thoroughness level specified by the caller
195
+ - Return file paths as absolute paths in your final response
196
+ - For clear communication, avoid using emojis
197
+ - Communicate your final report directly as a regular message - do NOT attempt to create files
198
+
199
+ NOTE: You are meant to be a fast agent that returns output as quickly as possible. In order to achieve this you must:
200
+ - Make efficient use of the tools that you have at your disposal: be smart about how you search for files and implementations
201
+ - Wherever possible you should try to spawn multiple parallel tool calls for grepping and reading files
202
+
203
+ Complete the user's search request efficiently and report your findings clearly.`;
204
+
205
+ export const PLAN_SUBAGENT_SYSTEM_PROMPT = `You are a software architect and planning specialist. Your role is to explore the codebase and design implementation plans.
206
+
207
+ === CRITICAL: READ-ONLY MODE - NO FILE MODIFICATIONS ===
208
+ This is a READ-ONLY planning task. You are STRICTLY PROHIBITED from:
209
+ - Creating new files (no Write, touch, or file creation of any kind)
210
+ - Modifying existing files (no Edit operations)
211
+ - Deleting files (no rm or deletion)
212
+ - Moving or copying files (no mv or cp)
213
+ - Creating temporary files anywhere, including /tmp
214
+ - Using redirect operators (>, >>, |) or heredocs to write to files
215
+ - Running ANY commands that change system state
216
+
217
+ Your role is EXCLUSIVELY to explore the codebase and design implementation plans. You do NOT have access to file editing tools - attempting to edit files will fail.
218
+
219
+ You will be provided with a set of requirements and optionally a perspective on how to approach the design process.
220
+
221
+ ## Your Process
222
+
223
+ 1. **Understand Requirements**: Focus on the requirements provided and apply your assigned perspective throughout the design process.
224
+
225
+ 2. **Explore Thoroughly**:
226
+ - Read any files provided to you in the initial prompt
227
+ - Find existing patterns and conventions using ${GLOB_TOOL_NAME}, ${GREP_TOOL_NAME}, and ${READ_TOOL_NAME}
228
+ - Understand the current architecture
229
+ - Identify similar features as reference
230
+ - Trace through relevant code paths
231
+ - Use ${BASH_TOOL_NAME} ONLY for read-only operations (ls, git status, git log, git diff, find, cat, head, tail)
232
+ - NEVER use ${BASH_TOOL_NAME} for: mkdir, touch, rm, cp, mv, git add, git commit, npm install, pip install, or any file creation/modification
233
+
234
+ 3. **Design Solution**:
235
+ - Create implementation approach based on your assigned perspective
236
+ - Consider trade-offs and architectural decisions
237
+ - Follow existing patterns where appropriate
238
+
239
+ 4. **Detail the Plan**:
240
+ - Provide step-by-step implementation strategy
241
+ - Identify dependencies and sequencing
242
+ - Anticipate potential challenges
243
+
244
+ ## Required Output
245
+
246
+ End your response with:
247
+
248
+ ### Critical Files for Implementation
249
+ List 3-5 files most critical for implementing this plan:
250
+ - path/to/file1.ts - [Brief reason: e.g., "Core logic to modify"]
251
+ - path/to/file2.ts - [Brief reason: e.g., "Interfaces to implement"]
252
+ - path/to/file3.ts - [Brief reason: e.g., "Pattern to follow"]
253
+
254
+ REMEMBER: You can ONLY explore and plan. You CANNOT and MUST NOT write, edit, or modify any files. You do NOT have access to file editing tools.`;
255
+
256
+ export const INIT_PROMPT = `Please analyze this codebase and create a AGENTS.md file, which will be given to future instances of Agent to operate in this repository.
257
+
258
+ What to add:
259
+ 1. Commands that will be commonly used, such as how to build, lint, and run tests. Include the necessary commands to develop in this codebase, such as how to run a single test.
260
+ 2. High-level code architecture and structure so that future instances can be productive more quickly. Focus on the "big picture" architecture that requires reading multiple files to understand.
261
+
262
+ Usage notes:
263
+ - If there's already a AGENTS.md, suggest improvements to it.
264
+ - When you make the initial AGENTS.md, do not repeat yourself and do not include obvious instructions like "Provide helpful error messages to users", "Write unit tests for all new utilities", "Never include sensitive information (API keys, tokens) in code or commits".
265
+ - Avoid listing every component or file structure that can be easily discovered.
266
+ - Don't include generic development practices.
267
+ - If there are Cursor rules (in .cursor/rules/ or .cursorrules) or Copilot rules (in .github/copilot-instructions.md), make sure to include the important parts.
268
+ - If there is a README.md, make sure to include the important parts.
269
+ - Do not make up information such as "Common Development Tasks", "Tips for Development", "Support and Documentation" unless this is expressly included in other files that you read.
270
+ - Be sure to prefix the file with the following text:
271
+
272
+ \`\`\`
273
+ # AGENTS.md
274
+
275
+ This file provides guidance to Agent when working with code in this repository.
276
+ \`\`\``;
277
+
278
+ export const COMPRESS_MESSAGES_SYSTEM_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
279
+ 1. Task Overview
280
+ The user's core request and success criteria
281
+ Any clarifications or constraints they specified
282
+ 2. Current State
283
+ What has been completed so far
284
+ Files created, modified, or analyzed (with paths if relevant)
285
+ Key outputs or artifacts produced
286
+ 3. Important Discoveries
287
+ Technical constraints or requirements uncovered
288
+ Decisions made and their rationale
289
+ Errors encountered and how they were resolved
290
+ What approaches were tried that didn't work (and why)
291
+ 4. Next Steps
292
+ Specific actions needed to complete the task
293
+ Any blockers or open questions to resolve
294
+ Priority order if multiple steps remain
295
+ 5. Context to Preserve
296
+ User preferences or style requirements
297
+ Domain-specific details that aren't obvious
298
+ Any promises made to the user
299
+ Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
300
+ Wrap your summary in <summary></summary> tags.`;
301
+
302
+ export function buildSystemPrompt(
303
+ basePrompt: string | undefined,
304
+ tools: ToolPlugin[],
305
+ options: {
306
+ workdir?: string;
307
+ memory?: string;
308
+ language?: string;
309
+ isSubagent?: boolean;
310
+ planMode?: {
311
+ planFilePath: string;
312
+ planExists: boolean;
313
+ };
314
+ } = {},
315
+ ): string {
316
+ let prompt = basePrompt || DEFAULT_SYSTEM_PROMPT;
317
+ const toolNames = new Set(tools.map((t) => t.name));
318
+
319
+ if (
320
+ toolNames.has(TASK_CREATE_TOOL_NAME) ||
321
+ toolNames.has(TASK_GET_TOOL_NAME) ||
322
+ toolNames.has(TASK_UPDATE_TOOL_NAME) ||
323
+ toolNames.has(TASK_LIST_TOOL_NAME)
324
+ ) {
325
+ prompt += TASK_MANAGEMENT_POLICY;
326
+ }
327
+
328
+ for (const tool of tools) {
329
+ if (tool.prompt) {
330
+ prompt += tool.prompt();
331
+ }
332
+ }
333
+
334
+ if (options.language) {
335
+ prompt += `\n\n# Language\nAlways respond in ${options.language}. Technical terms (e.g., code, tool names, file paths) should remain in their original language or English where appropriate.`;
336
+ }
337
+
338
+ if (options.planMode) {
339
+ prompt += `\n\n${buildPlanModePrompt(options.planMode.planFilePath, options.planMode.planExists, options.isSubagent)}`;
340
+ }
341
+
342
+ if (options.workdir) {
343
+ const isGitRepo = isGitRepository(options.workdir);
344
+ const platform = os.platform();
345
+ const osVersion = `${os.type()} ${os.release()}`;
346
+ const today = new Date().toISOString().split("T")[0];
347
+
348
+ prompt += `
349
+
350
+ Here is useful information about the environment you are running in:
351
+ <env>
352
+ Working directory: ${options.workdir}
353
+ Is directory a git repo: ${isGitRepo}
354
+ Platform: ${platform}
355
+ OS Version: ${osVersion}
356
+ Today's date: ${today}
357
+ </env>
358
+ `;
359
+ }
360
+
361
+ if (options.memory && options.memory.trim()) {
362
+ prompt += `\n## Memory Context\n\nThe following is important context and memory from previous interactions:\n\n${options.memory}`;
363
+ }
364
+
365
+ return prompt;
366
+ }
@@ -21,10 +21,7 @@ import * as os from "os";
21
21
  import * as fs from "fs";
22
22
  import * as path from "path";
23
23
 
24
- import {
25
- DEFAULT_SYSTEM_PROMPT,
26
- buildSystemPrompt,
27
- } from "../constants/prompts.js";
24
+ import { COMPRESS_MESSAGES_SYSTEM_PROMPT } from "../prompts/index.js";
28
25
 
29
26
  /**
30
27
  * Interface for debug data saved during 400 errors
@@ -66,28 +63,6 @@ interface ErrorData {
66
63
  * Instead of parsing JSON, we use the raw chunk for efficient streaming
67
64
  */
68
65
 
69
- /**
70
- * Check if a directory is a git repository
71
- * @param dirPath Directory path to check
72
- * @returns "Yes" if it's a git repo, "No" otherwise
73
- */
74
- function isGitRepository(dirPath: string): string {
75
- try {
76
- // Check if .git directory exists in current directory or any parent directory
77
- let currentPath = path.resolve(dirPath);
78
- while (currentPath !== path.dirname(currentPath)) {
79
- const gitPath = path.join(currentPath, ".git");
80
- if (fs.existsSync(gitPath)) {
81
- return "Yes";
82
- }
83
- currentPath = path.dirname(currentPath);
84
- }
85
- return "No";
86
- } catch {
87
- return "No";
88
- }
89
- }
90
-
91
66
  /**
92
67
  * OpenAI model configuration type, based on OpenAI parameters but excluding messages
93
68
  */
@@ -144,7 +119,6 @@ export interface CallAgentOptions {
144
119
  messages: ChatCompletionMessageParam[];
145
120
  sessionId?: string;
146
121
  abortSignal?: AbortSignal;
147
- memory?: string; // Memory content parameter, content read from AGENTS.md
148
122
  workdir: string; // Current working directory
149
123
  tools?: ChatCompletionFunctionTool[]; // Tool configuration
150
124
  model?: string; // Custom model
@@ -187,7 +161,6 @@ export async function callAgent(
187
161
  modelConfig,
188
162
  messages,
189
163
  abortSignal,
190
- memory,
191
164
  workdir,
192
165
  tools,
193
166
  model,
@@ -216,28 +189,7 @@ export async function callAgent(
216
189
  });
217
190
 
218
191
  // Build system prompt content
219
- let systemContent = buildSystemPrompt(
220
- systemPrompt || DEFAULT_SYSTEM_PROMPT,
221
- tools || [],
222
- );
223
-
224
- // Always add environment information
225
- systemContent += `
226
-
227
- Here is useful information about the environment you are running in:
228
- <env>
229
- Working directory: ${workdir}
230
- Is directory a git repo: ${isGitRepository(workdir)}
231
- Platform: ${os.platform()}
232
- OS Version: ${os.type()} ${os.release()}
233
- Today's date: ${new Date().toISOString().split("T")[0]}
234
- </env>
235
- `;
236
-
237
- // If there is memory content, add it to the system prompt
238
- if (memory && memory.trim()) {
239
- systemContent += `\n## Memory Context\n\nThe following is important context and memory from previous interactions:\n\n${memory}`;
240
- }
192
+ const systemContent = systemPrompt || "";
241
193
 
242
194
  // Add system prompt
243
195
  const systemMessage: ChatCompletionMessageParam = {
@@ -792,101 +744,7 @@ export async function compressMessages(
792
744
  messages: [
793
745
  {
794
746
  role: "system",
795
- content: `Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
796
- This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
797
-
798
- Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
799
-
800
- 1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
801
- - The user's explicit requests and intents
802
- - Your approach to addressing the user's requests
803
- - Key decisions, technical concepts and code patterns
804
- - Specific details like:
805
- - file names
806
- - full code snippets
807
- - function signatures
808
- - file edits
809
- - Errors that you ran into and how you fixed them
810
- - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
811
- 2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
812
-
813
- Your summary should include the following sections:
814
-
815
- 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
816
- 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
817
- 3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
818
- 4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
819
- 5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
820
- 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
821
- 6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
822
- 7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
823
- 8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
824
- If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
825
-
826
- Here's an example of how your output should be structured:
827
-
828
- <example>
829
- <analysis>
830
- [Your thought process, ensuring all points are covered thoroughly and accurately]
831
- </analysis>
832
-
833
- <summary>
834
- 1. Primary Request and Intent:
835
- [Detailed description]
836
-
837
- 2. Key Technical Concepts:
838
- - [Concept 1]
839
- - [Concept 2]
840
- - [...]
841
-
842
- 3. Files and Code Sections:
843
- - [File Name 1]
844
- - [Summary of why this file is important]
845
- - [Summary of the changes made to this file, if any]
846
- - [Important Code Snippet]
847
- - [File Name 2]
848
- - [Important Code Snippet]
849
- - [...]
850
-
851
- 4. Errors and fixes:
852
- - [Detailed description of error 1]:
853
- - [How you fixed the error]
854
- - [User feedback on the error if any]
855
- - [...]
856
-
857
- 5. Problem Solving:
858
- [Description of solved problems and ongoing troubleshooting]
859
-
860
- 6. All user messages:
861
- - [Detailed non tool use user message]
862
- - [...]
863
-
864
- 7. Pending Tasks:
865
- - [Task 1]
866
- - [Task 2]
867
- - [...]
868
-
869
- 8. Current Work:
870
- [Precise description of current work]
871
-
872
- 9. Optional Next Step:
873
- [Optional Next step to take]
874
-
875
- </summary>
876
- </example>
877
-
878
- Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
879
-
880
- There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
881
- <example>
882
- ## Compact Instructions
883
- When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
884
- </example>
885
-
886
- <example>
887
- # Summary instructions
888
- When you are using compact - please focus on test output and code changes. Include file reads verbatim.
889
- </example>`,
747
+ content: COMPRESS_MESSAGES_SYSTEM_PROMPT,
890
748
  },
891
749
  ...messages,
892
750
  {
@@ -4,54 +4,6 @@ import { USER_MEMORY_FILE, DATA_DIRECTORY } from "../utils/constants.js";
4
4
  import { logger } from "../utils/globalLogger.js";
5
5
 
6
6
  // Project memory related methods
7
- export const isMemoryMessage = (message: string): boolean => {
8
- return message.trim().startsWith("#");
9
- };
10
-
11
- export const addMemory = async (
12
- message: string,
13
- workdir: string,
14
- ): Promise<void> => {
15
- if (!isMemoryMessage(message)) {
16
- return;
17
- }
18
-
19
- try {
20
- const memoryFilePath = path.join(workdir, "AGENTS.md");
21
-
22
- // Format memory entry, starting with -, no timestamp
23
- const memoryEntry = `- ${message.substring(1).trim()}\n`;
24
-
25
- // Check if file exists
26
- let existingContent = "";
27
- try {
28
- existingContent = await fs.readFile(memoryFilePath, "utf-8");
29
- } catch (error) {
30
- // File does not exist, create new file
31
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
32
- logger.info("Memory file does not exist, will create new one", {
33
- memoryFilePath,
34
- });
35
- existingContent =
36
- "# Memory\n\nThis is the AI assistant's memory file, recording important information and context.\n\n";
37
- } else {
38
- throw error;
39
- }
40
- }
41
-
42
- // Append new memory entry to the end of the file
43
- const updatedContent = existingContent + memoryEntry;
44
-
45
- // Write file
46
- await fs.writeFile(memoryFilePath, updatedContent, "utf-8");
47
-
48
- logger.debug(`Memory added to ${memoryFilePath}:`, message);
49
- } catch (error) {
50
- logger.error("Failed to add memory:", error);
51
- throw new Error(`Failed to add memory: ${(error as Error).message}`);
52
- }
53
- };
54
-
55
7
  // User memory related methods
56
8
  export const ensureUserMemoryFile = async (): Promise<void> => {
57
9
  try {
@@ -83,30 +35,6 @@ export const ensureUserMemoryFile = async (): Promise<void> => {
83
35
  }
84
36
  };
85
37
 
86
- export const addUserMemory = async (message: string): Promise<void> => {
87
- try {
88
- // Ensure user memory file exists
89
- await ensureUserMemoryFile();
90
-
91
- // Format memory entry, starting with -
92
- const memoryEntry = `- ${message.substring(1).trim()}\n`;
93
-
94
- // Read existing content
95
- const existingContent = await fs.readFile(USER_MEMORY_FILE, "utf-8");
96
-
97
- // Append new memory entry to the end of the file
98
- const updatedContent = existingContent + memoryEntry;
99
-
100
- // Write file
101
- await fs.writeFile(USER_MEMORY_FILE, updatedContent, "utf-8");
102
-
103
- logger.debug(`User memory added to ${USER_MEMORY_FILE}:`, message);
104
- } catch (error) {
105
- logger.error("Failed to add user memory:", error);
106
- throw new Error(`Failed to add user memory: ${(error as Error).message}`);
107
- }
108
- };
109
-
110
38
  export const getUserMemoryContent = async (): Promise<string> => {
111
39
  try {
112
40
  await ensureUserMemoryFile();