diff --git a/src/core/prompts/sections/capabilities.ts b/src/core/prompts/sections/capabilities.ts index 8a4d638..c46aba4 100644 --- a/src/core/prompts/sections/capabilities.ts +++ b/src/core/prompts/sections/capabilities.ts @@ -1,8 +1,11 @@ -const MatchSearchFilesInstructions = "\n- You can use match_search_files to perform fuzzy-based searches across files using keyword/phrase. This tool is ideal for finding similar texts in notes. It excels at finding similar contents with similar keywords and phrases quickly." +const MatchSearchFilesInstructions = `**Match Search**: Perform fuzzy-based searches across files using keywords/phrases +(\`match_search_files\`) to find similar texts and contents quickly.` -const RegexSearchFilesInstructions = "\n- You can use regex_search_files to perform pattern-based searches across files using regular expressions. This tool is ideal for finding exact text matches, specific patterns (like tags, links, dates, URLs), or structural elements in notes. It excels at locating precise format patterns and is perfect for finding connections between notes, frontmatter elements, or specific Markdown formatting." +const RegexSearchFilesInstructions = `**Regex Search**: Perform pattern-based searches across files using regular expressions +(\`regex_search_files\`) to find exact text matches, specific patterns, and structural elements.` -const SemanticSearchFilesInstructions = "\n- You can use semantic_search_files to find content based on meaning rather than exact text matches. Semantic search uses embedding vectors to understand concepts and ideas, finding relevant content even when keywords differ. This is especially powerful for discovering thematically related notes, answering conceptual questions about your knowledge base, or finding content when you don't know the exact wording used in the notes." +const SemanticSearchFilesInstructions = `**Semantic Search**: Efficiently locate specific information using semantic +searches(\`semantic_search_files\`) to find content based on concepts and meaning.` function getAskModeCapabilitiesSection( cwd: string, @@ -22,19 +25,13 @@ function getAskModeCapabilitiesSection( default: searchFilesInstructions = ""; } - return `==== + return `# Capabilities -CAPABILITIES - -You are equipped with four core capabilities that map directly to user intents: - -1. **Insight & Understanding**: Your most powerful capability. Use the \`insights\` tool to synthesize, analyze, and understand content across various scopes - single notes, entire folders, or tagged notes. - -2. **Lookup & Navigate**: Efficiently locate specific information using semantic searches (\`semantic_search_files\`) for concepts and structured queries (\`dataview_query\`) for metadata like tags or dates. - -3. **Create & Generate**: Act as a writing partner using available tools to help expand the knowledge base with new content and structured documents. - -4. **Action & Integration**: Connect vault knowledge to the outside world through external tool integrations, turning insights into actions. +- **Insight & Understanding**: Your most powerful capability. Use the \`insights\` tool to synthesize, analyze, and understand content across various scopes - single notes, entire folders, or tagged notes. +- ${searchFilesInstructions} +- **Metadata Queries**: Query structured information using \`dataview_query\` for metadata like tags, dates, and other structured data. +- **Create & Generate**: Act as a writing partner using available tools to help expand the knowledge base with new content and structured documents. +- **Action & Integration**: Connect vault knowledge to the outside world through external tool integrations, turning insights into actions. ` } diff --git a/src/core/prompts/sections/index.ts b/src/core/prompts/sections/index.ts index a9f8c9e..0930331 100644 --- a/src/core/prompts/sections/index.ts +++ b/src/core/prompts/sections/index.ts @@ -1,9 +1,10 @@ -export { getRulesSection } from "./rules" +export { getMandatesSection } from "./rules" export { getSystemInfoSection } from "./system-info" export { getObjectiveSection } from "./objective" export { addCustomInstructions } from "./custom-instructions" export { getSharedToolUseSection } from "./tool-use" export { getMcpServersSection } from "./mcp-servers" +export { getPrimaryWorkflowsSection } from "./primary-workflows" export { getToolUseGuidelinesSection } from "./tool-use-guidelines" export { getCapabilitiesSection } from "./capabilities" export { getModesSection } from "./modes" diff --git a/src/core/prompts/sections/primary-workflows.ts b/src/core/prompts/sections/primary-workflows.ts new file mode 100644 index 0000000..aa9a5f8 --- /dev/null +++ b/src/core/prompts/sections/primary-workflows.ts @@ -0,0 +1,50 @@ +function getAskPrimaryWorkflows(): string { + return ` +# Primary Workflow + +Your interaction with the user follows a structured -step workflow to ensure clarity, accuracy, and efficiency. + +1. **Understand:** First, analyze the user's request by carefully considering their task and its context. The goal is to identify their primary objective, which is key to selecting the best tools. + +2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. + +3. **Execute:** Use the available tools (e.g., \`insights\`, \`semantic_search_files\`, \`list_files\`, \`read_file\`, \`write_file\`, \`attempt_completion\`, ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates'). +`; +} + +function getWritePrimaryWorkflows(): string { + return ` +# Primary Workflows + +Your interaction with the user follows a structured workflow to ensure clarity and efficiency. You will use \`\`, \`\`, and tool calls to solve tasks. + +## Content Creation and Refactoring + +When asked to create, summarize, refactor, or analyze notes and other content, follow this sequence: + +1. **Understand:** Use search and read tools to gather context from the user's vault. Understand the topic, existing structure, and any relevant linked notes. Don't make assumptions; if something is unclear, read the relevant files. +2. **Plan:** Formulate a plan for the content generation or modification. For complex tasks, share a concise summary of your plan with the user before you start. For example: "I will read notes A and B, synthesize their key points, and create a new summary note in the 'Summaries' folder." +3. **Implement:** Use the available tools to draft or edit the content in a new or existing file. Adhere to the user's existing formatting and writing style (e.g., Markdown conventions, header levels). +4. **Verify:** Reread the generated or modified content. Check it against the source material and the user's original request to ensure accuracy, coherence, and completeness. + +## Vault Organization and Automation + +When asked to perform tasks like creating project structures, reorganizing files, or automating workflows, follow this sequence: + +1. **Understand Requirements:** Analyze the user's request to identify the core goal. What structure needs to be created? What process needs to be automated? Use file listing and search tools to understand the current state of the vault. If the request is ambiguous, ask targeted clarification questions. +2. **Propose & Plan:** Formulate a detailed plan. For any action that modifies multiple files or creates new files/folders, **you must first present the plan to the user for approval.** The plan should be clear and explicit about what will be created, moved, or modified. +3. **User Approval:** Wait for the user to approve the plan before proceeding. +4. **Implementation:** Execute the plan using file system tools carefully. +5. **Final Report:** After execution, report back to the user with a summary of the changes made. +`; +} + +export function getPrimaryWorkflowsSection(mode?: string): string { + if (mode === 'ask') { + return getAskPrimaryWorkflows(); + } + if (mode === 'write') { + return getWritePrimaryWorkflows(); + } + return ''; +} diff --git a/src/core/prompts/sections/rules.ts b/src/core/prompts/sections/rules.ts index 9cb6aae..a73adc8 100644 --- a/src/core/prompts/sections/rules.ts +++ b/src/core/prompts/sections/rules.ts @@ -75,20 +75,17 @@ function getAskModeRulesSection( cwd: string, searchTool: string, ): string { - return `==== + return `# Core Mandates -RULES OF ENGAGEMENT - -These are non-negotiable rules you must follow at all times. - -- **Vault-Grounded Responses**: Every answer must be grounded in the user's note contents. You are a knowledge vault researcher, not a general chatbot. -- **Cite Your Sources**: When your answer is based on vault content, you **MUST** use Obsidian-style [[WikiLinks]] to reference all source notes (e.g., \`[[folder / note name]]\`). -- **One Tool Per Turn**: You can only use one tool per message. -- **Your Directory**: Your current working directory is: / -- **Error Handling**: When tools fail, explain the issue and provide alternative approaches -- **Context Awareness**: Always consider vault structure and user's current context -- **Efficiency**: Minimize tool calls while maximizing information gathering, prioritize the most relevant tools -- **Your Directory**: Your current working directory is: ${cwd.toPosix()} +- **Adhere to Vault Conventions:** Strictly follow existing folder, naming, and tag conventions. Review relevant structure and context before modifying or creating notes. +- **Vault-Grounded Responses:** Every answer must be based on the user's notes—no speculation. +- **Cite Your Sources:** When referencing notes, use Obsidian-style [[WikiLinks]]. +- **One Tool per Turn:** Use at most one tool in each message, and only when necessary. +- **Error Handling:** If a tool call fails, explain the cause and propose alternatives. +- **Context Awareness:** Always account for vault structure and the user's current context. +- **Efficiency:** Minimize tool calls and prioritize the most relevant tool. +- **Proactive yet Restrained:** Reasonably infer and execute implicit steps, but seek confirmation before ambiguous or significant actions. +- **Outcome-Driven Communication:** Follow the "thinking → communication → execution" loop; do not add extra summaries unless the user requests them. ` } @@ -122,7 +119,7 @@ ${getEditingInstructions(mode)} - It is critical you wait for the user's response after each tool use, in order to confirm the success of the tool use. For example, if asked to create a structured note, you would create a file, wait for the user's response it was created successfully, then create another file if needed, wait for the user's response it was created successfully, etc.` } -export function getRulesSection( +export function getMandatesSection( mode: string, cwd: string, searchTool: string, diff --git a/src/core/prompts/sections/tool-use-guidelines.ts b/src/core/prompts/sections/tool-use-guidelines.ts index 5986fd7..19fac1e 100644 --- a/src/core/prompts/sections/tool-use-guidelines.ts +++ b/src/core/prompts/sections/tool-use-guidelines.ts @@ -1,49 +1,3 @@ -function getAskModeToolUseGuidelines(): string { - return `# STRATEGY & EXECUTION - -Your interaction with the user follows a structured workflow to ensure clarity and efficiency. You will use \`\`, \`\`, and tool calls to solve tasks. - -**1. The Thinking Phase (\`\`):** -The \`\` tag is used for analysis and planning. Use it ONLY in these scenarios: -* **Initial Task Planning**: When the user provides a new task, analyze the request and create a step-by-step plan. -* **Processing Feedback**: When the user provides feedback, analyze it and plan your next actions. -* **Re-planning after Failure**: If a tool call fails or produces unexpected results, analyze and create a revised plan. - -**2. The Communication Phase (\`\`):** -Keep the user informed about your progress: -* **After Planning**: Briefly inform the user of your plan before executing the first tool call. -* **After Tool Results**: Provide status updates explaining what the result was, how it helps, and what you will do next. - -**3. The Execution Phase (Tool Calls):** -Execute tool calls as defined in your plan. You can execute multiple tool calls in parallel if they are independent. - -**Example Workflow:** - -User Request: \`Compare file_A.md and file_B.md\` - -Your Response: -\`\`\` - -The user wants to compare two files. -**Plan:** -1. Read both files in parallel -2. Analyze differences and summarize -3. Present final comparison - - - -I will read both files to prepare a comparison for you. - - - -file_A.md - - - -file_B.md - -\`\`\``; -} function getLearnModeToolUseGuidelines(): string { return `# Tool Use Guidelines @@ -77,32 +31,22 @@ function getLearnModeToolUseGuidelines(): string { } function getDefaultToolUseGuidelines(): string { - return `# Tool Use Guidelines + return `# TOOL USE -## General Principles +You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use. -1. In tags, assess what information you already have and what information you need to proceed with the task. -2. Choose the most appropriate tool based on the task and the tool descriptions provided. Assess if you need additional information to proceed, and which of the available tools would be most effective for gathering this information. It's critical that you think about each available tool and use the one that best fits the current step in the task. -3. If multiple actions are needed, use one tool at a time per message to accomplish the task iteratively, with each tool use being informed by the result of the previous tool use. Do not assume the outcome of any tool use. Each step must be informed by the previous step's result. -4. Formulate your tool use using the XML format specified for each tool. -5. After each tool use, the user will respond with the result of that tool use. This result will provide you with the necessary information to continue your task or make further decisions. This response may include: - - Information about whether the tool succeeded or failed, along with any reasons for failure. - - Any other relevant feedback or information related to the tool use. -6. ALWAYS wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user. - -It is crucial to proceed step-by-step, waiting for the user's message after each tool use before moving forward with the task. This approach allows you to: -1. Confirm the success of each step before proceeding. -2. Address any issues or errors that arise immediately. -3. Adapt your approach based on new information or unexpected results. -4. Ensure that each action builds correctly on the previous ones. - -By waiting for and carefully considering the user's response after each tool use, you can react accordingly and make informed decisions about how to proceed with the task. This iterative process helps ensure the overall success and accuracy of your work.`; +## Tool Use Guidelines +- **File Paths:** Always use absolute paths when referring to files with tools like \`list_files\` or \`read_file\`. Relative paths are not supported. You must provide an absolute path. +- **Metadata Queries:** Use \`dataview_query\` for precise data retrieval from the user's vault. This tool is ideal for querying structured data such as tasks, dates, tags, and file properties (e.g., "show me all incomplete tasks in the 'Projects' folder"). +- **Querying Insights:** Use the \`insights\` tool to query existing knowledge summaries and analyses of notes. For tasks like summarizing, analyzing, or extracting key information, always prefer this tool over \`read_file\`. Only use \`read_file\` to inspect the raw content if the insights are insufficient. +- **Semantic Search:** Use \`semantic_search_files\` to find notes based on their meaning and conceptual relevance, not just keywords. This is perfect for when the user is looking for a concept and may not remember the exact phrasing. +- **Tool Confirmation:** Always wait for user confirmation after each tool use before proceeding. Never assume the success of a tool use without explicit confirmation of the result from the user. +- **Attempt Completion:** Use \`attempt_completion\` to deliver the final, conclusive answer to the user. +- **Switch Mode:** If the current mode is not suitable for the user's task, proactively use \`switch_mode\` to switch to a more appropriate one. +`; } export function getToolUseGuidelinesSection(mode?: string): string { - if (mode === 'ask') { - return getAskModeToolUseGuidelines(); - } if (mode === 'learn') { return getLearnModeToolUseGuidelines(); } diff --git a/src/core/prompts/sections/tool-use.ts b/src/core/prompts/sections/tool-use.ts index 8a2b910..3f7317c 100644 --- a/src/core/prompts/sections/tool-use.ts +++ b/src/core/prompts/sections/tool-use.ts @@ -1,11 +1,5 @@ export function getSharedToolUseSection(): string { - return `==== - -TOOL USE - -You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use. - -# Tool Use Formatting + return `## Tool Use Formatting Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and each parameter is similarly enclosed within its own set of tags. Here's the structure: diff --git a/src/core/prompts/system.ts b/src/core/prompts/system.ts index f607be5..8c48297 100644 --- a/src/core/prompts/system.ts +++ b/src/core/prompts/system.ts @@ -21,13 +21,12 @@ import { ROOT_DIR } from './constants' import { addCustomInstructions, getCapabilitiesSection, + getMandatesSection, getMcpServersSection, getModesSection, - getObjectiveSection, - getRulesSection, + getPrimaryWorkflowsSection, getSharedToolUseSection, - getSystemInfoSection, - getToolUseGuidelinesSection, + getToolUseGuidelinesSection } from "./sections" // import { loadSystemPromptFile } from "./sections/custom-system-prompt" import { getToolDescriptionsForMode } from "./tools" @@ -101,6 +100,19 @@ export class SystemPrompt { const basePrompt = `${roleDefinition} +${getMandatesSection( + mode, + cwd, + filesSearchMethod, + supportsComputerUse, + diffStrategy, + experiments, +)} + +${getPrimaryWorkflowsSection(mode)} + +${getToolUseGuidelinesSection(mode)} + ${getSharedToolUseSection()} ${getToolDescriptionsForMode( @@ -116,8 +128,6 @@ ${getToolDescriptionsForMode( experiments, )} -${getToolUseGuidelinesSection(mode)} - ${mcpServersSection} ${getCapabilitiesSection( @@ -128,15 +138,6 @@ ${getCapabilitiesSection( ${modesSection} -${getRulesSection( - mode, - cwd, - filesSearchMethod, - supportsComputerUse, - diffStrategy, - experiments, - )} - ${await addCustomInstructions(this.app, promptComponent?.customInstructions || modeConfig.customInstructions || "", globalCustomInstructions || "", cwd, mode, { preferredLanguage })}` return basePrompt