Prettier backfill

This commit is contained in:
Matt Rubens
2025-01-17 14:11:28 -05:00
parent 3bcb4ff8c5
commit 60a0a824b9
174 changed files with 15715 additions and 15428 deletions

View File

@@ -1,422 +1,357 @@
import { SYSTEM_PROMPT, addCustomInstructions } from '../system'
import { McpHub } from '../../../services/mcp/McpHub'
import { McpServer } from '../../../shared/mcp'
import { ClineProvider } from '../../../core/webview/ClineProvider'
import { SearchReplaceDiffStrategy } from '../../../core/diff/strategies/search-replace'
import fs from 'fs/promises'
import os from 'os'
import { defaultModeSlug, modes } from '../../../shared/modes'
import { SYSTEM_PROMPT, addCustomInstructions } from "../system"
import { McpHub } from "../../../services/mcp/McpHub"
import { McpServer } from "../../../shared/mcp"
import { ClineProvider } from "../../../core/webview/ClineProvider"
import { SearchReplaceDiffStrategy } from "../../../core/diff/strategies/search-replace"
import fs from "fs/promises"
import os from "os"
import { defaultModeSlug, modes } from "../../../shared/modes"
// Import path utils to get access to toPosix string extension
import '../../../utils/path'
import "../../../utils/path"
// Mock environment-specific values for consistent tests
jest.mock('os', () => ({
...jest.requireActual('os'),
homedir: () => '/home/user'
jest.mock("os", () => ({
...jest.requireActual("os"),
homedir: () => "/home/user",
}))
jest.mock('default-shell', () => '/bin/bash')
jest.mock("default-shell", () => "/bin/bash")
jest.mock('os-name', () => () => 'Linux')
jest.mock("os-name", () => () => "Linux")
// Mock fs.readFile to return empty mcpServers config and mock rules files
jest.mock('fs/promises', () => ({
...jest.requireActual('fs/promises'),
readFile: jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith('mcpSettings.json')) {
return '{"mcpServers": {}}'
}
if (path.endsWith('.clinerules-code')) {
return '# Code Mode Rules\n1. Code specific rule'
}
if (path.endsWith('.clinerules-ask')) {
return '# Ask Mode Rules\n1. Ask specific rule'
}
if (path.endsWith('.clinerules-architect')) {
return '# Architect Mode Rules\n1. Architect specific rule'
}
if (path.endsWith('.clinerules')) {
return '# Test Rules\n1. First rule\n2. Second rule'
}
return ''
}),
writeFile: jest.fn().mockResolvedValue(undefined)
jest.mock("fs/promises", () => ({
...jest.requireActual("fs/promises"),
readFile: jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith("mcpSettings.json")) {
return '{"mcpServers": {}}'
}
if (path.endsWith(".clinerules-code")) {
return "# Code Mode Rules\n1. Code specific rule"
}
if (path.endsWith(".clinerules-ask")) {
return "# Ask Mode Rules\n1. Ask specific rule"
}
if (path.endsWith(".clinerules-architect")) {
return "# Architect Mode Rules\n1. Architect specific rule"
}
if (path.endsWith(".clinerules")) {
return "# Test Rules\n1. First rule\n2. Second rule"
}
return ""
}),
writeFile: jest.fn().mockResolvedValue(undefined),
}))
// Create a minimal mock of ClineProvider
const mockProvider = {
ensureMcpServersDirectoryExists: async () => '/mock/mcp/path',
ensureSettingsDirectoryExists: async () => '/mock/settings/path',
postMessageToWebview: async () => {},
context: {
extension: {
packageJSON: {
version: '1.0.0'
}
}
}
ensureMcpServersDirectoryExists: async () => "/mock/mcp/path",
ensureSettingsDirectoryExists: async () => "/mock/settings/path",
postMessageToWebview: async () => {},
context: {
extension: {
packageJSON: {
version: "1.0.0",
},
},
},
} as unknown as ClineProvider
// Instead of extending McpHub, create a mock that implements just what we need
const createMockMcpHub = (): McpHub => ({
getServers: () => [],
getMcpServersPath: async () => '/mock/mcp/path',
getMcpSettingsFilePath: async () => '/mock/settings/path',
dispose: async () => {},
// Add other required public methods with no-op implementations
restartConnection: async () => {},
readResource: async () => ({ contents: [] }),
callTool: async () => ({ content: [] }),
toggleServerDisabled: async () => {},
toggleToolAlwaysAllow: async () => {},
isConnecting: false,
connections: []
} as unknown as McpHub)
const createMockMcpHub = (): McpHub =>
({
getServers: () => [],
getMcpServersPath: async () => "/mock/mcp/path",
getMcpSettingsFilePath: async () => "/mock/settings/path",
dispose: async () => {},
// Add other required public methods with no-op implementations
restartConnection: async () => {},
readResource: async () => ({ contents: [] }),
callTool: async () => ({ content: [] }),
toggleServerDisabled: async () => {},
toggleToolAlwaysAllow: async () => {},
isConnecting: false,
connections: [],
}) as unknown as McpHub
describe('SYSTEM_PROMPT', () => {
let mockMcpHub: McpHub
describe("SYSTEM_PROMPT", () => {
let mockMcpHub: McpHub
beforeEach(() => {
jest.clearAllMocks()
})
beforeEach(() => {
jest.clearAllMocks()
})
afterEach(async () => {
// Clean up any McpHub instances
if (mockMcpHub) {
await mockMcpHub.dispose()
}
})
afterEach(async () => {
// Clean up any McpHub instances
if (mockMcpHub) {
await mockMcpHub.dispose()
}
})
it('should maintain consistent system prompt', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false, // supportsComputerUse
undefined, // mcpHub
undefined, // diffStrategy
undefined // browserViewportSize
)
expect(prompt).toMatchSnapshot()
})
it("should maintain consistent system prompt", async () => {
const prompt = await SYSTEM_PROMPT(
"/test/path",
false, // supportsComputerUse
undefined, // mcpHub
undefined, // diffStrategy
undefined, // browserViewportSize
)
it('should include browser actions when supportsComputerUse is true', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
true,
undefined,
undefined,
'1280x800'
)
expect(prompt).toMatchSnapshot()
})
expect(prompt).toMatchSnapshot()
})
it('should include MCP server info when mcpHub is provided', async () => {
mockMcpHub = createMockMcpHub()
it("should include browser actions when supportsComputerUse is true", async () => {
const prompt = await SYSTEM_PROMPT("/test/path", true, undefined, undefined, "1280x800")
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
mockMcpHub
)
expect(prompt).toMatchSnapshot()
})
expect(prompt).toMatchSnapshot()
})
it('should explicitly handle undefined mcpHub', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
undefined, // explicitly undefined mcpHub
undefined,
undefined
)
expect(prompt).toMatchSnapshot()
})
it("should include MCP server info when mcpHub is provided", async () => {
mockMcpHub = createMockMcpHub()
it('should handle different browser viewport sizes', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
true,
undefined,
undefined,
'900x600' // different viewport size
)
expect(prompt).toMatchSnapshot()
})
const prompt = await SYSTEM_PROMPT("/test/path", false, mockMcpHub)
it('should include diff strategy tool description', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
undefined,
new SearchReplaceDiffStrategy(), // Use actual diff strategy from the codebase
undefined
)
expect(prompt).toMatchSnapshot()
})
expect(prompt).toMatchSnapshot()
})
afterAll(() => {
jest.restoreAllMocks()
})
it("should explicitly handle undefined mcpHub", async () => {
const prompt = await SYSTEM_PROMPT(
"/test/path",
false,
undefined, // explicitly undefined mcpHub
undefined,
undefined,
)
expect(prompt).toMatchSnapshot()
})
it("should handle different browser viewport sizes", async () => {
const prompt = await SYSTEM_PROMPT(
"/test/path",
true,
undefined,
undefined,
"900x600", // different viewport size
)
expect(prompt).toMatchSnapshot()
})
it("should include diff strategy tool description", async () => {
const prompt = await SYSTEM_PROMPT(
"/test/path",
false,
undefined,
new SearchReplaceDiffStrategy(), // Use actual diff strategy from the codebase
undefined,
)
expect(prompt).toMatchSnapshot()
})
afterAll(() => {
jest.restoreAllMocks()
})
})
describe('addCustomInstructions', () => {
beforeEach(() => {
jest.clearAllMocks()
})
describe("addCustomInstructions", () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('should generate correct prompt for architect mode', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
undefined,
undefined,
undefined,
'architect'
)
expect(prompt).toMatchSnapshot()
})
it("should generate correct prompt for architect mode", async () => {
const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "architect")
it('should generate correct prompt for ask mode', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
undefined,
undefined,
undefined,
'ask'
)
expect(prompt).toMatchSnapshot()
})
expect(prompt).toMatchSnapshot()
})
it('should prioritize mode-specific rules for code mode', async () => {
const instructions = await addCustomInstructions(
{},
'/test/path',
defaultModeSlug
)
expect(instructions).toMatchSnapshot()
})
it("should generate correct prompt for ask mode", async () => {
const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "ask")
it('should prioritize mode-specific rules for ask mode', async () => {
const instructions = await addCustomInstructions(
{},
'/test/path',
modes[2].slug
)
expect(instructions).toMatchSnapshot()
})
expect(prompt).toMatchSnapshot()
})
it('should prioritize mode-specific rules for architect mode', async () => {
const instructions = await addCustomInstructions(
{},
'/test/path',
modes[1].slug
)
expect(instructions).toMatchSnapshot()
})
it("should prioritize mode-specific rules for code mode", async () => {
const instructions = await addCustomInstructions({}, "/test/path", defaultModeSlug)
expect(instructions).toMatchSnapshot()
})
it('should prioritize mode-specific rules for test engineer mode', async () => {
// Mock readFile to include test engineer rules
const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith('.clinerules-test')) {
return '# Test Engineer Rules\n1. Always write tests first\n2. Get approval before modifying non-test code'
}
if (path.endsWith('.clinerules')) {
return '# Test Rules\n1. First rule\n2. Second rule'
}
return ''
})
jest.spyOn(fs, 'readFile').mockImplementation(mockReadFile)
it("should prioritize mode-specific rules for ask mode", async () => {
const instructions = await addCustomInstructions({}, "/test/path", modes[2].slug)
expect(instructions).toMatchSnapshot()
})
const instructions = await addCustomInstructions(
{},
'/test/path',
'test'
)
expect(instructions).toMatchSnapshot()
})
it("should prioritize mode-specific rules for architect mode", async () => {
const instructions = await addCustomInstructions({}, "/test/path", modes[1].slug)
it('should prioritize mode-specific rules for code reviewer mode', async () => {
// Mock readFile to include code reviewer rules
const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith('.clinerules-review')) {
return '# Code Reviewer Rules\n1. Provide specific examples in feedback\n2. Focus on maintainability and best practices'
}
if (path.endsWith('.clinerules')) {
return '# Test Rules\n1. First rule\n2. Second rule'
}
return ''
})
jest.spyOn(fs, 'readFile').mockImplementation(mockReadFile)
expect(instructions).toMatchSnapshot()
})
const instructions = await addCustomInstructions(
{},
'/test/path',
'review'
)
expect(instructions).toMatchSnapshot()
})
it("should prioritize mode-specific rules for test engineer mode", async () => {
// Mock readFile to include test engineer rules
const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith(".clinerules-test")) {
return "# Test Engineer Rules\n1. Always write tests first\n2. Get approval before modifying non-test code"
}
if (path.endsWith(".clinerules")) {
return "# Test Rules\n1. First rule\n2. Second rule"
}
return ""
})
jest.spyOn(fs, "readFile").mockImplementation(mockReadFile)
it('should generate correct prompt for test engineer mode', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
undefined,
undefined,
undefined,
'test'
)
// Verify test engineer role requirements
expect(prompt).toContain('must ask the user to confirm before making ANY changes to non-test code')
expect(prompt).toContain('ask the user to confirm your test plan')
expect(prompt).toMatchSnapshot()
})
const instructions = await addCustomInstructions({}, "/test/path", "test")
expect(instructions).toMatchSnapshot()
})
it('should generate correct prompt for code reviewer mode', async () => {
const prompt = await SYSTEM_PROMPT(
'/test/path',
false,
undefined,
undefined,
undefined,
'review'
)
// Verify code reviewer role constraints
expect(prompt).toContain('providing detailed, actionable feedback')
expect(prompt).toContain('maintain a read-only approach')
expect(prompt).toMatchSnapshot()
})
it("should prioritize mode-specific rules for code reviewer mode", async () => {
// Mock readFile to include code reviewer rules
const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith(".clinerules-review")) {
return "# Code Reviewer Rules\n1. Provide specific examples in feedback\n2. Focus on maintainability and best practices"
}
if (path.endsWith(".clinerules")) {
return "# Test Rules\n1. First rule\n2. Second rule"
}
return ""
})
jest.spyOn(fs, "readFile").mockImplementation(mockReadFile)
it('should fall back to generic rules when mode-specific rules not found', async () => {
// Mock readFile to return ENOENT for mode-specific file
const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
if (path.endsWith('.clinerules-code') ||
path.endsWith('.clinerules-test') ||
path.endsWith('.clinerules-review')) {
const error = new Error('ENOENT') as NodeJS.ErrnoException
error.code = 'ENOENT'
throw error
}
if (path.endsWith('.clinerules')) {
return '# Test Rules\n1. First rule\n2. Second rule'
}
return ''
})
jest.spyOn(fs, 'readFile').mockImplementation(mockReadFile)
const instructions = await addCustomInstructions({}, "/test/path", "review")
expect(instructions).toMatchSnapshot()
})
const instructions = await addCustomInstructions(
{},
'/test/path',
defaultModeSlug
)
expect(instructions).toMatchSnapshot()
})
it("should generate correct prompt for test engineer mode", async () => {
const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "test")
it('should include preferred language when provided', async () => {
const instructions = await addCustomInstructions(
{ preferredLanguage: 'Spanish' },
'/test/path',
defaultModeSlug
)
expect(instructions).toMatchSnapshot()
})
// Verify test engineer role requirements
expect(prompt).toContain("must ask the user to confirm before making ANY changes to non-test code")
expect(prompt).toContain("ask the user to confirm your test plan")
expect(prompt).toMatchSnapshot()
})
it('should include custom instructions when provided', async () => {
const instructions = await addCustomInstructions(
{ customInstructions: 'Custom test instructions' },
'/test/path'
)
expect(instructions).toMatchSnapshot()
})
it("should generate correct prompt for code reviewer mode", async () => {
const prompt = await SYSTEM_PROMPT("/test/path", false, undefined, undefined, undefined, "review")
it('should combine all custom instructions', async () => {
const instructions = await addCustomInstructions(
{
customInstructions: 'Custom test instructions',
preferredLanguage: 'French'
},
'/test/path',
defaultModeSlug
)
expect(instructions).toMatchSnapshot()
})
// Verify code reviewer role constraints
expect(prompt).toContain("providing detailed, actionable feedback")
expect(prompt).toContain("maintain a read-only approach")
expect(prompt).toMatchSnapshot()
})
it('should handle undefined mode-specific instructions', async () => {
const instructions = await addCustomInstructions(
{},
'/test/path'
)
expect(instructions).toMatchSnapshot()
})
it("should fall back to generic rules when mode-specific rules not found", async () => {
// Mock readFile to return ENOENT for mode-specific file
const mockReadFile = jest.fn().mockImplementation(async (path: string) => {
if (
path.endsWith(".clinerules-code") ||
path.endsWith(".clinerules-test") ||
path.endsWith(".clinerules-review")
) {
const error = new Error("ENOENT") as NodeJS.ErrnoException
error.code = "ENOENT"
throw error
}
if (path.endsWith(".clinerules")) {
return "# Test Rules\n1. First rule\n2. Second rule"
}
return ""
})
jest.spyOn(fs, "readFile").mockImplementation(mockReadFile)
it('should trim mode-specific instructions', async () => {
const instructions = await addCustomInstructions(
{ customInstructions: ' Custom mode instructions ' },
'/test/path'
)
expect(instructions).toMatchSnapshot()
})
const instructions = await addCustomInstructions({}, "/test/path", defaultModeSlug)
it('should handle empty mode-specific instructions', async () => {
const instructions = await addCustomInstructions(
{ customInstructions: '' },
'/test/path'
)
expect(instructions).toMatchSnapshot()
})
expect(instructions).toMatchSnapshot()
})
it('should combine global and mode-specific instructions', async () => {
const instructions = await addCustomInstructions(
{
customInstructions: 'Global instructions',
customPrompts: {
code: { customInstructions: 'Mode-specific instructions' }
}
},
'/test/path',
defaultModeSlug
)
expect(instructions).toMatchSnapshot()
})
it("should include preferred language when provided", async () => {
const instructions = await addCustomInstructions(
{ preferredLanguage: "Spanish" },
"/test/path",
defaultModeSlug,
)
it('should prioritize mode-specific instructions after global ones', async () => {
const instructions = await addCustomInstructions(
{
customInstructions: 'First instruction',
customPrompts: {
code: { customInstructions: 'Second instruction' }
}
},
'/test/path',
defaultModeSlug
)
const instructionParts = instructions.split('\n\n')
const globalIndex = instructionParts.findIndex(part => part.includes('First instruction'))
const modeSpecificIndex = instructionParts.findIndex(part => part.includes('Second instruction'))
expect(globalIndex).toBeLessThan(modeSpecificIndex)
expect(instructions).toMatchSnapshot()
})
expect(instructions).toMatchSnapshot()
})
afterAll(() => {
jest.restoreAllMocks()
})
it("should include custom instructions when provided", async () => {
const instructions = await addCustomInstructions(
{ customInstructions: "Custom test instructions" },
"/test/path",
)
expect(instructions).toMatchSnapshot()
})
it("should combine all custom instructions", async () => {
const instructions = await addCustomInstructions(
{
customInstructions: "Custom test instructions",
preferredLanguage: "French",
},
"/test/path",
defaultModeSlug,
)
expect(instructions).toMatchSnapshot()
})
it("should handle undefined mode-specific instructions", async () => {
const instructions = await addCustomInstructions({}, "/test/path")
expect(instructions).toMatchSnapshot()
})
it("should trim mode-specific instructions", async () => {
const instructions = await addCustomInstructions(
{ customInstructions: " Custom mode instructions " },
"/test/path",
)
expect(instructions).toMatchSnapshot()
})
it("should handle empty mode-specific instructions", async () => {
const instructions = await addCustomInstructions({ customInstructions: "" }, "/test/path")
expect(instructions).toMatchSnapshot()
})
it("should combine global and mode-specific instructions", async () => {
const instructions = await addCustomInstructions(
{
customInstructions: "Global instructions",
customPrompts: {
code: { customInstructions: "Mode-specific instructions" },
},
},
"/test/path",
defaultModeSlug,
)
expect(instructions).toMatchSnapshot()
})
it("should prioritize mode-specific instructions after global ones", async () => {
const instructions = await addCustomInstructions(
{
customInstructions: "First instruction",
customPrompts: {
code: { customInstructions: "Second instruction" },
},
},
"/test/path",
defaultModeSlug,
)
const instructionParts = instructions.split("\n\n")
const globalIndex = instructionParts.findIndex((part) => part.includes("First instruction"))
const modeSpecificIndex = instructionParts.findIndex((part) => part.includes("Second instruction"))
expect(globalIndex).toBeLessThan(modeSpecificIndex)
expect(instructions).toMatchSnapshot()
})
afterAll(() => {
jest.restoreAllMocks()
})
})

View File

@@ -2,27 +2,31 @@ import { DiffStrategy } from "../../diff/DiffStrategy"
import { McpHub } from "../../../services/mcp/McpHub"
export function getCapabilitiesSection(
cwd: string,
supportsComputerUse: boolean,
mcpHub?: McpHub,
diffStrategy?: DiffStrategy,
cwd: string,
supportsComputerUse: boolean,
mcpHub?: McpHub,
diffStrategy?: DiffStrategy,
): string {
return `====
return `====
CAPABILITIES
- You have access to tools that let you execute CLI commands on the user's computer, list files, view source code definitions, regex search${
supportsComputerUse ? ", use the browser" : ""
}, read and write files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
supportsComputerUse ? ", use the browser" : ""
}, read and write files, and ask follow-up questions. These tools help you effectively accomplish a wide range of tasks, such as writing code, making edits or improvements to existing files, understanding the current state of a project, performing system operations, and much more.
- When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('${cwd}') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.
- You can use search_files to perform regex searches across files in a specified directory, outputting context-rich results that include surrounding lines. This is particularly useful for understanding code patterns, finding specific implementations, or identifying areas that need refactoring.
- You can use the list_code_definition_names tool to get an overview of source code definitions for all files at the top level of a specified directory. This can be particularly useful when you need to understand the broader context and relationships between certain parts of the code. You may need to call this tool multiple times to understand various parts of the codebase related to the task.
- For example, when asked to make edits or improvements you might analyze the file structure in the initial environment_details to get an overview of the project, then use list_code_definition_names to get further insight using source code definitions for files located in relevant directories, then read_file to examine the contents of relevant files, analyze the code and suggest improvements or make necessary edits, then use the write_to_file ${diffStrategy ? "or apply_diff " : ""}tool to apply the changes. If you refactored code that could affect other parts of the codebase, you could use search_files to ensure you update other files as needed.
- You can use the execute_command tool to run commands on the user's computer whenever you feel it can help accomplish the user's task. When you need to execute a CLI command, you must provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, since they are more flexible and easier to run. Interactive and long-running commands are allowed, since the commands are run in the user's VSCode terminal. The user may keep commands running in the background and you will be kept updated on their status along the way. Each command you execute is run in a new terminal instance.${
supportsComputerUse
? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
: ""
}${mcpHub ? `
supportsComputerUse
? "\n- You can use the browser_action tool to interact with websites (including html files and locally running development servers) through a Puppeteer-controlled browser when you feel it is necessary in accomplishing the user's task. This tool is particularly useful for web development tasks as it allows you to launch a browser, navigate to pages, interact with elements through clicks and keyboard input, and capture the results through screenshots and console logs. This tool may be useful at key stages of web development tasks-such as after implementing new features, making substantial changes, when troubleshooting issues, or to verify the result of your work. You can analyze the provided screenshots to ensure correct rendering or identify errors, and review console logs for runtime issues.\n - For example, if asked to add a component to a react website, you might create the necessary files, use execute_command to run the site locally, then use browser_action to launch the browser, navigate to the local server, and verify the component renders & functions correctly before closing the browser."
: ""
}${
mcpHub
? `
- You have access to MCP servers that may provide additional tools and resources. Each server may provide different capabilities that you can use to accomplish tasks more effectively.
` : ''}`
}
`
: ""
}`
}

View File

@@ -1,46 +1,51 @@
import fs from 'fs/promises'
import path from 'path'
import fs from "fs/promises"
import path from "path"
export async function loadRuleFiles(cwd: string): Promise<string> {
const ruleFiles = ['.clinerules', '.cursorrules', '.windsurfrules']
let combinedRules = ''
const ruleFiles = [".clinerules", ".cursorrules", ".windsurfrules"]
let combinedRules = ""
for (const file of ruleFiles) {
try {
const content = await fs.readFile(path.join(cwd, file), 'utf-8')
if (content.trim()) {
combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
}
} catch (err) {
// Silently skip if file doesn't exist
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
throw err
}
}
}
for (const file of ruleFiles) {
try {
const content = await fs.readFile(path.join(cwd, file), "utf-8")
if (content.trim()) {
combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
}
} catch (err) {
// Silently skip if file doesn't exist
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
throw err
}
}
}
return combinedRules
return combinedRules
}
export async function addCustomInstructions(customInstructions: string, cwd: string, preferredLanguage?: string): Promise<string> {
const ruleFileContent = await loadRuleFiles(cwd)
const allInstructions = []
export async function addCustomInstructions(
customInstructions: string,
cwd: string,
preferredLanguage?: string,
): Promise<string> {
const ruleFileContent = await loadRuleFiles(cwd)
const allInstructions = []
if (preferredLanguage) {
allInstructions.push(`You should always speak and think in the ${preferredLanguage} language.`)
}
if (customInstructions.trim()) {
allInstructions.push(customInstructions.trim())
}
if (preferredLanguage) {
allInstructions.push(`You should always speak and think in the ${preferredLanguage} language.`)
}
if (ruleFileContent && ruleFileContent.trim()) {
allInstructions.push(ruleFileContent.trim())
}
if (customInstructions.trim()) {
allInstructions.push(customInstructions.trim())
}
const joinedInstructions = allInstructions.join('\n\n')
if (ruleFileContent && ruleFileContent.trim()) {
allInstructions.push(ruleFileContent.trim())
}
return joinedInstructions ? `
const joinedInstructions = allInstructions.join("\n\n")
return joinedInstructions
? `
====
USER'S CUSTOM INSTRUCTIONS
@@ -48,5 +53,5 @@ USER'S CUSTOM INSTRUCTIONS
The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
${joinedInstructions}`
: ""
}
: ""
}

View File

@@ -1,8 +1,8 @@
export { getRulesSection } 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 { getToolUseGuidelinesSection } from './tool-use-guidelines'
export { getCapabilitiesSection } from './capabilities'
export { getRulesSection } 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 { getToolUseGuidelinesSection } from "./tool-use-guidelines"
export { getCapabilitiesSection } from "./capabilities"

View File

@@ -2,47 +2,48 @@ import { DiffStrategy } from "../../diff/DiffStrategy"
import { McpHub } from "../../../services/mcp/McpHub"
export async function getMcpServersSection(mcpHub?: McpHub, diffStrategy?: DiffStrategy): Promise<string> {
if (!mcpHub) {
return '';
}
if (!mcpHub) {
return ""
}
const connectedServers = mcpHub.getServers().length > 0
? `${mcpHub
.getServers()
.filter((server) => server.status === "connected")
.map((server) => {
const tools = server.tools
?.map((tool) => {
const schemaStr = tool.inputSchema
? ` Input Schema:
const connectedServers =
mcpHub.getServers().length > 0
? `${mcpHub
.getServers()
.filter((server) => server.status === "connected")
.map((server) => {
const tools = server.tools
?.map((tool) => {
const schemaStr = tool.inputSchema
? ` Input Schema:
${JSON.stringify(tool.inputSchema, null, 2).split("\n").join("\n ")}`
: ""
: ""
return `- ${tool.name}: ${tool.description}\n${schemaStr}`
})
.join("\n\n")
return `- ${tool.name}: ${tool.description}\n${schemaStr}`
})
.join("\n\n")
const templates = server.resourceTemplates
?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
.join("\n")
const templates = server.resourceTemplates
?.map((template) => `- ${template.uriTemplate} (${template.name}): ${template.description}`)
.join("\n")
const resources = server.resources
?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
.join("\n")
const resources = server.resources
?.map((resource) => `- ${resource.uri} (${resource.name}): ${resource.description}`)
.join("\n")
const config = JSON.parse(server.config)
const config = JSON.parse(server.config)
return (
`## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
(tools ? `\n\n### Available Tools\n${tools}` : "") +
(templates ? `\n\n### Resource Templates\n${templates}` : "") +
(resources ? `\n\n### Direct Resources\n${resources}` : "")
)
})
.join("\n\n")}`
: "(No MCP servers currently connected)";
return (
`## ${server.name} (\`${config.command}${config.args && Array.isArray(config.args) ? ` ${config.args.join(" ")}` : ""}\`)` +
(tools ? `\n\n### Available Tools\n${tools}` : "") +
(templates ? `\n\n### Resource Templates\n${templates}` : "") +
(resources ? `\n\n### Direct Resources\n${resources}` : "")
)
})
.join("\n\n")}`
: "(No MCP servers currently connected)"
return `MCP SERVERS
return `MCP SERVERS
The Model Context Protocol (MCP) enables communication between the system and locally running MCP servers that provide additional tools and resources to extend your capabilities.
@@ -397,11 +398,11 @@ IMPORTANT: Regardless of what else you see in the MCP settings file, you must de
## Editing MCP Servers
The user may ask to add tools or resources that may make sense to add to an existing MCP server (listed under 'Connected MCP Servers' above: ${
mcpHub
.getServers()
.map((server) => server.name)
.join(", ") || "(None running currently)"
}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use write_to_file${diffStrategy ? " or apply_diff" : ""} to make changes to the files.
mcpHub
.getServers()
.map((server) => server.name)
.join(", ") || "(None running currently)"
}, e.g. if it would use the same API. This would be possible if you can locate the MCP server repository on the user's system by looking at the server arguments for a filepath. You might then use list_files and read_file to explore the files in the repository, and use write_to_file${diffStrategy ? " or apply_diff" : ""} to make changes to the files.
However some MCP servers may be running from installed packages rather than a local repository, in which case it may make more sense to create a new MCP server.
@@ -410,4 +411,4 @@ However some MCP servers may be running from installed packages rather than a lo
The user may not always request the use or creation of MCP servers. Instead, they might provide tasks that can be completed with existing tools. While using the MCP SDK to extend your capabilities can be useful, it's important to understand that this is just one specialized type of task you can accomplish. You should only implement MCP servers when the user explicitly requests it (e.g., "add a tool that...").
Remember: The MCP documentation and example provided above are to help you understand and work with existing MCP servers or create new ones when requested by the user. You already have access to tools and capabilities that can be used to accomplish a wide range of tasks.`
}
}

View File

@@ -1,5 +1,5 @@
export function getObjectiveSection(): string {
return `====
return `====
OBJECTIVE
@@ -10,4 +10,4 @@ You accomplish a given task iteratively, breaking it down into clear steps and w
3. Remember, you have extensive capabilities with access to a wide range of tools that can be used in powerful and clever ways as necessary to accomplish each goal. Before calling a tool, do some analysis within <thinking></thinking> tags. First, analyze the file structure provided in environment_details to gain context and insights for proceeding effectively. Then, think about which of the provided tools is the most relevant tool to accomplish the user's task. Next, go through each of the required parameters of the relevant tool and determine if the user has directly provided or given enough information to infer a value. When deciding if the parameter can be inferred, carefully consider all the context to see if it supports a specific value. If all of the required parameters are present or can be reasonably inferred, close the thinking tag and proceed with the tool use. BUT, if one of the values for a required parameter is missing, DO NOT invoke the tool (not even with fillers for the missing params) and instead, ask the user to provide the missing parameters using the ask_followup_question tool. DO NOT ask for more information on optional parameters if it is not provided.
4. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built.
5. The user may provide feedback, which you can use to make improvements and try again. But DO NOT continue in pointless back and forth conversations, i.e. don't end your responses with questions or offers for further assistance.`
}
}

View File

@@ -1,11 +1,7 @@
import { DiffStrategy } from "../../diff/DiffStrategy"
export function getRulesSection(
cwd: string,
supportsComputerUse: boolean,
diffStrategy?: DiffStrategy
): string {
return `====
export function getRulesSection(cwd: string, supportsComputerUse: boolean, diffStrategy?: DiffStrategy): string {
return `====
RULES
@@ -23,10 +19,10 @@ ${diffStrategy ? "- You should use apply_diff instead of write_to_file when maki
- When executing commands, if you don't see the expected output, assume the terminal executed the command successfully and proceed with the task. The user's terminal may be unable to stream the output back properly. If you absolutely need to see the actual terminal output, use the ask_followup_question tool to request the user to copy and paste it back to you.
- The user may provide a file's contents directly in their message, in which case you shouldn't use the read_file tool to get the file contents again since you already have it.
- Your goal is to try to accomplish the user's task, NOT engage in a back and forth conversation.${
supportsComputerUse
? '\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.'
: ""
}
supportsComputerUse
? '\n- The user may ask generic non-development tasks, such as "what\'s the latest news" or "look up the weather in San Diego", in which case you might use the browser_action tool to complete the task if it makes sense to do so, rather than trying to create a website or using curl to answer the question. However, if an available MCP server tool or resource can be used instead, you should prefer to use it over browser_action.'
: ""
}
- NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user.
- You are STRICTLY FORBIDDEN from starting your messages with "Great", "Certainly", "Okay", "Sure". You should NOT be conversational in your responses, but rather direct and to the point. For example you should NOT say "Great, I've updated the CSS" but instead something like "I've updated the CSS". It is important you be clear and technical in your messages.
- When presented with images, utilize your vision capabilities to thoroughly examine them and extract meaningful information. Incorporate these insights into your thought process as you accomplish the user's task.
@@ -35,8 +31,8 @@ ${diffStrategy ? "- You should use apply_diff instead of write_to_file when maki
- When using the write_to_file tool, ALWAYS provide the COMPLETE file content in your response. This is NON-NEGOTIABLE. Partial updates or placeholders like '// rest of code unchanged' are STRICTLY FORBIDDEN. You MUST include ALL parts of the file, even if they haven't been modified. Failure to do so will result in incomplete or broken code, severely impacting the user's project.
- MCP operations should be used one at a time, similar to other tool usage. Wait for confirmation of success before proceeding with additional operations.
- 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 make a todo app, 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.${
supportsComputerUse
? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
: ""
}`
}
supportsComputerUse
? " Then if you want to test your work, you might use browser_action to launch the site, wait for the user's response confirming the site was launched along with a screenshot, then perhaps e.g., click a button to test functionality if needed, wait for the user's response confirming the button was clicked along with a screenshot of the new state, before finally closing the browser."
: ""
}`
}

View File

@@ -3,7 +3,7 @@ import os from "os"
import osName from "os-name"
export function getSystemInfoSection(cwd: string): string {
return `====
return `====
SYSTEM INFORMATION
@@ -13,4 +13,4 @@ Home Directory: ${os.homedir().toPosix()}
Current Working Directory: ${cwd.toPosix()}
When the user initially gives you a task, a recursive list of all filepaths in the current working directory ('/test/path') will be included in environment_details. This provides an overview of the project's file structure, offering key insights into the project from directory/file names (how developers conceptualize and organize their code) and file extensions (the language used). This can also guide decision-making on which files to explore further. If you need to further explore directories such as outside the current working directory, you can use the list_files tool. If you pass 'true' for the recursive parameter, it will list files recursively. Otherwise, it will list files at the top level, which is better suited for generic directories where you don't necessarily need the nested structure, like the Desktop.`
}
}

View File

@@ -1,5 +1,5 @@
export function getToolUseGuidelinesSection(): string {
return `# Tool Use Guidelines
return `# Tool Use Guidelines
1. In <thinking> 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. For example using the list_files tool is more effective than running a command like \`ls\` in the terminal. It's critical that you think about each available tool and use the one that best fits the current step in the task.
@@ -19,4 +19,4 @@ It is crucial to proceed step-by-step, waiting for the user's message after each
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.`
}
}

View File

@@ -1,5 +1,5 @@
export function getSharedToolUseSection(): string {
return `====
return `====
TOOL USE
@@ -22,4 +22,4 @@ For example:
</read_file>
Always adhere to this format for the tool use to ensure proper parsing and execution.`
}
}

View File

@@ -3,87 +3,84 @@ import { DiffStrategy } from "../diff/DiffStrategy"
import { McpHub } from "../../services/mcp/McpHub"
import { getToolDescriptionsForMode } from "./tools"
import {
getRulesSection,
getSystemInfoSection,
getObjectiveSection,
getSharedToolUseSection,
getMcpServersSection,
getToolUseGuidelinesSection,
getCapabilitiesSection
getRulesSection,
getSystemInfoSection,
getObjectiveSection,
getSharedToolUseSection,
getMcpServersSection,
getToolUseGuidelinesSection,
getCapabilitiesSection,
} from "./sections"
import fs from 'fs/promises'
import path from 'path'
import fs from "fs/promises"
import path from "path"
async function loadRuleFiles(cwd: string, mode: Mode): Promise<string> {
let combinedRules = ''
let combinedRules = ""
// First try mode-specific rules
const modeSpecificFile = `.clinerules-${mode}`
try {
const content = await fs.readFile(path.join(cwd, modeSpecificFile), 'utf-8')
if (content.trim()) {
combinedRules += `\n# Rules from ${modeSpecificFile}:\n${content.trim()}\n`
}
} catch (err) {
// Silently skip if file doesn't exist
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
throw err
}
}
// First try mode-specific rules
const modeSpecificFile = `.clinerules-${mode}`
try {
const content = await fs.readFile(path.join(cwd, modeSpecificFile), "utf-8")
if (content.trim()) {
combinedRules += `\n# Rules from ${modeSpecificFile}:\n${content.trim()}\n`
}
} catch (err) {
// Silently skip if file doesn't exist
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
throw err
}
}
// Then try generic rules files
const genericRuleFiles = ['.clinerules']
for (const file of genericRuleFiles) {
try {
const content = await fs.readFile(path.join(cwd, file), 'utf-8')
if (content.trim()) {
combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
}
} catch (err) {
// Silently skip if file doesn't exist
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
throw err
}
}
}
// Then try generic rules files
const genericRuleFiles = [".clinerules"]
for (const file of genericRuleFiles) {
try {
const content = await fs.readFile(path.join(cwd, file), "utf-8")
if (content.trim()) {
combinedRules += `\n# Rules from ${file}:\n${content.trim()}\n`
}
} catch (err) {
// Silently skip if file doesn't exist
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
throw err
}
}
}
return combinedRules
return combinedRules
}
interface State {
customInstructions?: string;
customPrompts?: CustomPrompts;
preferredLanguage?: string;
customInstructions?: string
customPrompts?: CustomPrompts
preferredLanguage?: string
}
export async function addCustomInstructions(
state: State,
cwd: string,
mode: Mode = defaultModeSlug
): Promise<string> {
const ruleFileContent = await loadRuleFiles(cwd, mode)
const allInstructions = []
export async function addCustomInstructions(state: State, cwd: string, mode: Mode = defaultModeSlug): Promise<string> {
const ruleFileContent = await loadRuleFiles(cwd, mode)
const allInstructions = []
if (state.preferredLanguage) {
allInstructions.push(`You should always speak and think in the ${state.preferredLanguage} language.`)
}
if (state.preferredLanguage) {
allInstructions.push(`You should always speak and think in the ${state.preferredLanguage} language.`)
}
if (state.customInstructions?.trim()) {
allInstructions.push(state.customInstructions.trim())
}
if (state.customInstructions?.trim()) {
allInstructions.push(state.customInstructions.trim())
}
const customPrompt = state.customPrompts?.[mode]
if (typeof customPrompt === 'object' && customPrompt?.customInstructions?.trim()) {
allInstructions.push(customPrompt.customInstructions.trim())
}
const customPrompt = state.customPrompts?.[mode]
if (typeof customPrompt === "object" && customPrompt?.customInstructions?.trim()) {
allInstructions.push(customPrompt.customInstructions.trim())
}
if (ruleFileContent && ruleFileContent.trim()) {
allInstructions.push(ruleFileContent.trim())
}
if (ruleFileContent && ruleFileContent.trim()) {
allInstructions.push(ruleFileContent.trim())
}
const joinedInstructions = allInstructions.join('\n\n')
const joinedInstructions = allInstructions.join("\n\n")
return joinedInstructions ? `
return joinedInstructions
? `
====
USER'S CUSTOM INSTRUCTIONS
@@ -91,19 +88,19 @@ USER'S CUSTOM INSTRUCTIONS
The following additional instructions are provided by the user, and should be followed to the best of your ability without interfering with the TOOL USE guidelines.
${joinedInstructions}`
: ""
: ""
}
async function generatePrompt(
cwd: string,
supportsComputerUse: boolean,
mode: Mode,
mcpHub?: McpHub,
diffStrategy?: DiffStrategy,
browserViewportSize?: string,
promptComponent?: PromptComponent,
cwd: string,
supportsComputerUse: boolean,
mode: Mode,
mcpHub?: McpHub,
diffStrategy?: DiffStrategy,
browserViewportSize?: string,
promptComponent?: PromptComponent,
): Promise<string> {
const basePrompt = `${promptComponent?.roleDefinition || getRoleDefinition(mode)}
const basePrompt = `${promptComponent?.roleDefinition || getRoleDefinition(mode)}
${getSharedToolUseSection()}
@@ -119,38 +116,38 @@ ${getRulesSection(cwd, supportsComputerUse, diffStrategy)}
${getSystemInfoSection(cwd)}
${getObjectiveSection()}`;
${getObjectiveSection()}`
return basePrompt;
return basePrompt
}
export const SYSTEM_PROMPT = async (
cwd: string,
supportsComputerUse: boolean,
mcpHub?: McpHub,
diffStrategy?: DiffStrategy,
browserViewportSize?: string,
mode: Mode = defaultModeSlug,
customPrompts?: CustomPrompts,
cwd: string,
supportsComputerUse: boolean,
mcpHub?: McpHub,
diffStrategy?: DiffStrategy,
browserViewportSize?: string,
mode: Mode = defaultModeSlug,
customPrompts?: CustomPrompts,
) => {
const getPromptComponent = (value: unknown) => {
if (typeof value === 'object' && value !== null) {
return value as PromptComponent;
}
return undefined;
};
const getPromptComponent = (value: unknown) => {
if (typeof value === "object" && value !== null) {
return value as PromptComponent
}
return undefined
}
// Use default mode if not found
const currentMode = modes.find(m => m.slug === mode) || modes[0];
const promptComponent = getPromptComponent(customPrompts?.[currentMode.slug]);
// Use default mode if not found
const currentMode = modes.find((m) => m.slug === mode) || modes[0]
const promptComponent = getPromptComponent(customPrompts?.[currentMode.slug])
return generatePrompt(
cwd,
supportsComputerUse,
currentMode.slug,
mcpHub,
diffStrategy,
browserViewportSize,
promptComponent
);
return generatePrompt(
cwd,
supportsComputerUse,
currentMode.slug,
mcpHub,
diffStrategy,
browserViewportSize,
promptComponent,
)
}

View File

@@ -1,10 +1,10 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getAccessMcpResourceDescription(args: ToolArgs): string | undefined {
if (!args.mcpHub) {
return undefined;
}
return `## access_mcp_resource
if (!args.mcpHub) {
return undefined
}
return `## access_mcp_resource
Description: Request to access a resource provided by a connected MCP server. Resources represent data sources that can be used as context, such as files, API responses, or system information.
Parameters:
- server_name: (required) The name of the MCP server providing the resource
@@ -21,4 +21,4 @@ Example: Requesting to access an MCP resource
<server_name>weather-server</server_name>
<uri>weather://san-francisco/current</uri>
</access_mcp_resource>`
}
}

View File

@@ -1,5 +1,5 @@
export function getAskFollowupQuestionDescription(): string {
return `## ask_followup_question
return `## ask_followup_question
Description: Ask the user a question to gather additional information needed to complete the task. This tool should be used when you encounter ambiguities, need clarification, or require more details to proceed effectively. It allows for interactive problem-solving by enabling direct communication with the user. Use this tool judiciously to maintain a balance between gathering necessary information and avoiding excessive back-and-forth.
Parameters:
- question: (required) The question to ask the user. This should be a clear, specific question that addresses the information you need.
@@ -12,4 +12,4 @@ Example: Requesting to ask the user for the path to the frontend-config.json fil
<ask_followup_question>
<question>What is the path to the frontend-config.json file?</question>
</ask_followup_question>`
}
}

View File

@@ -1,5 +1,5 @@
export function getAttemptCompletionDescription(): string {
return `## attempt_completion
return `## attempt_completion
Description: After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again.
IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in <thinking></thinking> tags if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool.
Parameters:
@@ -20,4 +20,4 @@ I've updated the CSS
</result>
<command>open index.html</command>
</attempt_completion>`
}
}

View File

@@ -1,10 +1,10 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getBrowserActionDescription(args: ToolArgs): string | undefined {
if (!args.supportsComputerUse) {
return undefined;
}
return `## browser_action
if (!args.supportsComputerUse) {
return undefined
}
return `## browser_action
Description: Request to interact with a Puppeteer-controlled browser. Every action, except \`close\`, will be responded to with a screenshot of the browser's current state, along with any new console logs. You may only perform one browser action per message, and wait for the user's response including a screenshot and logs to determine the next action.
- The sequence of actions **must always start with** launching the browser at a URL, and **must always end with** closing the browser. If you need to visit a new URL that is not possible to navigate to from the current webpage, you must first close the browser, then launch again at the new URL.
- While the browser is active, only the \`browser_action\` tool can be used. No other tools should be called during this time. You may proceed to use other tools only after closing the browser. For example if you run into an error and need to fix a file, you must close the browser, then use other tools to make the necessary changes, then re-launch the browser to verify the result.
@@ -49,4 +49,4 @@ Example: Requesting to click on the element at coordinates 450,300
<action>click</action>
<coordinate>450,300</coordinate>
</browser_action>`
}
}

View File

@@ -1,7 +1,7 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getExecuteCommandDescription(args: ToolArgs): string | undefined {
return `## execute_command
return `## execute_command
Description: Request to execute a CLI command on the system. Use this when you need to perform system operations or run specific commands to accomplish any step in the user's task. You must tailor your command to the user's system and provide a clear explanation of what the command does. Prefer to execute complex CLI commands over creating executable scripts, as they are more flexible and easier to run. Commands will be executed in the current working directory: ${args.cwd}
Parameters:
- command: (required) The CLI command to execute. This should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.
@@ -14,4 +14,4 @@ Example: Requesting to execute npm run dev
<execute_command>
<command>npm run dev</command>
</execute_command>`
}
}

View File

@@ -1,79 +1,80 @@
import { getExecuteCommandDescription } from './execute-command'
import { getReadFileDescription } from './read-file'
import { getWriteToFileDescription } from './write-to-file'
import { getSearchFilesDescription } from './search-files'
import { getListFilesDescription } from './list-files'
import { getListCodeDefinitionNamesDescription } from './list-code-definition-names'
import { getBrowserActionDescription } from './browser-action'
import { getAskFollowupQuestionDescription } from './ask-followup-question'
import { getAttemptCompletionDescription } from './attempt-completion'
import { getUseMcpToolDescription } from './use-mcp-tool'
import { getAccessMcpResourceDescription } from './access-mcp-resource'
import { DiffStrategy } from '../../diff/DiffStrategy'
import { McpHub } from '../../../services/mcp/McpHub'
import { Mode, ToolName, getModeConfig, isToolAllowedForMode } from '../../../shared/modes'
import { ToolArgs } from './types'
import { getExecuteCommandDescription } from "./execute-command"
import { getReadFileDescription } from "./read-file"
import { getWriteToFileDescription } from "./write-to-file"
import { getSearchFilesDescription } from "./search-files"
import { getListFilesDescription } from "./list-files"
import { getListCodeDefinitionNamesDescription } from "./list-code-definition-names"
import { getBrowserActionDescription } from "./browser-action"
import { getAskFollowupQuestionDescription } from "./ask-followup-question"
import { getAttemptCompletionDescription } from "./attempt-completion"
import { getUseMcpToolDescription } from "./use-mcp-tool"
import { getAccessMcpResourceDescription } from "./access-mcp-resource"
import { DiffStrategy } from "../../diff/DiffStrategy"
import { McpHub } from "../../../services/mcp/McpHub"
import { Mode, ToolName, getModeConfig, isToolAllowedForMode } from "../../../shared/modes"
import { ToolArgs } from "./types"
// Map of tool names to their description functions
const toolDescriptionMap: Record<string, (args: ToolArgs) => string | undefined> = {
'execute_command': args => getExecuteCommandDescription(args),
'read_file': args => getReadFileDescription(args),
'write_to_file': args => getWriteToFileDescription(args),
'search_files': args => getSearchFilesDescription(args),
'list_files': args => getListFilesDescription(args),
'list_code_definition_names': args => getListCodeDefinitionNamesDescription(args),
'browser_action': args => getBrowserActionDescription(args),
'ask_followup_question': () => getAskFollowupQuestionDescription(),
'attempt_completion': () => getAttemptCompletionDescription(),
'use_mcp_tool': args => getUseMcpToolDescription(args),
'access_mcp_resource': args => getAccessMcpResourceDescription(args),
'apply_diff': args => args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : ''
};
execute_command: (args) => getExecuteCommandDescription(args),
read_file: (args) => getReadFileDescription(args),
write_to_file: (args) => getWriteToFileDescription(args),
search_files: (args) => getSearchFilesDescription(args),
list_files: (args) => getListFilesDescription(args),
list_code_definition_names: (args) => getListCodeDefinitionNamesDescription(args),
browser_action: (args) => getBrowserActionDescription(args),
ask_followup_question: () => getAskFollowupQuestionDescription(),
attempt_completion: () => getAttemptCompletionDescription(),
use_mcp_tool: (args) => getUseMcpToolDescription(args),
access_mcp_resource: (args) => getAccessMcpResourceDescription(args),
apply_diff: (args) =>
args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : "",
}
export function getToolDescriptionsForMode(
mode: Mode,
cwd: string,
supportsComputerUse: boolean,
diffStrategy?: DiffStrategy,
browserViewportSize?: string,
mcpHub?: McpHub
mode: Mode,
cwd: string,
supportsComputerUse: boolean,
diffStrategy?: DiffStrategy,
browserViewportSize?: string,
mcpHub?: McpHub,
): string {
const config = getModeConfig(mode);
const args: ToolArgs = {
cwd,
supportsComputerUse,
diffStrategy,
browserViewportSize,
mcpHub
};
const config = getModeConfig(mode)
const args: ToolArgs = {
cwd,
supportsComputerUse,
diffStrategy,
browserViewportSize,
mcpHub,
}
// Map tool descriptions in the exact order specified in the mode's tools array
const descriptions = config.tools.map(([toolName, toolOptions]) => {
const descriptionFn = toolDescriptionMap[toolName];
if (!descriptionFn || !isToolAllowedForMode(toolName as ToolName, mode)) {
return undefined;
}
// Map tool descriptions in the exact order specified in the mode's tools array
const descriptions = config.tools.map(([toolName, toolOptions]) => {
const descriptionFn = toolDescriptionMap[toolName]
if (!descriptionFn || !isToolAllowedForMode(toolName as ToolName, mode)) {
return undefined
}
return descriptionFn({
...args,
toolOptions
});
});
return descriptionFn({
...args,
toolOptions,
})
})
return `# Tools\n\n${descriptions.filter(Boolean).join('\n\n')}`;
return `# Tools\n\n${descriptions.filter(Boolean).join("\n\n")}`
}
// Export individual description functions for backward compatibility
export {
getExecuteCommandDescription,
getReadFileDescription,
getWriteToFileDescription,
getSearchFilesDescription,
getListFilesDescription,
getListCodeDefinitionNamesDescription,
getBrowserActionDescription,
getAskFollowupQuestionDescription,
getAttemptCompletionDescription,
getUseMcpToolDescription,
getAccessMcpResourceDescription
}
getExecuteCommandDescription,
getReadFileDescription,
getWriteToFileDescription,
getSearchFilesDescription,
getListFilesDescription,
getListCodeDefinitionNamesDescription,
getBrowserActionDescription,
getAskFollowupQuestionDescription,
getAttemptCompletionDescription,
getUseMcpToolDescription,
getAccessMcpResourceDescription,
}

View File

@@ -1,7 +1,7 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getListCodeDefinitionNamesDescription(args: ToolArgs): string {
return `## list_code_definition_names
return `## list_code_definition_names
Description: Request to list definition names (classes, functions, methods, etc.) used in source code files at the top level of the specified directory. This tool provides insights into the codebase structure and important constructs, encapsulating high-level concepts and relationships that are crucial for understanding the overall architecture.
Parameters:
- path: (required) The path of the directory (relative to the current working directory ${args.cwd}) to list top level source code definitions for.
@@ -14,4 +14,4 @@ Example: Requesting to list all top level source code definitions in the current
<list_code_definition_names>
<path>.</path>
</list_code_definition_names>`
}
}

View File

@@ -1,7 +1,7 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getListFilesDescription(args: ToolArgs): string {
return `## list_files
return `## list_files
Description: Request to list files and directories within the specified directory. If recursive is true, it will list all files and directories recursively. If recursive is false or not provided, it will only list the top-level contents. Do not use this tool to confirm the existence of files you may have created, as the user will let you know if the files were created successfully or not.
Parameters:
- path: (required) The path of the directory to list contents for (relative to the current working directory ${args.cwd})
@@ -17,4 +17,4 @@ Example: Requesting to list all files in the current directory
<path>.</path>
<recursive>false</recursive>
</list_files>`
}
}

View File

@@ -1,7 +1,7 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getReadFileDescription(args: ToolArgs): string {
return `## read_file
return `## read_file
Description: Request to read the contents of a file at the specified path. Use this when you need to examine the contents of an existing file you do not know the contents of, for example to analyze code, review text files, or extract information from configuration files. The output includes line numbers prefixed to each line (e.g. "1 | const x = 1"), making it easier to reference specific lines when creating diffs or discussing code. Automatically extracts raw text from PDF and DOCX files. May not be suitable for other types of binary files, as it returns the raw content as a string.
Parameters:
- path: (required) The path of the file to read (relative to the current working directory ${args.cwd})
@@ -14,4 +14,4 @@ Example: Requesting to read frontend-config.json
<read_file>
<path>frontend-config.json</path>
</read_file>`
}
}

View File

@@ -1,7 +1,7 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getSearchFilesDescription(args: ToolArgs): string {
return `## search_files
return `## search_files
Description: Request to perform a regex search across files in a specified directory, providing context-rich results. This tool searches for patterns or specific content across multiple files, displaying each match with encapsulating context.
Parameters:
- path: (required) The path of the directory to search in (relative to the current working directory ${args.cwd}). This directory will be recursively searched.

View File

@@ -1,11 +1,11 @@
import { DiffStrategy } from '../../diff/DiffStrategy'
import { McpHub } from '../../../services/mcp/McpHub'
import { DiffStrategy } from "../../diff/DiffStrategy"
import { McpHub } from "../../../services/mcp/McpHub"
export type ToolArgs = {
cwd: string;
supportsComputerUse: boolean;
diffStrategy?: DiffStrategy;
browserViewportSize?: string;
mcpHub?: McpHub;
toolOptions?: any;
};
cwd: string
supportsComputerUse: boolean
diffStrategy?: DiffStrategy
browserViewportSize?: string
mcpHub?: McpHub
toolOptions?: any
}

View File

@@ -1,10 +1,10 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getUseMcpToolDescription(args: ToolArgs): string | undefined {
if (!args.mcpHub) {
return undefined;
}
return `## use_mcp_tool
if (!args.mcpHub) {
return undefined
}
return `## use_mcp_tool
Description: Request to use a tool provided by a connected MCP server. Each MCP server can provide multiple tools with different capabilities. Tools have defined input schemas that specify required and optional parameters.
Parameters:
- server_name: (required) The name of the MCP server providing the tool
@@ -34,4 +34,4 @@ Example: Requesting to use an MCP tool
}
</arguments>
</use_mcp_tool>`
}
}

View File

@@ -1,7 +1,7 @@
import { ToolArgs } from './types';
import { ToolArgs } from "./types"
export function getWriteToFileDescription(args: ToolArgs): string {
return `## write_to_file
return `## write_to_file
Description: Request to write full content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file.
Parameters:
- path: (required) The path of the file to write to (relative to the current working directory ${args.cwd})

View File

@@ -1,52 +1,52 @@
import { Mode } from '../../shared/modes';
import { Mode } from "../../shared/modes"
export type { Mode };
export type { Mode }
export type ToolName =
| 'execute_command'
| 'read_file'
| 'write_to_file'
| 'apply_diff'
| 'search_files'
| 'list_files'
| 'list_code_definition_names'
| 'browser_action'
| 'use_mcp_tool'
| 'access_mcp_resource'
| 'ask_followup_question'
| 'attempt_completion';
| "execute_command"
| "read_file"
| "write_to_file"
| "apply_diff"
| "search_files"
| "list_files"
| "list_code_definition_names"
| "browser_action"
| "use_mcp_tool"
| "access_mcp_resource"
| "ask_followup_question"
| "attempt_completion"
export const CODE_TOOLS: ToolName[] = [
'execute_command',
'read_file',
'write_to_file',
'apply_diff',
'search_files',
'list_files',
'list_code_definition_names',
'browser_action',
'use_mcp_tool',
'access_mcp_resource',
'ask_followup_question',
'attempt_completion'
];
"execute_command",
"read_file",
"write_to_file",
"apply_diff",
"search_files",
"list_files",
"list_code_definition_names",
"browser_action",
"use_mcp_tool",
"access_mcp_resource",
"ask_followup_question",
"attempt_completion",
]
export const ARCHITECT_TOOLS: ToolName[] = [
'read_file',
'search_files',
'list_files',
'list_code_definition_names',
'ask_followup_question',
'attempt_completion'
];
"read_file",
"search_files",
"list_files",
"list_code_definition_names",
"ask_followup_question",
"attempt_completion",
]
export const ASK_TOOLS: ToolName[] = [
'read_file',
'search_files',
'list_files',
'browser_action',
'use_mcp_tool',
'access_mcp_resource',
'ask_followup_question',
'attempt_completion'
];
"read_file",
"search_files",
"list_files",
"browser_action",
"use_mcp_tool",
"access_mcp_resource",
"ask_followup_question",
"attempt_completion",
]