diff --git a/backend/knowledge.md b/backend/knowledge.md index 79bc8170f6..7cc45dab74 100644 --- a/backend/knowledge.md +++ b/backend/knowledge.md @@ -16,6 +16,7 @@ This document provides an overview of the Manicode backend architecture, key com 10. [Security Considerations](#security-considerations) 11. [TODO List](#todo-list) 12. [Automatic URL Detection and Scraping](#automatic-url-detection-and-scraping) +13. [Planning System](#planning-system) ## Architecture Overview @@ -194,3 +195,40 @@ This project uses Bun for testing instead of Jest. When writing tests, keep the - Bun's test API is similar to Jest's, but there are some differences in implementation. - When mocking methods, use `mock(object.method)` instead of Jest's `jest.spyOn(object, 'method')`. - Bun's `mock` function expects 0-1 arguments, not 2 like Jest's `spyOn`. + +## Plan Generation for Complex Requests + +The backend now includes a feature to generate plans for complex user requests. This feature is designed to break down complex tasks into manageable steps and include appropriate verification processes. + +Key components: +1. `check-plan-required.ts`: Determines if a plan is needed based on the complexity of the user's request. +2. `generate-plan.ts`: Creates a detailed plan with numbered steps and verification processes. +3. `main-prompt.ts`: Integrates plan generation into the main request handling flow. + +The plan generation process: +1. `main-prompt.ts` calls `checkIfPlanRequired()` to determine if a plan is needed. +2. If a plan is required, `generatePlan()` is called to create a detailed plan. +3. The generated plan is streamed to the client using the `onResponseChunk` function, providing real-time updates. +4. The plan includes numbered steps, sub-steps, and appropriate verification steps (e.g., running type checkers, creating and running unit tests). + +Important implementation details: +- The system prompt for plan generation is recreated to ensure it has the most up-to-date context. +- The warm cache call is only fired if no plan was required, optimizing performance by avoiding unnecessary caching when a plan is generated. + +This feature enhances the system's ability to handle complex requests systematically and with proper verification. When working on request handling or AI prompts, consider whether the request might benefit from this plan generation feature. + +## Planning System + +The agent system prompt now includes a section explaining the planning process. Key points: + +- The assistant is given a plan to implement for complex tasks. +- The assistant should implement one or more steps from the plan. +- After completing steps, the assistant reports progress using a specific format: + - Example: [STEP 1 COMPLETE] or [STEPS 2-4 COMPLETE] +- The progress report should not include the end token "[END]". + +This planning system allows for more structured and trackable task implementation, especially for complex requests. It provides clear checkpoints for both the assistant and the user to understand the progress of a given task. + +When implementing features or fixing bugs, consider whether the task would benefit from this structured planning approach, particularly for multi-step or complex changes to the codebase. + + diff --git a/backend/src/check-plan-required.ts b/backend/src/check-plan-required.ts new file mode 100644 index 0000000000..95bdd5cd6b --- /dev/null +++ b/backend/src/check-plan-required.ts @@ -0,0 +1,46 @@ +import { Message } from 'common/actions' +import { System } from './claude' +import { promptClaude } from './claude' +import { claudeModels } from 'common/constants' +import { logger } from './util/logger' + +export async function checkIfPlanRequired( + messages: Message[], + system: System, + clientSessionId: string, + fingerprintId: string, + userInputId: string, + userId?: string +): Promise { + const planCheckPrompt = ` +Given the user's request, determine if it requires a plan. A plan is needed if the request: +1. Requires at least 3 steps to complete +2. Is complex in nature +3. Requires verification of multiple parts + +Analyze the request and respond with just the string: +"[REQUIRES_PLAN]" if a plan is needed, or +"[PLAN_UNNECESSARY]" if a plan is not needed. + +Do not include any other text. + +User request: ${messages[messages.length - 1].content} +`.trim() + + const response = await promptClaude( + [...messages, { role: 'user', content: planCheckPrompt }], + { + model: claudeModels.sonnet, + system, + clientSessionId, + fingerprintId, + userInputId, + userId, + } + ) + + const requiresPlan = response.trim().includes('[REQUIRES_PLAN]') + logger.info({ response, requiresPlan }, 'Plan check response') + + return requiresPlan +} diff --git a/backend/src/generate-patch.ts b/backend/src/generate-patch.ts index db129ce653..a2d1fbcc41 100644 --- a/backend/src/generate-patch.ts +++ b/backend/src/generate-patch.ts @@ -88,7 +88,7 @@ ${newContent} Are there any comments in the sketch that indicate surrounding code should remain as it is in the original file? For example, comments like "// ... existing code ..." or "# .... rest of the function ...". If so, please write "YES". Otherwise, write "NO". If "YES", don't write anything else. -If "NO", please also consider the following question. In rare cases, the new content focuses on the change of a single function or section of code with the intention to edit just this section, but the assistant forgot to add placeholder comments above and below the section to indicate the rest of the file is preserved. Without these placeholder comments the sketch of the updated file is incomplete. One clue this is the case is if the new content is much shorter than the original file. If they are about the same length, the sketch is probably complete and does not require modification. +If "NO", please also consider the following question. In rare cases, the new content focuses on the change of a single function or section of code with the intention to edit just this section, but the assistant forgot to add placeholder comments above and below the section to indicate the rest of the file is preserved. Without these placeholder comments the sketch of the updated file is incomplete. One clue this is the case is if the new content is just a single function whereas the original file has multiple functions. If you strongly believe this is the scenario, please write "INCOMPLETE_SKETCH". Otherwise (most likely), write "COMPLETE_SKETCH". `.trim() diff --git a/backend/src/generate-plan.ts b/backend/src/generate-plan.ts new file mode 100644 index 0000000000..22fdca1b45 --- /dev/null +++ b/backend/src/generate-plan.ts @@ -0,0 +1,55 @@ +import { Message } from 'common/actions' +import { System } from './claude' +import { promptClaudeStream } from './claude' +import { claudeModels } from 'common/constants' + +export async function generatePlan( + messages: Message[], + system: System, + clientSessionId: string, + fingerprintId: string, + userInputId: string, + onResponseChunk: (chunk: string) => void, + userId?: string +): Promise { + const planGenerationPrompt = ` +Based on the user's request, create a detailed plan for the assistant to follow with numbered steps to accomplish the task. + +Please follow these guidelines: +1. Reduce the scope of the plan to the minimum necessary to accomplish the task. Try to avoid unnecessary steps and do not modify more files or run more terminal commands than absolutely necessary. +2. Break down the task into clear, actionable steps for the assistant to follow. The assistant can only edit files and run terminal commands as part of the plan. Do not include steps for the user to do. +3. Include appropriate verification steps along the way and at the end, such as running a command to do type checking and fixing errors, creating and running unit tests, or any other relevant checks. + +User request: ${messages[messages.length - 1].content} + +Please provide the plan in the following format: +1. [First step] +2. [Second step] + a. [Sub-step if necessary] + b. [Another sub-step if necessary] +3. [Verification step (if applicable)] +... + +Please start by telling the user you will create a plan to address their request. +` + + let fullPlan = '' + const stream = promptClaudeStream( + [...messages, { role: 'user', content: planGenerationPrompt }], + { + model: claudeModels.sonnet, + system, + clientSessionId, + fingerprintId, + userInputId, + userId, + } + ) + + for await (const chunk of stream) { + fullPlan += chunk + onResponseChunk(chunk) + } + + return fullPlan.trim() +} diff --git a/backend/src/main-prompt.ts b/backend/src/main-prompt.ts index b0bd3a58ea..8225d0e6a4 100644 --- a/backend/src/main-prompt.ts +++ b/backend/src/main-prompt.ts @@ -5,7 +5,12 @@ import { promptClaudeStream } from './claude' import { ProjectFileContext } from 'common/util/file' import { didClientUseTool } from 'common/util/tools' import { getSearchSystemPrompt, getAgentSystemPrompt } from './system-prompt' -import { STOP_MARKER, TOOL_RESULT_MARKER } from 'common/constants' +import { + PLAN_START_MARKER, + PLAN_STOP_MARKER, + STOP_MARKER, + TOOL_RESULT_MARKER, +} from 'common/constants' import { FileChange, Message } from 'common/actions' import { ToolCall } from 'common/actions' import { requestFiles, requestFile } from './websockets/websocket-action' @@ -18,6 +23,9 @@ import { processStreamWithTags } from './process-stream' import { generateKnowledgeFiles } from './generate-knowledge-files' import { countTokens } from './util/token-counter' import { logger } from './util/logger' +import { checkIfPlanRequired } from './check-plan-required' +import { generatePlan } from './generate-plan' +import { buildArray } from 'common/util/array' /** * Prompt claude, handle tool calls, and generate file changes. @@ -33,15 +41,28 @@ export async function mainPrompt( userId?: string ) { let fullResponse = '' + let continuedMessages: Message[] = fullResponse + ? [{ role: 'assistant', content: fullResponse }] + : [] let genKnowledgeFilesPromise: Promise[]> = Promise.resolve([]) const fileProcessingPromises: Promise[] = [] const lastMessage = messages[messages.length - 1] const messagesWithoutLastMessage = messages.slice(0, -1) + let isPlanInProgress = checkIfPlanInProgress(messages) - if (!didClientUseTool(lastMessage)) { + if (!didClientUseTool(lastMessage) && !isPlanInProgress) { // Step 1: Read more files. const system = getSearchSystemPrompt(fileContext) + + const planRequiredPromise = checkIfPlanRequired( + messages, + system, + clientSessionId, + fingerprintId, + userInputId, + userId + ) // If the fileContext.files is empty, use prompts to select files and add them to context. const responseChunk = await updateFileContext( ws, @@ -56,11 +77,42 @@ export async function mainPrompt( if (responseChunk !== null) { onResponseChunk(responseChunk.readFilesMessage) fullResponse += `\n\n${responseChunk.toolCallMessage}\n\n${responseChunk.readFilesMessage}` + } + + const updatedSystem = getSearchSystemPrompt(fileContext) + const planRequired = await planRequiredPromise + + if (planRequired) { + onResponseChunk('\n\n') + const plan = await generatePlan( + messages, + updatedSystem, + clientSessionId, + fingerprintId, + userInputId, + onResponseChunk, + userId + ) + fullResponse += plan.replaceAll(STOP_MARKER, '').trim() + fullResponse += `\n\n${PLAN_START_MARKER}` + onResponseChunk('\n\n') + continuedMessages = [ + { + role: 'assistant', + content: fullResponse, + }, + { + role: 'user', + content: 'Please execute the plan.', + }, + ] + logger.info({ plan }, 'Generated plan') + isPlanInProgress = true + } else { // Prompt cache the new files. - const system = getSearchSystemPrompt(fileContext) warmCacheForRequestRelevantFiles( - system, + updatedSystem, clientSessionId, fingerprintId, userInputId, @@ -98,7 +150,7 @@ export async function mainPrompt( const numAssistantMessages = messages .slice(lastUserMessageIndex) .filter((message) => message.role === 'assistant').length - const shouldPause = numAssistantMessages >= 3 + const shouldPause = numAssistantMessages >= 10 if (shouldPause) { const response = `\nI'll pause to get more instructions from the user.\n` onResponseChunk(response) @@ -110,9 +162,6 @@ export async function mainPrompt( } let toolCall: ToolCall | null = null - let continuedMessages: Message[] = fullResponse - ? [{ role: 'assistant', content: fullResponse }] - : [] let isComplete = false let iterationCount = 0 const MAX_ITERATIONS = 10 @@ -121,15 +170,20 @@ export async function mainPrompt( if (lastMessage.role === 'user' && typeof lastMessage.content === 'string') { newLastMessage = { ...lastMessage, - content: `${lastMessage.content} - - -Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested. Then pause to get more instructions from the user. - - + content: buildArray( + lastMessage.content, + ` +Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested.${isPlanInProgress ? '' : ' Then pause to get more instructions from the user.'} +`, + ` Always end your response with the following marker: ${STOP_MARKER} `, + isPlanInProgress && + ` + You should attempt to execute the entire plan. When the plan is complete or it is hard to make progress, end your response with the following marker: ${PLAN_STOP_MARKER} +` + ).join('\n\n'), } } @@ -247,6 +301,10 @@ ${STOP_MARKER} if (foundEndOfResponse) { fullResponse += '\n[END]' } + isPlanInProgress = checkIfPlanInProgress([ + ...messages, + { role: 'assistant', content: fullResponse }, + ]) const maybeToolCall = toolCall as ToolCall | null @@ -278,9 +336,18 @@ ${STOP_MARKER} } else if (maybeToolCall !== null) { isComplete = true logger.debug(maybeToolCall, 'tool call') - } else if (fullResponse.includes(STOP_MARKER)) { + } else if (isPlanInProgress && fullResponse.includes(STOP_MARKER)) { + toolCall = { + id: Math.random().toString(36).slice(2), + name: 'continue_plan', + input: {}, + } + isComplete = true + } else if ( + fullResponse.includes(STOP_MARKER) || + fullResponse.includes(PLAN_STOP_MARKER) + ) { isComplete = true - fullResponse = fullResponse.replace(STOP_MARKER, '') logger.debug('Reached STOP_MARKER') } else { logger.debug('Continuing to generate') @@ -321,6 +388,18 @@ ${STOP_MARKER} } } +function checkIfPlanInProgress(messages: Message[]): boolean { + const messagesString = JSON.stringify(messages) + const lastStartMarkerIndex = messagesString.lastIndexOf(PLAN_START_MARKER) + const lastStopMarkerIndex = messagesString.lastIndexOf(PLAN_STOP_MARKER) + + if (lastStartMarkerIndex === -1 && lastStopMarkerIndex === -1) { + return false + } + + return lastStartMarkerIndex > lastStopMarkerIndex +} + function getRelevantFileInfoMessage(filePaths: string[]) { const readFilesMessage = `Reading the following files...${filePaths.join(', ')}` const toolCallMessage = `Please find the files relevant to the user request` diff --git a/backend/src/system-prompt.ts b/backend/src/system-prompt.ts index d6b8d57ba5..ffc2f15b48 100644 --- a/backend/src/system-prompt.ts +++ b/backend/src/system-prompt.ts @@ -74,6 +74,7 @@ export const getAgentSystemPrompt = ( editingFilesPrompt, knowledgeFilesPrompt, toolsPrompt, + planningPrompt, // For large projects, don't include file tree in agent context. projectFileTreePrompt.length < 40_000 ? projectFileTreePrompt : null, getRelevantFilesPromptPart1(fileContext) @@ -112,6 +113,29 @@ You are assisting the user with one particular coding project to which you have If you are unsure about the answer to a user's question, you should say "I don't have enough information to confidently answer your question." If the scope of the change the user is requesting is too large to implement all at once (e.g. requires greater than 750 lines of code), you can tell the user the scope is too big and ask which sub-problem to focus on first. `.trim() +const planningPrompt = ` +# Planning and Implementation + +For complex tasks, you will be given a plan to implement. This plan will consist of numbered steps, and may include sub-steps. Your job is to implement these steps in order. + +When implementing the plan: +1. Focus on one or more steps at a time. +2. Make the necessary code changes to implement each step. +3. Do not be afraid to deviate from the plan where it makes sense to do so. If you do, please explain how you are deviating from the plan. +4. After completing one or more steps, indicate which steps you've completed using the format: "[STEP X COMPLETE]" or "[STEPS X-Y COMPLETE]". +5. Do not write any text after you signaled you completed some step(s). In particular, do not write "${STOP_MARKER}". + +Example: +After implementing steps 1 and 2 of a plan, you would write: +[STEPS 1-2 COMPLETE] + +Then stop. Do not output the "${STOP_MARKER}" marker. This helps track progress and allows for easier review of your work. + +If the plan is complete or you cannot make further progress on the plan, then at that point you should write "${STOP_MARKER}". + +Remember to be thorough but concise in your implementations, and always adhere to the project's coding standards and best practices. +`.trim() + const editingFilesPrompt = ` # Editing files @@ -391,7 +415,7 @@ Whenever you modify an exported token like a function or class or variable, you Confine your edits to only what is directly necessary. Preserve the behavior of all existing code. Change only what you must to accomplish the user's request or add to a knowledge file. -Always end your response with the following marker: +Always end your response with the following marker, unless you are on an intermediate step of a plan: ${STOP_MARKER} This marker helps ensure that your entire response has been received and processed correctly. diff --git a/common/src/constants.ts b/common/src/constants.ts index c0749d29a7..e23fb9aa76 100644 --- a/common/src/constants.ts +++ b/common/src/constants.ts @@ -1,4 +1,6 @@ export const STOP_MARKER = '[' + 'END]' +export const PLAN_STOP_MARKER = '[' + 'PLAN_END]' +export const PLAN_START_MARKER = '[' + 'PLAN_START]' export const FIND_FILES_MARKER = '[' + 'FIND_FILES_PLEASE]' export const TOOL_RESULT_MARKER = '[' + 'TOOL_RESULT]' @@ -35,6 +37,7 @@ export const SKIPPED_TERMINAL_COMMANDS = [ 'add', 'hey', 'diff', + 'make', ] export const MAX_DATE = new Date(86399999999999) diff --git a/common/src/project-file-tree.ts b/common/src/project-file-tree.ts index ac22cf8ab1..1696af7e2d 100644 --- a/common/src/project-file-tree.ts +++ b/common/src/project-file-tree.ts @@ -12,6 +12,7 @@ export function getProjectFileTree( const defaultIgnore = ignore.default() defaultIgnore.add('.git') defaultIgnore.add('*.min.*') + defaultIgnore.add('node_modules') if (projectRoot === os.homedir()) { defaultIgnore.add('.*') diff --git a/npm-app/src/client.ts b/npm-app/src/client.ts index e561444467..af78c23747 100644 --- a/npm-app/src/client.ts +++ b/npm-app/src/client.ts @@ -112,7 +112,10 @@ export class Client { const content = await handler(input, id) const toolResultMessage: Message = { role: 'user', - content: `${TOOL_RESULT_MARKER}\n${content}`, + content: `${TOOL_RESULT_MARKER}\n${content}`.replace( + 'continue_plan', + '' + ), } this.chatStorage.addMessage( this.chatStorage.getCurrentChat(), diff --git a/npm-app/src/tool-handlers.ts b/npm-app/src/tool-handlers.ts index 2a48c9f1ca..b4e2e8b423 100644 --- a/npm-app/src/tool-handlers.ts +++ b/npm-app/src/tool-handlers.ts @@ -135,4 +135,5 @@ export const toolHandlers: Record = { search_manifold_markets: handleSearchManifoldMarkets, run_terminal_command: ((input, id) => handleRunTerminalCommand(input, id, 'assistant')) as ToolHandler, + continue_plan: () => Promise.resolve('Please continue executing the plan.'), }