Merge branch 'main' into vs/support-unbound

This commit is contained in:
pugazhendhi-m
2025-01-28 21:58:23 +05:30
committed by GitHub
41 changed files with 1691 additions and 180 deletions

View File

@@ -1,5 +0,0 @@
---
"roo-cline": patch
---
Add per-server MCP network timeout configuration

View File

@@ -1,5 +1,11 @@
# Roo Code Changelog # Roo Code Changelog
## [3.3.4]
- Add per-server MCP network timeout configuration ranging from 15 seconds to an hour
- Speed up diff editing (thanks @hannesrudolph and @KyleHerndon!)
- Add option to perform explain/improve/fix code actions either in the existing task or a new task (thanks @samhvw8!)
## [3.3.3] ## [3.3.3]
- Throw errors sooner when a mode tries to write a restricted file - Throw errors sooner when a mode tries to write a restricted file

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "roo-cline", "name": "roo-cline",
"version": "3.3.3", "version": "3.3.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "roo-cline", "name": "roo-cline",
"version": "3.3.3", "version": "3.3.4",
"dependencies": { "dependencies": {
"@anthropic-ai/bedrock-sdk": "^0.10.2", "@anthropic-ai/bedrock-sdk": "^0.10.2",
"@anthropic-ai/sdk": "^0.26.0", "@anthropic-ai/sdk": "^0.26.0",

View File

@@ -3,7 +3,7 @@
"displayName": "Roo Code (prev. Roo Cline)", "displayName": "Roo Code (prev. Roo Cline)",
"description": "A VS Code plugin that enhances coding with AI-powered automation, multi-model support, and experimental features.", "description": "A VS Code plugin that enhances coding with AI-powered automation, multi-model support, and experimental features.",
"publisher": "RooVeterinaryInc", "publisher": "RooVeterinaryInc",
"version": "3.3.3", "version": "3.3.4",
"icon": "assets/icons/rocket.png", "icon": "assets/icons/rocket.png",
"galleryBanner": { "galleryBanner": {
"color": "#617A91", "color": "#617A91",

View File

@@ -1,5 +1,6 @@
import { Anthropic } from "@anthropic-ai/sdk" import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI, { AzureOpenAI } from "openai" import OpenAI, { AzureOpenAI } from "openai"
import { import {
ApiHandlerOptions, ApiHandlerOptions,
azureOpenAiDefaultApiVersion, azureOpenAiDefaultApiVersion,
@@ -8,6 +9,7 @@ import {
} from "../../shared/api" } from "../../shared/api"
import { ApiHandler, SingleCompletionHandler } from "../index" import { ApiHandler, SingleCompletionHandler } from "../index"
import { convertToOpenAiMessages } from "../transform/openai-format" import { convertToOpenAiMessages } from "../transform/openai-format"
import { convertToR1Format } from "../transform/r1-format"
import { ApiStream } from "../transform/stream" import { ApiStream } from "../transform/stream"
export class OpenAiHandler implements ApiHandler, SingleCompletionHandler { export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
@@ -16,7 +18,8 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
constructor(options: ApiHandlerOptions) { constructor(options: ApiHandlerOptions) {
this.options = options this.options = options
// Azure API shape slightly differs from the core API shape: https://github.com/openai/openai-node?tab=readme-ov-file#microsoft-azure-openai // Azure API shape slightly differs from the core API shape:
// https://github.com/openai/openai-node?tab=readme-ov-file#microsoft-azure-openai
const urlHost = new URL(this.options.openAiBaseUrl ?? "").host const urlHost = new URL(this.options.openAiBaseUrl ?? "").host
if (urlHost === "azure.com" || urlHost.endsWith(".azure.com") || options.openAiUseAzure) { if (urlHost === "azure.com" || urlHost.endsWith(".azure.com") || options.openAiUseAzure) {
this.client = new AzureOpenAI({ this.client = new AzureOpenAI({
@@ -38,7 +41,7 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
const deepseekReasoner = modelId.includes("deepseek-reasoner") const deepseekReasoner = modelId.includes("deepseek-reasoner")
if (!deepseekReasoner && (this.options.openAiStreamingEnabled ?? true)) { if (this.options.openAiStreamingEnabled ?? true) {
const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = { const systemMessage: OpenAI.Chat.ChatCompletionSystemMessageParam = {
role: "system", role: "system",
content: systemPrompt, content: systemPrompt,
@@ -46,7 +49,9 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = {
model: modelId, model: modelId,
temperature: 0, temperature: 0,
messages: [systemMessage, ...convertToOpenAiMessages(messages)], messages: deepseekReasoner
? convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
: [systemMessage, ...convertToOpenAiMessages(messages)],
stream: true as const, stream: true as const,
stream_options: { include_usage: true }, stream_options: { include_usage: true },
} }
@@ -64,6 +69,12 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
text: delta.content, text: delta.content,
} }
} }
if ("reasoning_content" in delta && delta.reasoning_content) {
yield {
type: "reasoning",
text: (delta.reasoning_content as string | undefined) || "",
}
}
if (chunk.usage) { if (chunk.usage) {
yield { yield {
type: "usage", type: "usage",
@@ -73,24 +84,19 @@ export class OpenAiHandler implements ApiHandler, SingleCompletionHandler {
} }
} }
} else { } else {
let systemMessage: OpenAI.Chat.ChatCompletionUserMessageParam | OpenAI.Chat.ChatCompletionSystemMessageParam
// o1 for instance doesnt support streaming, non-1 temp, or system prompt // o1 for instance doesnt support streaming, non-1 temp, or system prompt
// deepseek reasoner supports system prompt const systemMessage: OpenAI.Chat.ChatCompletionUserMessageParam = {
systemMessage = deepseekReasoner
? {
role: "system",
content: systemPrompt,
}
: {
role: "user", role: "user",
content: systemPrompt, content: systemPrompt,
} }
const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { const requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = {
model: modelId, model: modelId,
messages: [systemMessage, ...convertToOpenAiMessages(messages)], messages: deepseekReasoner
? convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
: [systemMessage, ...convertToOpenAiMessages(messages)],
} }
const response = await this.client.chat.completions.create(requestOptions) const response = await this.client.chat.completions.create(requestOptions)
yield { yield {

View File

@@ -19,6 +19,7 @@ interface OpenRouterApiStreamUsageChunk extends ApiStreamUsageChunk {
} }
import { SingleCompletionHandler } from ".." import { SingleCompletionHandler } from ".."
import { convertToR1Format } from "../transform/r1-format"
export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler { export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
private options: ApiHandlerOptions private options: ApiHandlerOptions
@@ -41,7 +42,7 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
messages: Anthropic.Messages.MessageParam[], messages: Anthropic.Messages.MessageParam[],
): AsyncGenerator<ApiStreamChunk> { ): AsyncGenerator<ApiStreamChunk> {
// Convert Anthropic messages to OpenAI format // Convert Anthropic messages to OpenAI format
const openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [ let openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "system", content: systemPrompt }, { role: "system", content: systemPrompt },
...convertToOpenAiMessages(messages), ...convertToOpenAiMessages(messages),
] ]
@@ -117,6 +118,9 @@ export class OpenRouterHandler implements ApiHandler, SingleCompletionHandler {
case "deepseek/deepseek-r1": case "deepseek/deepseek-r1":
// Recommended temperature for DeepSeek reasoning models // Recommended temperature for DeepSeek reasoning models
temperature = 0.6 temperature = 0.6
// DeepSeek highly recommends using user instead of system role
openAiMessages[0].role = "user"
openAiMessages = convertToR1Format([{ role: "user", content: systemPrompt }, ...messages])
} }
// https://openrouter.ai/docs/transforms // https://openrouter.ai/docs/transforms

View File

@@ -0,0 +1,180 @@
import { convertToR1Format } from "../r1-format"
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
describe("convertToR1Format", () => {
it("should convert basic text messages", () => {
const input: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
]
const expected: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there" },
]
expect(convertToR1Format(input)).toEqual(expected)
})
it("should merge consecutive messages with same role", () => {
const input: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "Hello" },
{ role: "user", content: "How are you?" },
{ role: "assistant", content: "Hi!" },
{ role: "assistant", content: "I'm doing well" },
]
const expected: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "user", content: "Hello\nHow are you?" },
{ role: "assistant", content: "Hi!\nI'm doing well" },
]
expect(convertToR1Format(input)).toEqual(expected)
})
it("should handle image content", () => {
const input: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "base64data",
},
},
],
},
]
const expected: OpenAI.Chat.ChatCompletionMessageParam[] = [
{
role: "user",
content: [
{
type: "image_url",
image_url: {
url: "data:image/jpeg;base64,base64data",
},
},
],
},
]
expect(convertToR1Format(input)).toEqual(expected)
})
it("should handle mixed text and image content", () => {
const input: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "Check this image:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "base64data",
},
},
],
},
]
const expected: OpenAI.Chat.ChatCompletionMessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "Check this image:" },
{
type: "image_url",
image_url: {
url: "data:image/jpeg;base64,base64data",
},
},
],
},
]
expect(convertToR1Format(input)).toEqual(expected)
})
it("should merge mixed content messages with same role", () => {
const input: Anthropic.Messages.MessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "First image:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: "image1",
},
},
],
},
{
role: "user",
content: [
{ type: "text", text: "Second image:" },
{
type: "image",
source: {
type: "base64",
media_type: "image/png",
data: "image2",
},
},
],
},
]
const expected: OpenAI.Chat.ChatCompletionMessageParam[] = [
{
role: "user",
content: [
{ type: "text", text: "First image:" },
{
type: "image_url",
image_url: {
url: "data:image/jpeg;base64,image1",
},
},
{ type: "text", text: "Second image:" },
{
type: "image_url",
image_url: {
url: "data:image/png;base64,image2",
},
},
],
},
]
expect(convertToR1Format(input)).toEqual(expected)
})
it("should handle empty messages array", () => {
expect(convertToR1Format([])).toEqual([])
})
it("should handle messages with empty content", () => {
const input: Anthropic.Messages.MessageParam[] = [
{ role: "user", content: "" },
{ role: "assistant", content: "" },
]
const expected: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "user", content: "" },
{ role: "assistant", content: "" },
]
expect(convertToR1Format(input)).toEqual(expected)
})
})

View File

@@ -0,0 +1,98 @@
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
type ContentPartText = OpenAI.Chat.ChatCompletionContentPartText
type ContentPartImage = OpenAI.Chat.ChatCompletionContentPartImage
type UserMessage = OpenAI.Chat.ChatCompletionUserMessageParam
type AssistantMessage = OpenAI.Chat.ChatCompletionAssistantMessageParam
type Message = OpenAI.Chat.ChatCompletionMessageParam
type AnthropicMessage = Anthropic.Messages.MessageParam
/**
* Converts Anthropic messages to OpenAI format while merging consecutive messages with the same role.
* This is required for DeepSeek Reasoner which does not support successive messages with the same role.
*
* @param messages Array of Anthropic messages
* @returns Array of OpenAI messages where consecutive messages with the same role are combined
*/
export function convertToR1Format(messages: AnthropicMessage[]): Message[] {
return messages.reduce<Message[]>((merged, message) => {
const lastMessage = merged[merged.length - 1]
let messageContent: string | (ContentPartText | ContentPartImage)[] = ""
let hasImages = false
// Convert content to appropriate format
if (Array.isArray(message.content)) {
const textParts: string[] = []
const imageParts: ContentPartImage[] = []
message.content.forEach((part) => {
if (part.type === "text") {
textParts.push(part.text)
}
if (part.type === "image") {
hasImages = true
imageParts.push({
type: "image_url",
image_url: { url: `data:${part.source.media_type};base64,${part.source.data}` },
})
}
})
if (hasImages) {
const parts: (ContentPartText | ContentPartImage)[] = []
if (textParts.length > 0) {
parts.push({ type: "text", text: textParts.join("\n") })
}
parts.push(...imageParts)
messageContent = parts
} else {
messageContent = textParts.join("\n")
}
} else {
messageContent = message.content
}
// If last message has same role, merge the content
if (lastMessage?.role === message.role) {
if (typeof lastMessage.content === "string" && typeof messageContent === "string") {
lastMessage.content += `\n${messageContent}`
}
// If either has image content, convert both to array format
else {
const lastContent = Array.isArray(lastMessage.content)
? lastMessage.content
: [{ type: "text" as const, text: lastMessage.content || "" }]
const newContent = Array.isArray(messageContent)
? messageContent
: [{ type: "text" as const, text: messageContent }]
if (message.role === "assistant") {
const mergedContent = [...lastContent, ...newContent] as AssistantMessage["content"]
lastMessage.content = mergedContent
} else {
const mergedContent = [...lastContent, ...newContent] as UserMessage["content"]
lastMessage.content = mergedContent
}
}
} else {
// Add as new message with the correct type based on role
if (message.role === "assistant") {
const newMessage: AssistantMessage = {
role: "assistant",
content: messageContent as AssistantMessage["content"],
}
merged.push(newMessage)
} else {
const newMessage: UserMessage = {
role: "user",
content: messageContent as UserMessage["content"],
}
merged.push(newMessage)
}
}
return merged
}, [])
}

View File

@@ -60,6 +60,8 @@ import { BrowserSession } from "../services/browser/BrowserSession"
import { OpenRouterHandler } from "../api/providers/openrouter" import { OpenRouterHandler } from "../api/providers/openrouter"
import { McpHub } from "../services/mcp/McpHub" import { McpHub } from "../services/mcp/McpHub"
import crypto from "crypto" import crypto from "crypto"
import { insertGroups } from "./diff/insert-groups"
import { EXPERIMENT_IDS, experiments as Experiments } from "../shared/experiments"
const cwd = const cwd =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) ?? path.join(os.homedir(), "Desktop") // may or may not exist but fs checking existence would immediately ask for permission which would be bad UX, need to come up with a better solution
@@ -115,7 +117,7 @@ export class Cline {
task?: string | undefined, task?: string | undefined,
images?: string[] | undefined, images?: string[] | undefined,
historyItem?: HistoryItem | undefined, historyItem?: HistoryItem | undefined,
experimentalDiffStrategy: boolean = false, experiments?: Record<string, boolean>,
) { ) {
if (!task && !images && !historyItem) { if (!task && !images && !historyItem) {
throw new Error("Either historyItem or task/images must be provided") throw new Error("Either historyItem or task/images must be provided")
@@ -137,7 +139,7 @@ export class Cline {
} }
// Initialize diffStrategy based on current state // Initialize diffStrategy based on current state
this.updateDiffStrategy(experimentalDiffStrategy) this.updateDiffStrategy(Experiments.isEnabled(experiments ?? {}, EXPERIMENT_IDS.DIFF_STRATEGY))
if (task || images) { if (task || images) {
this.startTask(task, images) this.startTask(task, images)
@@ -150,9 +152,8 @@ export class Cline {
async updateDiffStrategy(experimentalDiffStrategy?: boolean) { async updateDiffStrategy(experimentalDiffStrategy?: boolean) {
// If not provided, get from current state // If not provided, get from current state
if (experimentalDiffStrategy === undefined) { if (experimentalDiffStrategy === undefined) {
const { experimentalDiffStrategy: stateExperimentalDiffStrategy } = const { experiments: stateExperimental } = (await this.providerRef.deref()?.getState()) ?? {}
(await this.providerRef.deref()?.getState()) ?? {} experimentalDiffStrategy = stateExperimental?.[EXPERIMENT_IDS.DIFF_STRATEGY] ?? false
experimentalDiffStrategy = stateExperimentalDiffStrategy ?? false
} }
this.diffStrategy = getDiffStrategy(this.api.getModel().id, this.fuzzyMatchThreshold, experimentalDiffStrategy) this.diffStrategy = getDiffStrategy(this.api.getModel().id, this.fuzzyMatchThreshold, experimentalDiffStrategy)
} }
@@ -809,7 +810,7 @@ export class Cline {
}) })
} }
const { browserViewportSize, mode, customModePrompts, preferredLanguage } = const { browserViewportSize, mode, customModePrompts, preferredLanguage, experiments } =
(await this.providerRef.deref()?.getState()) ?? {} (await this.providerRef.deref()?.getState()) ?? {}
const { customModes } = (await this.providerRef.deref()?.getState()) ?? {} const { customModes } = (await this.providerRef.deref()?.getState()) ?? {}
const systemPrompt = await (async () => { const systemPrompt = await (async () => {
@@ -830,6 +831,7 @@ export class Cline {
this.customInstructions, this.customInstructions,
preferredLanguage, preferredLanguage,
this.diffEnabled, this.diffEnabled,
experiments,
) )
})() })()
@@ -1008,6 +1010,10 @@ export class Cline {
return `[${block.name} for '${block.params.regex}'${ return `[${block.name} for '${block.params.regex}'${
block.params.file_pattern ? ` in '${block.params.file_pattern}'` : "" block.params.file_pattern ? ` in '${block.params.file_pattern}'` : ""
}]` }]`
case "insert_code_block":
return `[${block.name} for '${block.params.path}']`
case "search_and_replace":
return `[${block.name} for '${block.params.path}']`
case "list_files": case "list_files":
return `[${block.name} for '${block.params.path}']` return `[${block.name} for '${block.params.path}']`
case "list_code_definition_names": case "list_code_definition_names":
@@ -1479,6 +1485,323 @@ export class Cline {
break break
} }
} }
case "insert_code_block": {
const relPath: string | undefined = block.params.path
const operations: string | undefined = block.params.operations
const sharedMessageProps: ClineSayTool = {
tool: "appliedDiff",
path: getReadablePath(cwd, removeClosingTag("path", relPath)),
}
try {
if (block.partial) {
const partialMessage = JSON.stringify(sharedMessageProps)
await this.ask("tool", partialMessage, block.partial).catch(() => {})
break
}
// Validate required parameters
if (!relPath) {
this.consecutiveMistakeCount++
pushToolResult(await this.sayAndCreateMissingParamError("insert_code_block", "path"))
break
}
if (!operations) {
this.consecutiveMistakeCount++
pushToolResult(
await this.sayAndCreateMissingParamError("insert_code_block", "operations"),
)
break
}
const absolutePath = path.resolve(cwd, relPath)
const fileExists = await fileExistsAtPath(absolutePath)
if (!fileExists) {
this.consecutiveMistakeCount++
const formattedError = `File does not exist at path: ${absolutePath}\n\n<error_details>\nThe specified file could not be found. Please verify the file path and try again.\n</error_details>`
await this.say("error", formattedError)
pushToolResult(formattedError)
break
}
let parsedOperations: Array<{
start_line: number
content: string
}>
try {
parsedOperations = JSON.parse(operations)
if (!Array.isArray(parsedOperations)) {
throw new Error("Operations must be an array")
}
} catch (error) {
this.consecutiveMistakeCount++
await this.say("error", `Failed to parse operations JSON: ${error.message}`)
pushToolResult(formatResponse.toolError("Invalid operations JSON format"))
break
}
this.consecutiveMistakeCount = 0
// Read the file
const fileContent = await fs.readFile(absolutePath, "utf8")
this.diffViewProvider.editType = "modify"
this.diffViewProvider.originalContent = fileContent
const lines = fileContent.split("\n")
const updatedContent = insertGroups(
lines,
parsedOperations.map((elem) => {
return {
index: elem.start_line - 1,
elements: elem.content.split("\n"),
}
}),
).join("\n")
// Show changes in diff view
if (!this.diffViewProvider.isEditing) {
await this.ask("tool", JSON.stringify(sharedMessageProps), true).catch(() => {})
// First open with original content
await this.diffViewProvider.open(relPath)
await this.diffViewProvider.update(fileContent, false)
this.diffViewProvider.scrollToFirstDiff()
await delay(200)
}
const diff = formatResponse.createPrettyPatch(relPath, fileContent, updatedContent)
if (!diff) {
pushToolResult(`No changes needed for '${relPath}'`)
break
}
await this.diffViewProvider.update(updatedContent, true)
const completeMessage = JSON.stringify({
...sharedMessageProps,
diff,
} satisfies ClineSayTool)
const didApprove = await this.ask("tool", completeMessage, false).then(
(response) => response.response === "yesButtonClicked",
)
if (!didApprove) {
await this.diffViewProvider.revertChanges()
pushToolResult("Changes were rejected by the user.")
break
}
const { newProblemsMessage, userEdits, finalContent } =
await this.diffViewProvider.saveChanges()
this.didEditFile = true
if (!userEdits) {
pushToolResult(
`The code block was successfully inserted in ${relPath.toPosix()}.${newProblemsMessage}`,
)
await this.diffViewProvider.reset()
break
}
const userFeedbackDiff = JSON.stringify({
tool: "appliedDiff",
path: getReadablePath(cwd, relPath),
diff: userEdits,
} satisfies ClineSayTool)
console.debug("[DEBUG] User made edits, sending feedback diff:", userFeedbackDiff)
await this.say("user_feedback_diff", userFeedbackDiff)
pushToolResult(
`The user made the following updates to your content:\n\n${userEdits}\n\n` +
`The updated content, which includes both your original modifications and the user's edits, has been successfully saved to ${relPath.toPosix()}. Here is the full, updated content of the file:\n\n` +
`<final_file_content path="${relPath.toPosix()}">\n${finalContent}\n</final_file_content>\n\n` +
`Please note:\n` +
`1. You do not need to re-write the file with these changes, as they have already been applied.\n` +
`2. Proceed with the task using this updated file content as the new baseline.\n` +
`3. If the user's edits have addressed part of the task or changed the requirements, adjust your approach accordingly.` +
`${newProblemsMessage}`,
)
await this.diffViewProvider.reset()
} catch (error) {
handleError("insert block", error)
await this.diffViewProvider.reset()
}
break
}
case "search_and_replace": {
const relPath: string | undefined = block.params.path
const operations: string | undefined = block.params.operations
const sharedMessageProps: ClineSayTool = {
tool: "appliedDiff",
path: getReadablePath(cwd, removeClosingTag("path", relPath)),
}
try {
if (block.partial) {
const partialMessage = JSON.stringify({
path: removeClosingTag("path", relPath),
operations: removeClosingTag("operations", operations),
})
await this.ask("tool", partialMessage, block.partial).catch(() => {})
break
} else {
if (!relPath) {
this.consecutiveMistakeCount++
pushToolResult(
await this.sayAndCreateMissingParamError("search_and_replace", "path"),
)
break
}
if (!operations) {
this.consecutiveMistakeCount++
pushToolResult(
await this.sayAndCreateMissingParamError("search_and_replace", "operations"),
)
break
}
const absolutePath = path.resolve(cwd, relPath)
const fileExists = await fileExistsAtPath(absolutePath)
if (!fileExists) {
this.consecutiveMistakeCount++
const formattedError = `File does not exist at path: ${absolutePath}\n\n<error_details>\nThe specified file could not be found. Please verify the file path and try again.\n</error_details>`
await this.say("error", formattedError)
pushToolResult(formattedError)
break
}
let parsedOperations: Array<{
search: string
replace: string
start_line?: number
end_line?: number
use_regex?: boolean
ignore_case?: boolean
regex_flags?: string
}>
try {
parsedOperations = JSON.parse(operations)
if (!Array.isArray(parsedOperations)) {
throw new Error("Operations must be an array")
}
} catch (error) {
this.consecutiveMistakeCount++
await this.say("error", `Failed to parse operations JSON: ${error.message}`)
pushToolResult(formatResponse.toolError("Invalid operations JSON format"))
break
}
// Read the original file content
const fileContent = await fs.readFile(absolutePath, "utf-8")
this.diffViewProvider.editType = "modify"
this.diffViewProvider.originalContent = fileContent
let lines = fileContent.split("\n")
for (const op of parsedOperations) {
const flags = op.regex_flags ?? (op.ignore_case ? "gi" : "g")
const multilineFlags = flags.includes("m") ? flags : flags + "m"
const searchPattern = op.use_regex
? new RegExp(op.search, multilineFlags)
: new RegExp(escapeRegExp(op.search), multilineFlags)
if (op.start_line || op.end_line) {
const startLine = Math.max((op.start_line ?? 1) - 1, 0)
const endLine = Math.min((op.end_line ?? lines.length) - 1, lines.length - 1)
// Get the content before and after the target section
const beforeLines = lines.slice(0, startLine)
const afterLines = lines.slice(endLine + 1)
// Get the target section and perform replacement
const targetContent = lines.slice(startLine, endLine + 1).join("\n")
const modifiedContent = targetContent.replace(searchPattern, op.replace)
const modifiedLines = modifiedContent.split("\n")
// Reconstruct the full content with the modified section
lines = [...beforeLines, ...modifiedLines, ...afterLines]
} else {
// Global replacement
const fullContent = lines.join("\n")
const modifiedContent = fullContent.replace(searchPattern, op.replace)
lines = modifiedContent.split("\n")
}
}
const newContent = lines.join("\n")
this.consecutiveMistakeCount = 0
// Show diff preview
const diff = formatResponse.createPrettyPatch(relPath, fileContent, newContent)
if (!diff) {
pushToolResult(`No changes needed for '${relPath}'`)
break
}
await this.diffViewProvider.open(relPath)
await this.diffViewProvider.update(newContent, true)
this.diffViewProvider.scrollToFirstDiff()
const completeMessage = JSON.stringify({
...sharedMessageProps,
diff: diff,
} satisfies ClineSayTool)
const didApprove = await askApproval("tool", completeMessage)
if (!didApprove) {
await this.diffViewProvider.revertChanges() // This likely handles closing the diff view
break
}
const { newProblemsMessage, userEdits, finalContent } =
await this.diffViewProvider.saveChanges()
this.didEditFile = true // used to determine if we should wait for busy terminal to update before sending api request
if (userEdits) {
await this.say(
"user_feedback_diff",
JSON.stringify({
tool: fileExists ? "editedExistingFile" : "newFileCreated",
path: getReadablePath(cwd, relPath),
diff: userEdits,
} satisfies ClineSayTool),
)
pushToolResult(
`The user made the following updates to your content:\n\n${userEdits}\n\n` +
`The updated content, which includes both your original modifications and the user's edits, has been successfully saved to ${relPath.toPosix()}. Here is the full, updated content of the file, including line numbers:\n\n` +
`<final_file_content path="${relPath.toPosix()}">\n${addLineNumbers(finalContent || "")}\n</final_file_content>\n\n` +
`Please note:\n` +
`1. You do not need to re-write the file with these changes, as they have already been applied.\n` +
`2. Proceed with the task using this updated file content as the new baseline.\n` +
`3. If the user's edits have addressed part of the task or changed the requirements, adjust your approach accordingly.` +
`${newProblemsMessage}`,
)
} else {
pushToolResult(
`Changes successfully applied to ${relPath.toPosix()}:\n\n${newProblemsMessage}`,
)
}
await this.diffViewProvider.reset()
break
}
} catch (error) {
await handleError("applying search and replace", error)
await this.diffViewProvider.reset()
break
}
}
case "read_file": { case "read_file": {
const relPath: string | undefined = block.params.path const relPath: string | undefined = block.params.path
const sharedMessageProps: ClineSayTool = { const sharedMessageProps: ClineSayTool = {
@@ -2072,6 +2395,7 @@ export class Cline {
targetMode.name targetMode.name
} mode${reason ? ` because: ${reason}` : ""}.`, } mode${reason ? ` because: ${reason}` : ""}.`,
) )
await delay(500) // delay to allow mode change to take effect before next tool is executed
break break
} }
} catch (error) { } catch (error) {
@@ -2391,6 +2715,10 @@ export class Cline {
let reasoningMessage = "" let reasoningMessage = ""
try { try {
for await (const chunk of stream) { for await (const chunk of stream) {
if (!chunk) {
// Sometimes chunk is undefined, no idea that can cause it, but this workaround seems to fix it
continue
}
switch (chunk.type) { switch (chunk.type) {
case "reasoning": case "reasoning":
reasoningMessage += chunk.text reasoningMessage += chunk.text
@@ -2746,3 +3074,7 @@ export class Cline {
return `<environment_details>\n${details.trim()}\n</environment_details>` return `<environment_details>\n${details.trim()}\n</environment_details>`
} }
} }
function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
}

View File

@@ -1,5 +1,6 @@
import * as vscode from "vscode" import * as vscode from "vscode"
import * as path from "path" import * as path from "path"
import { ClineProvider } from "./webview/ClineProvider"
export const ACTION_NAMES = { export const ACTION_NAMES = {
EXPLAIN: "Roo Code: Explain Code", EXPLAIN: "Roo Code: Explain Code",
@@ -113,6 +114,18 @@ export class CodeActionProvider implements vscode.CodeActionProvider {
return action return action
} }
private createActionPair(
baseTitle: string,
kind: vscode.CodeActionKind,
baseCommand: string,
args: any[],
): vscode.CodeAction[] {
return [
this.createAction(`${baseTitle} in New Task`, kind, baseCommand, args),
this.createAction(`${baseTitle} in Current Task`, kind, `${baseCommand}InCurrentTask`, args),
]
}
private hasIntersectingRange(range1: vscode.Range, range2: vscode.Range): boolean { private hasIntersectingRange(range1: vscode.Range, range2: vscode.Range): boolean {
// Optimize range intersection check // Optimize range intersection check
return !( return !(
@@ -138,8 +151,9 @@ export class CodeActionProvider implements vscode.CodeActionProvider {
const actions: vscode.CodeAction[] = [] const actions: vscode.CodeAction[] = []
// Create actions using helper method // Create actions using helper method
// Add explain actions
actions.push( actions.push(
this.createAction(ACTION_NAMES.EXPLAIN, vscode.CodeActionKind.QuickFix, COMMAND_IDS.EXPLAIN, [ ...this.createActionPair(ACTION_NAMES.EXPLAIN, vscode.CodeActionKind.QuickFix, COMMAND_IDS.EXPLAIN, [
filePath, filePath,
effectiveRange.text, effectiveRange.text,
]), ]),
@@ -154,7 +168,7 @@ export class CodeActionProvider implements vscode.CodeActionProvider {
if (relevantDiagnostics.length > 0) { if (relevantDiagnostics.length > 0) {
const diagnosticMessages = relevantDiagnostics.map(this.createDiagnosticData) const diagnosticMessages = relevantDiagnostics.map(this.createDiagnosticData)
actions.push( actions.push(
this.createAction(ACTION_NAMES.FIX, vscode.CodeActionKind.QuickFix, COMMAND_IDS.FIX, [ ...this.createActionPair(ACTION_NAMES.FIX, vscode.CodeActionKind.QuickFix, COMMAND_IDS.FIX, [
filePath, filePath,
effectiveRange.text, effectiveRange.text,
diagnosticMessages, diagnosticMessages,
@@ -163,11 +177,14 @@ export class CodeActionProvider implements vscode.CodeActionProvider {
} }
} }
// Add improve actions
actions.push( actions.push(
this.createAction(ACTION_NAMES.IMPROVE, vscode.CodeActionKind.RefactorRewrite, COMMAND_IDS.IMPROVE, [ ...this.createActionPair(
filePath, ACTION_NAMES.IMPROVE,
effectiveRange.text, vscode.CodeActionKind.RefactorRewrite,
]), COMMAND_IDS.IMPROVE,
[filePath, effectiveRange.text],
),
) )
return actions return actions

View File

@@ -1,5 +1,5 @@
import * as vscode from "vscode" import * as vscode from "vscode"
import { CodeActionProvider } from "../CodeActionProvider" import { CodeActionProvider, ACTION_NAMES } from "../CodeActionProvider"
// Mock VSCode API // Mock VSCode API
jest.mock("vscode", () => ({ jest.mock("vscode", () => ({
@@ -109,9 +109,11 @@ describe("CodeActionProvider", () => {
it("should provide explain and improve actions by default", () => { it("should provide explain and improve actions by default", () => {
const actions = provider.provideCodeActions(mockDocument, mockRange, mockContext) const actions = provider.provideCodeActions(mockDocument, mockRange, mockContext)
expect(actions).toHaveLength(2) expect(actions).toHaveLength(4)
expect((actions as any)[0].title).toBe("Roo Code: Explain Code") expect((actions as any)[0].title).toBe(`${ACTION_NAMES.EXPLAIN} in New Task`)
expect((actions as any)[1].title).toBe("Roo Code: Improve Code") expect((actions as any)[1].title).toBe(`${ACTION_NAMES.EXPLAIN} in Current Task`)
expect((actions as any)[2].title).toBe(`${ACTION_NAMES.IMPROVE} in New Task`)
expect((actions as any)[3].title).toBe(`${ACTION_NAMES.IMPROVE} in Current Task`)
}) })
it("should provide fix action when diagnostics exist", () => { it("should provide fix action when diagnostics exist", () => {
@@ -125,8 +127,9 @@ describe("CodeActionProvider", () => {
const actions = provider.provideCodeActions(mockDocument, mockRange, mockContext) const actions = provider.provideCodeActions(mockDocument, mockRange, mockContext)
expect(actions).toHaveLength(3) expect(actions).toHaveLength(6)
expect((actions as any).some((a: any) => a.title === "Roo Code: Fix Code")).toBe(true) expect((actions as any).some((a: any) => a.title === `${ACTION_NAMES.FIX} in New Task`)).toBe(true)
expect((actions as any).some((a: any) => a.title === `${ACTION_NAMES.FIX} in Current Task`)).toBe(true)
}) })
it("should handle errors gracefully", () => { it("should handle errors gracefully", () => {

View File

@@ -13,6 +13,8 @@ export const toolUseNames = [
"read_file", "read_file",
"write_to_file", "write_to_file",
"apply_diff", "apply_diff",
"insert_code_block",
"search_and_replace",
"search_files", "search_files",
"list_files", "list_files",
"list_code_definition_names", "list_code_definition_names",
@@ -50,6 +52,7 @@ export const toolParamNames = [
"end_line", "end_line",
"mode_slug", "mode_slug",
"reason", "reason",
"operations",
] as const ] as const
export type ToolParamName = (typeof toolParamNames)[number] export type ToolParamName = (typeof toolParamNames)[number]
@@ -78,6 +81,11 @@ export interface WriteToFileToolUse extends ToolUse {
params: Partial<Pick<Record<ToolParamName, string>, "path" | "content" | "line_count">> params: Partial<Pick<Record<ToolParamName, string>, "path" | "content" | "line_count">>
} }
export interface InsertCodeBlockToolUse extends ToolUse {
name: "insert_code_block"
params: Partial<Pick<Record<ToolParamName, string>, "path" | "operations">>
}
export interface SearchFilesToolUse extends ToolUse { export interface SearchFilesToolUse extends ToolUse {
name: "search_files" name: "search_files"
params: Partial<Pick<Record<ToolParamName, string>, "path" | "regex" | "file_pattern">> params: Partial<Pick<Record<ToolParamName, string>, "path" | "regex" | "file_pattern">>

View File

@@ -0,0 +1,31 @@
/**
* Inserts multiple groups of elements at specified indices in an array
* @param original Array to insert into, split by lines
* @param insertGroups Array of groups to insert, each with an index and elements to insert
* @returns New array with all insertions applied
*/
export interface InsertGroup {
index: number
elements: string[]
}
export function insertGroups(original: string[], insertGroups: InsertGroup[]): string[] {
// Sort groups by index to maintain order
insertGroups.sort((a, b) => a.index - b.index)
let result: string[] = []
let lastIndex = 0
insertGroups.forEach(({ index, elements }) => {
// Add elements from original array up to insertion point
result.push(...original.slice(lastIndex, index))
// Add the group of elements
result.push(...elements)
lastIndex = index
})
// Add remaining elements from original array
result.push(...original.slice(lastIndex))
return result
}

View File

@@ -273,7 +273,7 @@ Your search/replace content here
: "" : ""
return { return {
success: false, success: false,
error: `No sufficiently similar match found${lineRange} (${Math.floor(bestMatchScore * 100)}% similar, needs ${Math.floor(this.fuzzyThreshold * 100)}%)\n\nDebug Info:\n- Similarity Score: ${Math.floor(bestMatchScore * 100)}%\n- Required Threshold: ${Math.floor(this.fuzzyThreshold * 100)}%\n- Search Range: ${startLine && endLine ? `lines ${startLine}-${endLine}` : "start to end"}\n\nSearch Content:\n${searchChunk}${bestMatchSection}${originalContentSection}`, error: `No sufficiently similar match found${lineRange} (${Math.floor(bestMatchScore * 100)}% similar, needs ${Math.floor(this.fuzzyThreshold * 100)}%)\n\nDebug Info:\n- Similarity Score: ${Math.floor(bestMatchScore * 100)}%\n- Required Threshold: ${Math.floor(this.fuzzyThreshold * 100)}%\n- Search Range: ${startLine && endLine ? `lines ${startLine}-${endLine}` : "start to end"}\n- Tip: Use read_file to get the latest content of the file before attempting the diff again, as the file content may have changed\n\nSearch Content:\n${searchChunk}${bestMatchSection}${originalContentSection}`,
} }
} }

View File

@@ -248,11 +248,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -264,7 +263,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -553,11 +551,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -569,7 +566,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -858,11 +854,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -874,7 +869,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -1211,11 +1205,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -1228,7 +1221,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. 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. - 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. 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.
@@ -1930,11 +1922,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -1946,7 +1937,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -2283,11 +2273,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -2300,7 +2289,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. 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. - 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. 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.
@@ -2649,11 +2637,12 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- You should use apply_diff instead of write_to_file when making changes to existing files since it is much faster and easier to apply a diff than to write the entire file again. Only use write_to_file to edit files when apply_diff has failed repeatedly to apply the diff. - For editing files, you have access to these tools: write_to_file (for creating new files or complete file rewrites), apply_diff (for replacing lines in existing files).
- When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -2665,7 +2654,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -2954,11 +2942,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -2970,7 +2957,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -3302,11 +3288,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -3318,7 +3303,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.
@@ -3593,11 +3577,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '/test/path', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '/test/path'). For example, if you needed to run \`npm install\` in a project outside of '/test/path', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool. - When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -3609,7 +3592,6 @@ RULES
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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. - 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.

View File

@@ -11,6 +11,7 @@ import { defaultModeSlug, modes } from "../../../shared/modes"
import "../../../utils/path" import "../../../utils/path"
import { addCustomInstructions } from "../sections/custom-instructions" import { addCustomInstructions } from "../sections/custom-instructions"
import * as modesSection from "../sections/modes" import * as modesSection from "../sections/modes"
import { EXPERIMENT_IDS } from "../../../shared/experiments"
// Mock the sections // Mock the sections
jest.mock("../sections/modes", () => ({ jest.mock("../sections/modes", () => ({
@@ -121,6 +122,7 @@ const createMockMcpHub = (): McpHub =>
describe("SYSTEM_PROMPT", () => { describe("SYSTEM_PROMPT", () => {
let mockMcpHub: McpHub let mockMcpHub: McpHub
let experiments: Record<string, boolean>
beforeAll(() => { beforeAll(() => {
// Ensure fs mock is properly initialized // Ensure fs mock is properly initialized
@@ -140,6 +142,10 @@ describe("SYSTEM_PROMPT", () => {
"/mock/mcp/path", "/mock/mcp/path",
] ]
dirs.forEach((dir) => mockFs._mockDirectories.add(dir)) dirs.forEach((dir) => mockFs._mockDirectories.add(dir))
experiments = {
[EXPERIMENT_IDS.SEARCH_AND_REPLACE]: false,
[EXPERIMENT_IDS.INSERT_BLOCK]: false,
}
}) })
beforeEach(() => { beforeEach(() => {
@@ -164,6 +170,10 @@ describe("SYSTEM_PROMPT", () => {
defaultModeSlug, // mode defaultModeSlug, // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()
@@ -179,7 +189,11 @@ describe("SYSTEM_PROMPT", () => {
"1280x800", // browserViewportSize "1280x800", // browserViewportSize
defaultModeSlug, // mode defaultModeSlug, // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes,
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()
@@ -197,7 +211,11 @@ describe("SYSTEM_PROMPT", () => {
undefined, // browserViewportSize undefined, // browserViewportSize
defaultModeSlug, // mode defaultModeSlug, // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes,
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()
@@ -213,7 +231,11 @@ describe("SYSTEM_PROMPT", () => {
undefined, // browserViewportSize undefined, // browserViewportSize
defaultModeSlug, // mode defaultModeSlug, // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes,
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()
@@ -229,7 +251,11 @@ describe("SYSTEM_PROMPT", () => {
"900x600", // different viewport size "900x600", // different viewport size
defaultModeSlug, // mode defaultModeSlug, // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes,
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()
@@ -249,6 +275,7 @@ describe("SYSTEM_PROMPT", () => {
undefined, // globalCustomInstructions undefined, // globalCustomInstructions
undefined, // preferredLanguage undefined, // preferredLanguage
true, // diffEnabled true, // diffEnabled
experiments,
) )
expect(prompt).toContain("apply_diff") expect(prompt).toContain("apply_diff")
@@ -269,6 +296,7 @@ describe("SYSTEM_PROMPT", () => {
undefined, // globalCustomInstructions undefined, // globalCustomInstructions
undefined, // preferredLanguage undefined, // preferredLanguage
false, // diffEnabled false, // diffEnabled
experiments,
) )
expect(prompt).not.toContain("apply_diff") expect(prompt).not.toContain("apply_diff")
@@ -289,6 +317,7 @@ describe("SYSTEM_PROMPT", () => {
undefined, // globalCustomInstructions undefined, // globalCustomInstructions
undefined, // preferredLanguage undefined, // preferredLanguage
undefined, // diffEnabled undefined, // diffEnabled
experiments,
) )
expect(prompt).not.toContain("apply_diff") expect(prompt).not.toContain("apply_diff")
@@ -308,6 +337,8 @@ describe("SYSTEM_PROMPT", () => {
undefined, // customModes undefined, // customModes
undefined, // globalCustomInstructions undefined, // globalCustomInstructions
"Spanish", // preferredLanguage "Spanish", // preferredLanguage
undefined, // diffEnabled
experiments,
) )
expect(prompt).toContain("Language Preference:") expect(prompt).toContain("Language Preference:")
@@ -337,6 +368,9 @@ describe("SYSTEM_PROMPT", () => {
undefined, // customModePrompts undefined, // customModePrompts
customModes, // customModes customModes, // customModes
"Global instructions", // globalCustomInstructions "Global instructions", // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
) )
// Role definition should be at the top // Role definition should be at the top
@@ -368,6 +402,10 @@ describe("SYSTEM_PROMPT", () => {
defaultModeSlug, defaultModeSlug,
customModePrompts, customModePrompts,
undefined, undefined,
undefined,
undefined,
undefined,
experiments,
) )
// Role definition from promptComponent should be at the top // Role definition from promptComponent should be at the top
@@ -394,18 +432,160 @@ describe("SYSTEM_PROMPT", () => {
defaultModeSlug, defaultModeSlug,
customModePrompts, customModePrompts,
undefined, undefined,
undefined,
undefined,
undefined,
experiments,
) )
// Should use the default mode's role definition // Should use the default mode's role definition
expect(prompt.indexOf(modes[0].roleDefinition)).toBeLessThan(prompt.indexOf("TOOL USE")) expect(prompt.indexOf(modes[0].roleDefinition)).toBeLessThan(prompt.indexOf("TOOL USE"))
}) })
describe("experimental tools", () => {
it("should disable experimental tools by default", async () => {
const prompt = await SYSTEM_PROMPT(
mockContext,
"/test/path",
false, // supportsComputerUse
undefined, // mcpHub
undefined, // diffStrategy
undefined, // browserViewportSize
defaultModeSlug, // mode
undefined, // customModePrompts
undefined, // customModes
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments, // experiments - undefined should disable all experimental tools
)
// Verify experimental tools are not included in the prompt
expect(prompt).not.toContain(EXPERIMENT_IDS.SEARCH_AND_REPLACE)
expect(prompt).not.toContain(EXPERIMENT_IDS.INSERT_BLOCK)
})
it("should enable experimental tools when explicitly enabled", async () => {
const experiments = {
[EXPERIMENT_IDS.SEARCH_AND_REPLACE]: true,
[EXPERIMENT_IDS.INSERT_BLOCK]: true,
}
const prompt = await SYSTEM_PROMPT(
mockContext,
"/test/path",
false, // supportsComputerUse
undefined, // mcpHub
undefined, // diffStrategy
undefined, // browserViewportSize
defaultModeSlug, // mode
undefined, // customModePrompts
undefined, // customModes
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
)
// Verify experimental tools are included in the prompt when enabled
expect(prompt).toContain(EXPERIMENT_IDS.SEARCH_AND_REPLACE)
expect(prompt).toContain(EXPERIMENT_IDS.INSERT_BLOCK)
})
it("should selectively enable experimental tools", async () => {
const experiments = {
[EXPERIMENT_IDS.SEARCH_AND_REPLACE]: true,
[EXPERIMENT_IDS.INSERT_BLOCK]: false,
}
const prompt = await SYSTEM_PROMPT(
mockContext,
"/test/path",
false, // supportsComputerUse
undefined, // mcpHub
undefined, // diffStrategy
undefined, // browserViewportSize
defaultModeSlug, // mode
undefined, // customModePrompts
undefined, // customModes
undefined, // globalCustomInstructions
undefined, // preferredLanguage
undefined, // diffEnabled
experiments,
)
// Verify only enabled experimental tools are included
expect(prompt).toContain(EXPERIMENT_IDS.SEARCH_AND_REPLACE)
expect(prompt).not.toContain(EXPERIMENT_IDS.INSERT_BLOCK)
})
it("should list all available editing tools in base instruction", async () => {
const experiments = {
[EXPERIMENT_IDS.SEARCH_AND_REPLACE]: true,
[EXPERIMENT_IDS.INSERT_BLOCK]: true,
}
const prompt = await SYSTEM_PROMPT(
mockContext,
"/test/path",
false,
undefined,
new SearchReplaceDiffStrategy(),
undefined,
defaultModeSlug,
undefined,
undefined,
undefined,
undefined,
true, // diffEnabled
experiments,
)
// Verify base instruction lists all available tools
expect(prompt).toContain("apply_diff (for replacing lines in existing files)")
expect(prompt).toContain("write_to_file (for creating new files or complete file rewrites)")
expect(prompt).toContain("insert_code_block (for adding sections to existing files)")
expect(prompt).toContain("search_and_replace (for finding and replacing individual pieces of text)")
})
it("should provide detailed instructions for each enabled tool", async () => {
const experiments = {
[EXPERIMENT_IDS.SEARCH_AND_REPLACE]: true,
[EXPERIMENT_IDS.INSERT_BLOCK]: true,
}
const prompt = await SYSTEM_PROMPT(
mockContext,
"/test/path",
false,
undefined,
new SearchReplaceDiffStrategy(),
undefined,
defaultModeSlug,
undefined,
undefined,
undefined,
undefined,
true,
experiments,
)
// Verify detailed instructions for each tool
expect(prompt).toContain(
"You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files.",
)
expect(prompt).toContain("The insert_code_block tool adds code snippets or content blocks to files")
expect(prompt).toContain("The search_and_replace tool finds and replaces text or regex in files")
})
})
afterAll(() => { afterAll(() => {
jest.restoreAllMocks() jest.restoreAllMocks()
}) })
}) })
describe("addCustomInstructions", () => { describe("addCustomInstructions", () => {
let experiments: Record<string, boolean>
beforeAll(() => { beforeAll(() => {
// Ensure fs mock is properly initialized // Ensure fs mock is properly initialized
const mockFs = jest.requireMock("fs/promises") const mockFs = jest.requireMock("fs/promises")
@@ -417,6 +597,11 @@ describe("addCustomInstructions", () => {
} }
throw new Error(`ENOENT: no such file or directory, mkdir '${path}'`) throw new Error(`ENOENT: no such file or directory, mkdir '${path}'`)
}) })
experiments = {
[EXPERIMENT_IDS.SEARCH_AND_REPLACE]: false,
[EXPERIMENT_IDS.INSERT_BLOCK]: false,
}
}) })
beforeEach(() => { beforeEach(() => {
@@ -434,6 +619,10 @@ describe("addCustomInstructions", () => {
"architect", // mode "architect", // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes
undefined,
undefined,
undefined,
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()
@@ -450,6 +639,10 @@ describe("addCustomInstructions", () => {
"ask", // mode "ask", // mode
undefined, // customModePrompts undefined, // customModePrompts
undefined, // customModes undefined, // customModes
undefined,
undefined,
undefined,
experiments,
) )
expect(prompt).toMatchSnapshot() expect(prompt).toMatchSnapshot()

View File

@@ -3,14 +3,58 @@ import { modes, ModeConfig } from "../../../shared/modes"
import * as vscode from "vscode" import * as vscode from "vscode"
import * as path from "path" import * as path from "path"
function getEditingInstructions(diffStrategy?: DiffStrategy, experiments?: Record<string, boolean>): string {
const instructions: string[] = []
const availableTools: string[] = ["write_to_file (for creating new files or complete file rewrites)"]
// Collect available editing tools
if (diffStrategy) {
availableTools.push("apply_diff (for replacing lines in existing files)")
}
if (experiments?.["insert_code_block"]) {
availableTools.push("insert_code_block (for adding sections to existing files)")
}
if (experiments?.["search_and_replace"]) {
availableTools.push("search_and_replace (for finding and replacing individual pieces of text)")
}
// Base editing instruction mentioning all available tools
if (availableTools.length > 1) {
instructions.push(`- For editing files, you have access to these tools: ${availableTools.join(", ")}.`)
}
// Additional details for experimental features
if (experiments?.["insert_code_block"]) {
instructions.push(
"- The insert_code_block tool adds code snippets or content blocks to files, such as adding a new function to a JavaScript file or inserting a new route in a Python file. This tool will insert it at the specified line location. It can support multiple operations at once.",
)
}
if (experiments?.["search_and_replace"]) {
instructions.push(
"- The search_and_replace tool finds and replaces text or regex in files. This tool allows you to search for a specific regex pattern or text and replace it with another value. Be cautious when using this tool to ensure you are replacing the correct text. It can support multiple operations at once.",
)
}
instructions.push(
"- When using the write_to_file tool to modify a file, use the tool directly with the desired content. You do not need to display the content before using the 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.",
)
if (availableTools.length > 1) {
instructions.push(
"- You should always prefer using other editing tools over write_to_file when making changes to existing files since write_to_file is much slower and cannot handle large files.",
)
}
return instructions.join("\n")
}
export function getRulesSection( export function getRulesSection(
cwd: string, cwd: string,
supportsComputerUse: boolean, supportsComputerUse: boolean,
diffStrategy?: DiffStrategy, diffStrategy?: DiffStrategy,
context?: vscode.ExtensionContext, experiments?: Record<string, boolean> | undefined,
): string { ): string {
const settingsDir = context ? path.join(context.globalStorageUri.fsPath, "settings") : "<settings directory>"
const customModesPath = path.join(settingsDir, "cline_custom_modes.json")
return `==== return `====
RULES RULES
@@ -21,15 +65,10 @@ RULES
- Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`. - Before using the execute_command tool, you must first think about the SYSTEM INFORMATION context provided to understand the user's environment and tailor your commands to ensure they are compatible with their system. You must also consider if the command you need to run should be executed in a specific directory outside of the current working directory '${cwd.toPosix()}', and if so prepend with \`cd\`'ing into that directory && then executing the command (as one command since you are stuck operating from '${cwd.toPosix()}'). For example, if you needed to run \`npm install\` in a project outside of '${cwd.toPosix()}', you would need to prepend with a \`cd\` i.e. pseudocode for this would be \`cd (path to project) && (command, in this case npm install)\`.
- When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes. - When using the search_files tool, craft your regex patterns carefully to balance specificity and flexibility. Based on the user's task you may use it to find code patterns, TODO comments, function definitions, or any text-based information across the project. The results include context, so analyze the surrounding code to better understand the matches. Leverage the search_files tool in combination with other tools for more comprehensive analysis. For example, use it to find specific code patterns, then use read_file to examine the full context of interesting matches before using write_to_file to make informed changes.
- When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser. - When creating a new project (such as an app, website, or any software project), organize all new files within a dedicated project directory unless the user specifies otherwise. Use appropriate file paths when writing files, as the write_to_file tool will automatically create any necessary directories. Structure the project logically, adhering to best practices for the specific type of project being created. Unless otherwise specified, new projects should be easily run without additional setup, for example most projects can be built in HTML, CSS, and JavaScript - which you can open in a browser.
${ ${getEditingInstructions(diffStrategy, experiments)}
diffStrategy
? "- You should use apply_diff instead of write_to_file when making changes to existing files since it is much faster and easier to apply a diff than to write the entire file again. Only use write_to_file to edit files when apply_diff has failed repeatedly to apply the diff."
: "- When you want to modify a file, use the write_to_file tool directly with the desired content. You do not need to display the content before using the tool."
}
- Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode. - Some modes have restrictions on which files they can edit. If you attempt to edit a restricted file, the operation will be rejected with a FileRestrictionError that will specify which file patterns are allowed for the current mode.
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write. - Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
* For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$" * For example, in architect mode trying to edit app.js would be rejected because architect mode can only edit files matching "\\.md$"
- Be sure to consider the type of project (e.g. Python, JavaScript, web application) when determining the appropriate structure and files to include. Also consider what files may be most relevant to accomplishing the task, for example looking at a project's manifest file would help you understand the project's dependencies, which you could incorporate into any code you write.
- When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices. - When making changes to code, always consider the context in which the code is being used. Ensure that your changes are compatible with the existing codebase and that they follow the project's coding standards and best practices.
- Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again.
- You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves. - You are only allowed to ask the user questions using the ask_followup_question tool. Use this tool only when you need additional details to complete a task, and be sure to use a clear and concise question that will help you move forward with the task. However if you can use the available tools to avoid having to ask the user questions, you should do so. For example, if the user mentions a file that may be in an outside directory like the Desktop, you should use the list_files tool to list the files in the Desktop and check if the file they are talking about is there, rather than asking the user to provide the file path themselves.
@@ -45,7 +84,6 @@ ${
- 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. - 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.
- At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details. - At the end of each user message, you will automatically receive environment_details. This information is not written by the user themselves, but is auto-generated to provide potentially relevant context about the project structure and environment. While this information can be valuable for understanding the project context, do not treat it as a direct part of the user's request or response. Use it to inform your actions and decisions, but don't assume the user is explicitly asking about or referring to this information unless they clearly do so in their message. When using environment_details, explain your actions clearly to ensure the user understands, as they may not be aware of these details.
- Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal. - Before executing commands, check the "Actively Running Terminals" section in environment_details. If present, consider how these active processes might impact your task. For example, if a local development server is already running, you wouldn't need to start it again. If no active terminals are listed, proceed with command execution as normal.
- 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. - 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.${ - 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 supportsComputerUse

View File

@@ -39,6 +39,7 @@ async function generatePrompt(
globalCustomInstructions?: string, globalCustomInstructions?: string,
preferredLanguage?: string, preferredLanguage?: string,
diffEnabled?: boolean, diffEnabled?: boolean,
experiments?: Record<string, boolean>,
): Promise<string> { ): Promise<string> {
if (!context) { if (!context) {
throw new Error("Extension context is required for generating system prompt") throw new Error("Extension context is required for generating system prompt")
@@ -68,6 +69,7 @@ ${getToolDescriptionsForMode(
browserViewportSize, browserViewportSize,
mcpHub, mcpHub,
customModeConfigs, customModeConfigs,
experiments,
)} )}
${getToolUseGuidelinesSection()} ${getToolUseGuidelinesSection()}
@@ -78,7 +80,7 @@ ${getCapabilitiesSection(cwd, supportsComputerUse, mcpHub, effectiveDiffStrategy
${modesSection} ${modesSection}
${getRulesSection(cwd, supportsComputerUse, effectiveDiffStrategy, context)} ${getRulesSection(cwd, supportsComputerUse, effectiveDiffStrategy, experiments)}
${getSystemInfoSection(cwd, mode, customModeConfigs)} ${getSystemInfoSection(cwd, mode, customModeConfigs)}
@@ -102,6 +104,7 @@ export const SYSTEM_PROMPT = async (
globalCustomInstructions?: string, globalCustomInstructions?: string,
preferredLanguage?: string, preferredLanguage?: string,
diffEnabled?: boolean, diffEnabled?: boolean,
experiments?: Record<string, boolean>,
): Promise<string> => { ): Promise<string> => {
if (!context) { if (!context) {
throw new Error("Extension context is required for generating system prompt") throw new Error("Extension context is required for generating system prompt")
@@ -135,5 +138,6 @@ export const SYSTEM_PROMPT = async (
globalCustomInstructions, globalCustomInstructions,
preferredLanguage, preferredLanguage,
diffEnabled, diffEnabled,
experiments,
) )
} }

View File

@@ -3,6 +3,8 @@ import { getReadFileDescription } from "./read-file"
import { getWriteToFileDescription } from "./write-to-file" import { getWriteToFileDescription } from "./write-to-file"
import { getSearchFilesDescription } from "./search-files" import { getSearchFilesDescription } from "./search-files"
import { getListFilesDescription } from "./list-files" import { getListFilesDescription } from "./list-files"
import { getInsertCodeBlockDescription } from "./insert-code-block"
import { getSearchAndReplaceDescription } from "./search-and-replace"
import { getListCodeDefinitionNamesDescription } from "./list-code-definition-names" import { getListCodeDefinitionNamesDescription } from "./list-code-definition-names"
import { getBrowserActionDescription } from "./browser-action" import { getBrowserActionDescription } from "./browser-action"
import { getAskFollowupQuestionDescription } from "./ask-followup-question" import { getAskFollowupQuestionDescription } from "./ask-followup-question"
@@ -30,6 +32,8 @@ const toolDescriptionMap: Record<string, (args: ToolArgs) => string | undefined>
use_mcp_tool: (args) => getUseMcpToolDescription(args), use_mcp_tool: (args) => getUseMcpToolDescription(args),
access_mcp_resource: (args) => getAccessMcpResourceDescription(args), access_mcp_resource: (args) => getAccessMcpResourceDescription(args),
switch_mode: () => getSwitchModeDescription(), switch_mode: () => getSwitchModeDescription(),
insert_code_block: (args) => getInsertCodeBlockDescription(args),
search_and_replace: (args) => getSearchAndReplaceDescription(args),
apply_diff: (args) => apply_diff: (args) =>
args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : "", args.diffStrategy ? args.diffStrategy.getToolDescription({ cwd: args.cwd, toolOptions: args.toolOptions }) : "",
} }
@@ -42,6 +46,7 @@ export function getToolDescriptionsForMode(
browserViewportSize?: string, browserViewportSize?: string,
mcpHub?: McpHub, mcpHub?: McpHub,
customModes?: ModeConfig[], customModes?: ModeConfig[],
experiments?: Record<string, boolean>,
): string { ): string {
const config = getModeConfig(mode, customModes) const config = getModeConfig(mode, customModes)
const args: ToolArgs = { const args: ToolArgs = {
@@ -60,7 +65,7 @@ export function getToolDescriptionsForMode(
const toolGroup = TOOL_GROUPS[groupName] const toolGroup = TOOL_GROUPS[groupName]
if (toolGroup) { if (toolGroup) {
toolGroup.forEach((tool) => { toolGroup.forEach((tool) => {
if (isToolAllowedForMode(tool as ToolName, mode, customModes ?? [])) { if (isToolAllowedForMode(tool as ToolName, mode, customModes ?? [], experiments ?? {})) {
tools.add(tool) tools.add(tool)
} }
}) })
@@ -100,4 +105,6 @@ export {
getUseMcpToolDescription, getUseMcpToolDescription,
getAccessMcpResourceDescription, getAccessMcpResourceDescription,
getSwitchModeDescription, getSwitchModeDescription,
getInsertCodeBlockDescription,
getSearchAndReplaceDescription,
} }

View File

@@ -0,0 +1,35 @@
import { ToolArgs } from "./types"
export function getInsertCodeBlockDescription(args: ToolArgs): string {
return `## insert_code_block
Description: Inserts code blocks at specific line positions in a file. This is the primary tool for adding new code (functions/methods/classes, imports, attributes etc.) as it allows for precise insertions without overwriting existing content. The tool uses an efficient line-based insertion system that maintains file integrity and proper ordering of multiple insertions. Beware to use the proper indentation. This tool is the preferred way to add new code to files.
Parameters:
- path: (required) The path of the file to insert code into (relative to the current working directory ${args.cwd.toPosix()})
- operations: (required) A JSON array of insertion operations. Each operation is an object with:
* start_line: (required) The line number where the code block should be inserted. The content currently at that line will end up below the inserted code block.
* content: (required) The code block to insert at the specified position. IMPORTANT NOTE: If the content is a single line, it can be a string. If it's a multi-line content, it should be a string with newline characters (\n) for line breaks.
Usage:
<insert_code_block>
<path>File path here</path>
<operations>[
{
"start_line": 10,
"content": "Your code block here"
}
]</operations>
</insert_code_block>
Example: Insert a new function and its import statement
<insert_code_block>
<path>src/app.ts</path>
<operations>[
{
"start_line": 1,
"content": "import { sum } from './utils';"
},
{
"start_line": 10,
"content": "function calculateTotal(items: number[]): number {\n return items.reduce((sum, item) => sum + item, 0);\n}"
}
]</operations>
</insert_code_block>`
}

View File

@@ -0,0 +1,52 @@
import { ToolArgs } from "./types"
export function getSearchAndReplaceDescription(args: ToolArgs): string {
return `## search_and_replace
Description: Request to perform search and replace operations on a file. Each operation can specify a search pattern (string or regex) and replacement text, with optional line range restrictions and regex flags. Shows a diff preview before applying changes.
Parameters:
- path: (required) The path of the file to modify (relative to the current working directory ${args.cwd.toPosix()})
- operations: (required) A JSON array of search/replace operations. Each operation is an object with:
* search: (required) The text or pattern to search for
* replace: (required) The text to replace matches with. If multiple lines need to be replaced, use "\n" for newlines
* start_line: (optional) Starting line number for restricted replacement
* end_line: (optional) Ending line number for restricted replacement
* use_regex: (optional) Whether to treat search as a regex pattern
* ignore_case: (optional) Whether to ignore case when matching
* regex_flags: (optional) Additional regex flags when use_regex is true
Usage:
<search_and_replace>
<path>File path here</path>
<operations>[
{
"search": "text to find",
"replace": "replacement text",
"start_line": 1,
"end_line": 10
}
]</operations>
</search_and_replace>
Example: Replace "foo" with "bar" in lines 1-10 of example.ts
<search_and_replace>
<path>example.ts</path>
<operations>[
{
"search": "foo",
"replace": "bar",
"start_line": 1,
"end_line": 10
}
]</operations>
</search_and_replace>
Example: Replace all occurrences of "old" with "new" using regex
<search_and_replace>
<path>example.ts</path>
<operations>[
{
"search": "old\\w+",
"replace": "new$&",
"use_regex": true,
"ignore_case": true
}
]</operations>
</search_and_replace>`
}

View File

@@ -40,6 +40,7 @@ import { singleCompletionHandler } from "../../utils/single-completion-handler"
import { getCommitInfo, searchCommits, getWorkingState } from "../../utils/git" import { getCommitInfo, searchCommits, getWorkingState } from "../../utils/git"
import { ConfigManager } from "../config/ConfigManager" import { ConfigManager } from "../config/ConfigManager"
import { CustomModesManager } from "../config/CustomModesManager" import { CustomModesManager } from "../config/CustomModesManager"
import { EXPERIMENT_IDS, experiments as Experiments, experimentDefault, ExperimentId } from "../../shared/experiments"
import { CustomSupportPrompts, supportPrompt } from "../../shared/support-prompt" import { CustomSupportPrompts, supportPrompt } from "../../shared/support-prompt"
import { ACTION_NAMES } from "../CodeActionProvider" import { ACTION_NAMES } from "../CodeActionProvider"
@@ -80,6 +81,8 @@ type GlobalStateKey =
| "alwaysAllowWrite" | "alwaysAllowWrite"
| "alwaysAllowExecute" | "alwaysAllowExecute"
| "alwaysAllowBrowser" | "alwaysAllowBrowser"
| "alwaysAllowMcp"
| "alwaysAllowModeSwitch"
| "taskHistory" | "taskHistory"
| "openAiBaseUrl" | "openAiBaseUrl"
| "openAiModelId" | "openAiModelId"
@@ -100,7 +103,6 @@ type GlobalStateKey =
| "soundEnabled" | "soundEnabled"
| "soundVolume" | "soundVolume"
| "diffEnabled" | "diffEnabled"
| "alwaysAllowMcp"
| "browserViewportSize" | "browserViewportSize"
| "screenshotQuality" | "screenshotQuality"
| "fuzzyMatchThreshold" | "fuzzyMatchThreshold"
@@ -118,7 +120,7 @@ type GlobalStateKey =
| "customModePrompts" | "customModePrompts"
| "customSupportPrompts" | "customSupportPrompts"
| "enhancementApiConfigId" | "enhancementApiConfigId"
| "experimentalDiffStrategy" | "experiments" // Map of experiment IDs to their enabled state
| "autoApprovalEnabled" | "autoApprovalEnabled"
| "customModes" // Array of custom modes | "customModes" // Array of custom modes
| "unboundModelId" | "unboundModelId"
@@ -190,10 +192,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return findLast(Array.from(this.activeInstances), (instance) => instance.view?.visible === true) return findLast(Array.from(this.activeInstances), (instance) => instance.view?.visible === true)
} }
public static async handleCodeAction( public static async getInstance(): Promise<ClineProvider | undefined> {
promptType: keyof typeof ACTION_NAMES,
params: Record<string, string | any[]>,
): Promise<void> {
let visibleProvider = ClineProvider.getVisibleInstance() let visibleProvider = ClineProvider.getVisibleInstance()
// If no visible provider, try to show the sidebar view // If no visible provider, try to show the sidebar view
@@ -209,10 +208,46 @@ export class ClineProvider implements vscode.WebviewViewProvider {
return return
} }
return visibleProvider
}
public static async isActiveTask(): Promise<boolean> {
const visibleProvider = await ClineProvider.getInstance()
if (!visibleProvider) {
return false
}
if (visibleProvider.cline) {
return true
}
return false
}
public static async handleCodeAction(
command: string,
promptType: keyof typeof ACTION_NAMES,
params: Record<string, string | any[]>,
): Promise<void> {
const visibleProvider = await ClineProvider.getInstance()
if (!visibleProvider) {
return
}
const { customSupportPrompts } = await visibleProvider.getState() const { customSupportPrompts } = await visibleProvider.getState()
const prompt = supportPrompt.create(promptType, params, customSupportPrompts) const prompt = supportPrompt.create(promptType, params, customSupportPrompts)
if (visibleProvider.cline && command.endsWith("InCurrentTask")) {
await visibleProvider.postMessageToWebview({
type: "invoke",
invoke: "sendMessage",
text: prompt,
})
return
}
await visibleProvider.initClineWithTask(prompt) await visibleProvider.initClineWithTask(prompt)
} }
@@ -307,7 +342,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
fuzzyMatchThreshold, fuzzyMatchThreshold,
mode, mode,
customInstructions: globalInstructions, customInstructions: globalInstructions,
experimentalDiffStrategy, experiments,
} = await this.getState() } = await this.getState()
const modePrompt = customModePrompts?.[mode] as PromptComponent const modePrompt = customModePrompts?.[mode] as PromptComponent
@@ -322,7 +357,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
task, task,
images, images,
undefined, undefined,
experimentalDiffStrategy, experiments,
) )
} }
@@ -335,7 +370,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
fuzzyMatchThreshold, fuzzyMatchThreshold,
mode, mode,
customInstructions: globalInstructions, customInstructions: globalInstructions,
experimentalDiffStrategy, experiments,
} = await this.getState() } = await this.getState()
const modePrompt = customModePrompts?.[mode] as PromptComponent const modePrompt = customModePrompts?.[mode] as PromptComponent
@@ -350,7 +385,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
undefined, undefined,
undefined, undefined,
historyItem, historyItem,
experimentalDiffStrategy, experiments,
) )
} }
@@ -589,6 +624,10 @@ export class ClineProvider implements vscode.WebviewViewProvider {
await this.updateGlobalState("alwaysAllowMcp", message.bool) await this.updateGlobalState("alwaysAllowMcp", message.bool)
await this.postStateToWebview() await this.postStateToWebview()
break break
case "alwaysAllowModeSwitch":
await this.updateGlobalState("alwaysAllowModeSwitch", message.bool)
await this.postStateToWebview()
break
case "askResponse": case "askResponse":
this.cline?.handleWebviewAskResponse(message.askResponse!, message.text, message.images) this.cline?.handleWebviewAskResponse(message.askResponse!, message.text, message.images)
break break
@@ -1008,14 +1047,14 @@ export class ClineProvider implements vscode.WebviewViewProvider {
diffEnabled, diffEnabled,
mcpEnabled, mcpEnabled,
fuzzyMatchThreshold, fuzzyMatchThreshold,
experimentalDiffStrategy, experiments,
} = await this.getState() } = await this.getState()
// Create diffStrategy based on current model and settings // Create diffStrategy based on current model and settings
const diffStrategy = getDiffStrategy( const diffStrategy = getDiffStrategy(
apiConfiguration.apiModelId || apiConfiguration.openRouterModelId || "", apiConfiguration.apiModelId || apiConfiguration.openRouterModelId || "",
fuzzyMatchThreshold, fuzzyMatchThreshold,
experimentalDiffStrategy, Experiments.isEnabled(experiments, EXPERIMENT_IDS.DIFF_STRATEGY),
) )
const cwd = const cwd =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) || "" vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath).at(0) || ""
@@ -1036,6 +1075,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
customInstructions, customInstructions,
preferredLanguage, preferredLanguage,
diffEnabled, diffEnabled,
experiments,
) )
await this.postMessageToWebview({ await this.postMessageToWebview({
@@ -1171,14 +1211,28 @@ export class ClineProvider implements vscode.WebviewViewProvider {
vscode.window.showErrorMessage("Failed to get list api configuration") vscode.window.showErrorMessage("Failed to get list api configuration")
} }
break break
case "experimentalDiffStrategy": case "updateExperimental": {
await this.updateGlobalState("experimentalDiffStrategy", message.bool ?? false) if (!message.values) {
// Update diffStrategy in current Cline instance if it exists break
if (this.cline) {
await this.cline.updateDiffStrategy(message.bool ?? false)
} }
const updatedExperiments = {
...((await this.getGlobalState("experiments")) ?? experimentDefault),
...message.values,
} as Record<ExperimentId, boolean>
await this.updateGlobalState("experiments", updatedExperiments)
// Update diffStrategy in current Cline instance if it exists
if (message.values[EXPERIMENT_IDS.DIFF_STRATEGY] !== undefined && this.cline) {
await this.cline.updateDiffStrategy(
Experiments.isEnabled(updatedExperiments, EXPERIMENT_IDS.DIFF_STRATEGY),
)
}
await this.postStateToWebview() await this.postStateToWebview()
break break
}
case "updateMcpTimeout": case "updateMcpTimeout":
if (message.serverName && typeof message.timeout === "number") { if (message.serverName && typeof message.timeout === "number") {
try { try {
@@ -1821,6 +1875,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
alwaysAllowExecute, alwaysAllowExecute,
alwaysAllowBrowser, alwaysAllowBrowser,
alwaysAllowMcp, alwaysAllowMcp,
alwaysAllowModeSwitch,
soundEnabled, soundEnabled,
diffEnabled, diffEnabled,
taskHistory, taskHistory,
@@ -1840,8 +1895,8 @@ export class ClineProvider implements vscode.WebviewViewProvider {
customModePrompts, customModePrompts,
customSupportPrompts, customSupportPrompts,
enhancementApiConfigId, enhancementApiConfigId,
experimentalDiffStrategy,
autoApprovalEnabled, autoApprovalEnabled,
experiments,
} = await this.getState() } = await this.getState()
const allowedCommands = vscode.workspace.getConfiguration("roo-cline").get<string[]>("allowedCommands") || [] const allowedCommands = vscode.workspace.getConfiguration("roo-cline").get<string[]>("allowedCommands") || []
@@ -1855,6 +1910,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
alwaysAllowExecute: alwaysAllowExecute ?? false, alwaysAllowExecute: alwaysAllowExecute ?? false,
alwaysAllowBrowser: alwaysAllowBrowser ?? false, alwaysAllowBrowser: alwaysAllowBrowser ?? false,
alwaysAllowMcp: alwaysAllowMcp ?? false, alwaysAllowMcp: alwaysAllowMcp ?? false,
alwaysAllowModeSwitch: alwaysAllowModeSwitch ?? false,
uriScheme: vscode.env.uriScheme, uriScheme: vscode.env.uriScheme,
clineMessages: this.cline?.clineMessages || [], clineMessages: this.cline?.clineMessages || [],
taskHistory: (taskHistory || []) taskHistory: (taskHistory || [])
@@ -1880,9 +1936,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
customModePrompts: customModePrompts ?? {}, customModePrompts: customModePrompts ?? {},
customSupportPrompts: customSupportPrompts ?? {}, customSupportPrompts: customSupportPrompts ?? {},
enhancementApiConfigId, enhancementApiConfigId,
experimentalDiffStrategy: experimentalDiffStrategy ?? false,
autoApprovalEnabled: autoApprovalEnabled ?? false, autoApprovalEnabled: autoApprovalEnabled ?? false,
customModes: await this.customModesManager.getCustomModes(), customModes: await this.customModesManager.getCustomModes(),
experiments: experiments ?? experimentDefault,
} }
} }
@@ -1982,6 +2038,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
alwaysAllowExecute, alwaysAllowExecute,
alwaysAllowBrowser, alwaysAllowBrowser,
alwaysAllowMcp, alwaysAllowMcp,
alwaysAllowModeSwitch,
taskHistory, taskHistory,
allowedCommands, allowedCommands,
soundEnabled, soundEnabled,
@@ -2004,9 +2061,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
customModePrompts, customModePrompts,
customSupportPrompts, customSupportPrompts,
enhancementApiConfigId, enhancementApiConfigId,
experimentalDiffStrategy,
autoApprovalEnabled, autoApprovalEnabled,
customModes, customModes,
experiments,
unboundApiKey, unboundApiKey,
unboundModelId, unboundModelId,
] = await Promise.all([ ] = await Promise.all([
@@ -2053,6 +2110,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("alwaysAllowExecute") as Promise<boolean | undefined>, this.getGlobalState("alwaysAllowExecute") as Promise<boolean | undefined>,
this.getGlobalState("alwaysAllowBrowser") as Promise<boolean | undefined>, this.getGlobalState("alwaysAllowBrowser") as Promise<boolean | undefined>,
this.getGlobalState("alwaysAllowMcp") as Promise<boolean | undefined>, this.getGlobalState("alwaysAllowMcp") as Promise<boolean | undefined>,
this.getGlobalState("alwaysAllowModeSwitch") as Promise<boolean | undefined>,
this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>, this.getGlobalState("taskHistory") as Promise<HistoryItem[] | undefined>,
this.getGlobalState("allowedCommands") as Promise<string[] | undefined>, this.getGlobalState("allowedCommands") as Promise<string[] | undefined>,
this.getGlobalState("soundEnabled") as Promise<boolean | undefined>, this.getGlobalState("soundEnabled") as Promise<boolean | undefined>,
@@ -2075,9 +2133,9 @@ export class ClineProvider implements vscode.WebviewViewProvider {
this.getGlobalState("customModePrompts") as Promise<CustomModePrompts | undefined>, this.getGlobalState("customModePrompts") as Promise<CustomModePrompts | undefined>,
this.getGlobalState("customSupportPrompts") as Promise<CustomSupportPrompts | undefined>, this.getGlobalState("customSupportPrompts") as Promise<CustomSupportPrompts | undefined>,
this.getGlobalState("enhancementApiConfigId") as Promise<string | undefined>, this.getGlobalState("enhancementApiConfigId") as Promise<string | undefined>,
this.getGlobalState("experimentalDiffStrategy") as Promise<boolean | undefined>,
this.getGlobalState("autoApprovalEnabled") as Promise<boolean | undefined>, this.getGlobalState("autoApprovalEnabled") as Promise<boolean | undefined>,
this.customModesManager.getCustomModes(), this.customModesManager.getCustomModes(),
this.getGlobalState("experiments") as Promise<Record<ExperimentId, boolean> | undefined>,
this.getSecret("unboundApiKey") as Promise<string | undefined>, this.getSecret("unboundApiKey") as Promise<string | undefined>,
this.getGlobalState("unboundModelId") as Promise<string | undefined>, this.getGlobalState("unboundModelId") as Promise<string | undefined>,
]) ])
@@ -2145,6 +2203,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
alwaysAllowExecute: alwaysAllowExecute ?? false, alwaysAllowExecute: alwaysAllowExecute ?? false,
alwaysAllowBrowser: alwaysAllowBrowser ?? false, alwaysAllowBrowser: alwaysAllowBrowser ?? false,
alwaysAllowMcp: alwaysAllowMcp ?? false, alwaysAllowMcp: alwaysAllowMcp ?? false,
alwaysAllowModeSwitch: alwaysAllowModeSwitch ?? false,
taskHistory, taskHistory,
allowedCommands, allowedCommands,
soundEnabled: soundEnabled ?? false, soundEnabled: soundEnabled ?? false,
@@ -2194,7 +2253,7 @@ export class ClineProvider implements vscode.WebviewViewProvider {
customModePrompts: customModePrompts ?? {}, customModePrompts: customModePrompts ?? {},
customSupportPrompts: customSupportPrompts ?? {}, customSupportPrompts: customSupportPrompts ?? {},
enhancementApiConfigId, enhancementApiConfigId,
experimentalDiffStrategy: experimentalDiffStrategy ?? false, experiments: experiments ?? experimentDefault,
autoApprovalEnabled: autoApprovalEnabled ?? false, autoApprovalEnabled: autoApprovalEnabled ?? false,
customModes, customModes,
} }

View File

@@ -4,6 +4,7 @@ import { ExtensionMessage, ExtensionState } from "../../../shared/ExtensionMessa
import { setSoundEnabled } from "../../../utils/sound" import { setSoundEnabled } from "../../../utils/sound"
import { defaultModeSlug, modes } from "../../../shared/modes" import { defaultModeSlug, modes } from "../../../shared/modes"
import { addCustomInstructions } from "../../prompts/sections/custom-instructions" import { addCustomInstructions } from "../../prompts/sections/custom-instructions"
import { experimentDefault, experiments } from "../../../shared/experiments"
// Mock custom-instructions module // Mock custom-instructions module
const mockAddCustomInstructions = jest.fn() const mockAddCustomInstructions = jest.fn()
@@ -320,6 +321,7 @@ describe("ClineProvider", () => {
requestDelaySeconds: 5, requestDelaySeconds: 5,
mode: defaultModeSlug, mode: defaultModeSlug,
customModes: [], customModes: [],
experiments: experimentDefault,
} }
const message: ExtensionMessage = { const message: ExtensionMessage = {
@@ -617,6 +619,7 @@ describe("ClineProvider", () => {
mode: "code", mode: "code",
diffEnabled: true, diffEnabled: true,
fuzzyMatchThreshold: 1.0, fuzzyMatchThreshold: 1.0,
experiments: experimentDefault,
} as any) } as any)
// Reset Cline mock // Reset Cline mock
@@ -636,7 +639,7 @@ describe("ClineProvider", () => {
"Test task", "Test task",
undefined, undefined,
undefined, undefined,
undefined, experimentDefault,
) )
}) })
test("handles mode-specific custom instructions updates", async () => { test("handles mode-specific custom instructions updates", async () => {
@@ -887,6 +890,7 @@ describe("ClineProvider", () => {
}, },
mcpEnabled: true, mcpEnabled: true,
mode: "code" as const, mode: "code" as const,
experiments: experimentDefault,
} as any) } as any)
const handler1 = getMessageHandler() const handler1 = getMessageHandler()
@@ -918,6 +922,7 @@ describe("ClineProvider", () => {
}, },
mcpEnabled: false, mcpEnabled: false,
mode: "code" as const, mode: "code" as const,
experiments: experimentDefault,
} as any) } as any)
const handler2 = getMessageHandler() const handler2 = getMessageHandler()
@@ -985,6 +990,7 @@ describe("ClineProvider", () => {
experimentalDiffStrategy: true, experimentalDiffStrategy: true,
diffEnabled: true, diffEnabled: true,
fuzzyMatchThreshold: 0.8, fuzzyMatchThreshold: 0.8,
experiments: experimentDefault,
} as any) } as any)
// Mock SYSTEM_PROMPT to verify diffStrategy and diffEnabled are passed // Mock SYSTEM_PROMPT to verify diffStrategy and diffEnabled are passed
@@ -1012,6 +1018,7 @@ describe("ClineProvider", () => {
undefined, // effectiveInstructions undefined, // effectiveInstructions
undefined, // preferredLanguage undefined, // preferredLanguage
true, // diffEnabled true, // diffEnabled
experimentDefault,
) )
// Run the test again to verify it's consistent // Run the test again to verify it's consistent
@@ -1034,6 +1041,7 @@ describe("ClineProvider", () => {
experimentalDiffStrategy: true, experimentalDiffStrategy: true,
diffEnabled: false, diffEnabled: false,
fuzzyMatchThreshold: 0.8, fuzzyMatchThreshold: 0.8,
experiments: experimentDefault,
} as any) } as any)
// Mock SYSTEM_PROMPT to verify diffEnabled is passed as false // Mock SYSTEM_PROMPT to verify diffEnabled is passed as false
@@ -1061,6 +1069,7 @@ describe("ClineProvider", () => {
undefined, // effectiveInstructions undefined, // effectiveInstructions
undefined, // preferredLanguage undefined, // preferredLanguage
false, // diffEnabled false, // diffEnabled
experimentDefault,
) )
}) })
@@ -1077,6 +1086,7 @@ describe("ClineProvider", () => {
mode: "architect", mode: "architect",
mcpEnabled: false, mcpEnabled: false,
browserViewportSize: "900x600", browserViewportSize: "900x600",
experiments: experimentDefault,
} as any) } as any)
// Mock SYSTEM_PROMPT to call addCustomInstructions // Mock SYSTEM_PROMPT to call addCustomInstructions

View File

@@ -171,6 +171,7 @@ export function activate(context: vscode.ExtensionContext) {
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
command: string, command: string,
promptType: keyof typeof ACTION_NAMES, promptType: keyof typeof ACTION_NAMES,
inNewTask: boolean,
inputPrompt?: string, inputPrompt?: string,
inputPlaceholder?: string, inputPlaceholder?: string,
) => { ) => {
@@ -194,14 +195,29 @@ export function activate(context: vscode.ExtensionContext) {
...(userInput ? { userInput } : {}), ...(userInput ? { userInput } : {}),
} }
await ClineProvider.handleCodeAction(promptType, params) await ClineProvider.handleCodeAction(command, promptType, params)
}, },
), ),
) )
} }
// Helper function to register both versions of a code action
const registerCodeActionPair = (
context: vscode.ExtensionContext,
baseCommand: string,
promptType: keyof typeof ACTION_NAMES,
inputPrompt?: string,
inputPlaceholder?: string,
) => {
// Register new task version
registerCodeAction(context, baseCommand, promptType, true, inputPrompt, inputPlaceholder)
// Register current task version
registerCodeAction(context, `${baseCommand}InCurrentTask`, promptType, false, inputPrompt, inputPlaceholder)
}
// Register code action commands // Register code action commands
registerCodeAction( registerCodeActionPair(
context, context,
"roo-cline.explainCode", "roo-cline.explainCode",
"EXPLAIN", "EXPLAIN",
@@ -209,7 +225,7 @@ export function activate(context: vscode.ExtensionContext) {
"E.g. How does the error handling work?", "E.g. How does the error handling work?",
) )
registerCodeAction( registerCodeActionPair(
context, context,
"roo-cline.fixCode", "roo-cline.fixCode",
"FIX", "FIX",
@@ -217,7 +233,7 @@ export function activate(context: vscode.ExtensionContext) {
"E.g. Maintain backward compatibility", "E.g. Maintain backward compatibility",
) )
registerCodeAction( registerCodeActionPair(
context, context,
"roo-cline.improveCode", "roo-cline.improveCode",
"IMPROVE", "IMPROVE",

View File

@@ -88,7 +88,6 @@ export class DiffViewProvider {
if (!isFinal) { if (!isFinal) {
accumulatedLines.pop() // remove the last partial line only if it's not the final update accumulatedLines.pop() // remove the last partial line only if it's not the final update
} }
const diffLines = accumulatedLines.slice(this.streamedLines.length)
const diffEditor = this.activeDiffEditor const diffEditor = this.activeDiffEditor
const document = diffEditor?.document const document = diffEditor?.document
@@ -100,21 +99,19 @@ export class DiffViewProvider {
const beginningOfDocument = new vscode.Position(0, 0) const beginningOfDocument = new vscode.Position(0, 0)
diffEditor.selection = new vscode.Selection(beginningOfDocument, beginningOfDocument) diffEditor.selection = new vscode.Selection(beginningOfDocument, beginningOfDocument)
for (let i = 0; i < diffLines.length; i++) { const endLine = accumulatedLines.length
const currentLine = this.streamedLines.length + i
// Replace all content up to the current line with accumulated lines // Replace all content up to the current line with accumulated lines
// This is necessary (as compared to inserting one line at a time) to handle cases where html tags on previous lines are auto closed for example
const edit = new vscode.WorkspaceEdit() const edit = new vscode.WorkspaceEdit()
const rangeToReplace = new vscode.Range(0, 0, currentLine + 1, 0) const rangeToReplace = new vscode.Range(0, 0, endLine + 1, 0)
const contentToReplace = accumulatedLines.slice(0, currentLine + 1).join("\n") + "\n" const contentToReplace = accumulatedLines.slice(0, endLine + 1).join("\n") + "\n"
edit.replace(document.uri, rangeToReplace, contentToReplace) edit.replace(document.uri, rangeToReplace, contentToReplace)
await vscode.workspace.applyEdit(edit) await vscode.workspace.applyEdit(edit)
// Update decorations // Update decorations
this.activeLineController.setActiveLine(currentLine) this.activeLineController.setActiveLine(endLine)
this.fadedOverlayController.updateOverlayAfterLine(currentLine, document.lineCount) this.fadedOverlayController.updateOverlayAfterLine(endLine, document.lineCount)
// Scroll to the current line // Scroll to the current line
this.scrollEditorToLine(currentLine) this.scrollEditorToLine(endLine)
}
// Update the streamedLines with the new accumulated content // Update the streamedLines with the new accumulated content
this.streamedLines = accumulatedLines this.streamedLines = accumulatedLines
if (isFinal) { if (isFinal) {

View File

@@ -6,6 +6,7 @@ import { McpServer } from "./mcp"
import { GitCommit } from "../utils/git" import { GitCommit } from "../utils/git"
import { Mode, CustomModePrompts, ModeConfig } from "./modes" import { Mode, CustomModePrompts, ModeConfig } from "./modes"
import { CustomSupportPrompts } from "./support-prompt" import { CustomSupportPrompts } from "./support-prompt"
import { ExperimentId } from "./experiments"
export interface LanguageModelChatSelector { export interface LanguageModelChatSelector {
vendor?: string vendor?: string
@@ -91,6 +92,7 @@ export interface ExtensionState {
alwaysAllowBrowser?: boolean alwaysAllowBrowser?: boolean
alwaysAllowMcp?: boolean alwaysAllowMcp?: boolean
alwaysApproveResubmit?: boolean alwaysApproveResubmit?: boolean
alwaysAllowModeSwitch?: boolean
requestDelaySeconds: number requestDelaySeconds: number
uriScheme?: string uriScheme?: string
allowedCommands?: string[] allowedCommands?: string[]
@@ -107,7 +109,7 @@ export interface ExtensionState {
mode: Mode mode: Mode
modeApiConfigs?: Record<Mode, string> modeApiConfigs?: Record<Mode, string>
enhancementApiConfigId?: string enhancementApiConfigId?: string
experimentalDiffStrategy?: boolean experiments: Record<ExperimentId, boolean> // Map of experiment IDs to their enabled state
autoApprovalEnabled?: boolean autoApprovalEnabled?: boolean
customModes: ModeConfig[] customModes: ModeConfig[]
toolRequirements?: Record<string, boolean> // Map of tool names to their requirements (e.g. {"apply_diff": true} if diffEnabled) toolRequirements?: Record<string, boolean> // Map of tool names to their requirements (e.g. {"apply_diff": true} if diffEnabled)

View File

@@ -41,6 +41,7 @@ export interface WebviewMessage {
| "refreshOpenAiModels" | "refreshOpenAiModels"
| "alwaysAllowBrowser" | "alwaysAllowBrowser"
| "alwaysAllowMcp" | "alwaysAllowMcp"
| "alwaysAllowModeSwitch"
| "playSound" | "playSound"
| "soundEnabled" | "soundEnabled"
| "soundVolume" | "soundVolume"
@@ -74,7 +75,7 @@ export interface WebviewMessage {
| "getSystemPrompt" | "getSystemPrompt"
| "systemPrompt" | "systemPrompt"
| "enhancementApiConfigId" | "enhancementApiConfigId"
| "experimentalDiffStrategy" | "updateExperimental"
| "autoApprovalEnabled" | "autoApprovalEnabled"
| "updateCustomMode" | "updateCustomMode"
| "deleteCustomMode" | "deleteCustomMode"

View File

@@ -14,6 +14,12 @@ describe("isToolAllowedForMode", () => {
roleDefinition: "You are a CSS editor", roleDefinition: "You are a CSS editor",
groups: ["read", ["edit", { fileRegex: "\\.css$" }], "browser"], groups: ["read", ["edit", { fileRegex: "\\.css$" }], "browser"],
}, },
{
slug: "test-exp-mode",
name: "Test Exp Mode",
roleDefinition: "You are an experimental tester",
groups: ["read", "edit", "browser"],
},
] ]
it("allows always available tools", () => { it("allows always available tools", () => {
@@ -240,6 +246,87 @@ describe("isToolAllowedForMode", () => {
expect(isToolAllowedForMode("write_to_file", "markdown-editor", customModes, toolRequirements)).toBe(false) expect(isToolAllowedForMode("write_to_file", "markdown-editor", customModes, toolRequirements)).toBe(false)
}) })
describe("experimental tools", () => {
it("disables tools when experiment is disabled", () => {
const experiments = {
search_and_replace: false,
insert_code_block: false,
}
expect(
isToolAllowedForMode(
"search_and_replace",
"test-exp-mode",
customModes,
undefined,
undefined,
experiments,
),
).toBe(false)
expect(
isToolAllowedForMode(
"insert_code_block",
"test-exp-mode",
customModes,
undefined,
undefined,
experiments,
),
).toBe(false)
})
it("allows tools when experiment is enabled", () => {
const experiments = {
search_and_replace: true,
insert_code_block: true,
}
expect(
isToolAllowedForMode(
"search_and_replace",
"test-exp-mode",
customModes,
undefined,
undefined,
experiments,
),
).toBe(true)
expect(
isToolAllowedForMode(
"insert_code_block",
"test-exp-mode",
customModes,
undefined,
undefined,
experiments,
),
).toBe(true)
})
it("allows non-experimental tools when experiments are disabled", () => {
const experiments = {
search_and_replace: false,
insert_code_block: false,
}
expect(
isToolAllowedForMode("read_file", "markdown-editor", customModes, undefined, undefined, experiments),
).toBe(true)
expect(
isToolAllowedForMode(
"write_to_file",
"markdown-editor",
customModes,
undefined,
{ path: "test.md" },
experiments,
),
).toBe(true)
})
})
}) })
describe("FileRestrictionError", () => { describe("FileRestrictionError", () => {

69
src/shared/experiments.ts Normal file
View File

@@ -0,0 +1,69 @@
export const EXPERIMENT_IDS = {
DIFF_STRATEGY: "experimentalDiffStrategy",
SEARCH_AND_REPLACE: "search_and_replace",
INSERT_BLOCK: "insert_code_block",
} as const
export type ExperimentKey = keyof typeof EXPERIMENT_IDS
export type ExperimentId = valueof<typeof EXPERIMENT_IDS>
export interface ExperimentConfig {
name: string
description: string
enabled: boolean
}
type valueof<X> = X[keyof X]
export const experimentConfigsMap: Record<ExperimentKey, ExperimentConfig> = {
DIFF_STRATEGY: {
name: "Use experimental unified diff strategy",
description:
"Enable the experimental unified diff strategy. This strategy might reduce the number of retries caused by model errors but may cause unexpected behavior or incorrect edits. Only enable if you understand the risks and are willing to carefully review all changes.",
enabled: false,
},
SEARCH_AND_REPLACE: {
name: "Use experimental search and replace tool",
description:
"Enable the experimental search and replace tool, allowing Roo to replace multiple instances of a search term in one request.",
enabled: false,
},
INSERT_BLOCK: {
name: "Use experimental insert block tool",
description:
"Enable the experimental insert block tool, allowing Roo to insert multiple code blocks at once at specific line numbers without needing to create a diff.",
enabled: false,
},
}
export const experimentDefault = Object.fromEntries(
Object.entries(experimentConfigsMap).map(([_, config]) => [
EXPERIMENT_IDS[_ as keyof typeof EXPERIMENT_IDS] as ExperimentId,
config.enabled,
]),
) as Record<ExperimentId, boolean>
export const experiments = {
get: (id: ExperimentKey): ExperimentConfig | undefined => {
return experimentConfigsMap[id]
},
isEnabled: (experimentsConfig: Record<ExperimentId, boolean>, id: ExperimentId): boolean => {
return experimentsConfig[id] ?? experimentDefault[id]
},
} as const
// Expose experiment details for UI - pre-compute from map for better performance
export const experimentLabels = Object.fromEntries(
Object.entries(experimentConfigsMap).map(([_, config]) => [
EXPERIMENT_IDS[_ as keyof typeof EXPERIMENT_IDS] as ExperimentId,
config.name,
]),
) as Record<string, string>
export const experimentDescriptions = Object.fromEntries(
Object.entries(experimentConfigsMap).map(([_, config]) => [
EXPERIMENT_IDS[_ as keyof typeof EXPERIMENT_IDS] as ExperimentId,
config.description,
]),
) as Record<string, string>

View File

@@ -6,6 +6,7 @@ interface ApiMetrics {
totalCacheWrites?: number totalCacheWrites?: number
totalCacheReads?: number totalCacheReads?: number
totalCost: number totalCost: number
contextTokens: number // Total tokens in conversation (last message's tokensIn + tokensOut)
} }
/** /**
@@ -32,8 +33,22 @@ export function getApiMetrics(messages: ClineMessage[]): ApiMetrics {
totalCacheWrites: undefined, totalCacheWrites: undefined,
totalCacheReads: undefined, totalCacheReads: undefined,
totalCost: 0, totalCost: 0,
contextTokens: 0,
} }
// Find the last api_req_started message that has valid token information
const lastApiReq = [...messages].reverse().find((message) => {
if (message.type === "say" && message.say === "api_req_started" && message.text) {
try {
const parsedData = JSON.parse(message.text)
return typeof parsedData.tokensIn === "number" && typeof parsedData.tokensOut === "number"
} catch {
return false
}
}
return false
})
messages.forEach((message) => { messages.forEach((message) => {
if (message.type === "say" && message.say === "api_req_started" && message.text) { if (message.type === "say" && message.say === "api_req_started" && message.text) {
try { try {
@@ -55,6 +70,14 @@ export function getApiMetrics(messages: ClineMessage[]): ApiMetrics {
if (typeof cost === "number") { if (typeof cost === "number") {
result.totalCost += cost result.totalCost += cost
} }
// If this is the last api request, use its tokens for context size
if (message === lastApiReq) {
// Only update context tokens if both input and output tokens are non-zero
if (tokensIn > 0 && tokensOut > 0) {
result.contextTokens = tokensIn + tokensOut
}
}
} catch (error) { } catch (error) {
console.error("Error parsing JSON:", error) console.error("Error parsing JSON:", error)
} }

View File

@@ -160,12 +160,19 @@ export function isToolAllowedForMode(
customModes: ModeConfig[], customModes: ModeConfig[],
toolRequirements?: Record<string, boolean>, toolRequirements?: Record<string, boolean>,
toolParams?: Record<string, any>, // All tool parameters toolParams?: Record<string, any>, // All tool parameters
experiments?: Record<string, boolean>,
): boolean { ): boolean {
// Always allow these tools // Always allow these tools
if (ALWAYS_AVAILABLE_TOOLS.includes(tool as any)) { if (ALWAYS_AVAILABLE_TOOLS.includes(tool as any)) {
return true return true
} }
if (experiments && tool in experiments) {
if (!experiments[tool]) {
return false
}
}
// Check tool requirements if any exist // Check tool requirements if any exist
if (toolRequirements && tool in toolRequirements) { if (toolRequirements && tool in toolRequirements) {
if (!toolRequirements[tool]) { if (!toolRequirements[tool]) {
@@ -198,7 +205,7 @@ export function isToolAllowedForMode(
const filePath = toolParams?.path const filePath = toolParams?.path
if ( if (
filePath && filePath &&
(toolParams.diff || toolParams.content) && (toolParams.diff || toolParams.content || toolParams.operations) &&
!doesFileMatchRegex(filePath, options.fileRegex) !doesFileMatchRegex(filePath, options.fileRegex)
) { ) {
throw new FileRestrictionError(mode.name, options.fileRegex, options.description, filePath) throw new FileRestrictionError(mode.name, options.fileRegex, options.description, filePath)

View File

@@ -21,7 +21,7 @@ export const TOOL_DISPLAY_NAMES = {
// Define available tool groups // Define available tool groups
export const TOOL_GROUPS: Record<string, ToolGroupValues> = { export const TOOL_GROUPS: Record<string, ToolGroupValues> = {
read: ["read_file", "search_files", "list_files", "list_code_definition_names"], read: ["read_file", "search_files", "list_files", "list_code_definition_names"],
edit: ["write_to_file", "apply_diff"], edit: ["write_to_file", "apply_diff", "insert_code_block", "search_and_replace"],
browser: ["browser_action"], browser: ["browser_action"],
command: ["execute_command"], command: ["execute_command"],
mcp: ["use_mcp_tool", "access_mcp_resource"], mcp: ["use_mcp_tool", "access_mcp_resource"],

View File

@@ -28,6 +28,8 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => {
setAlwaysAllowBrowser, setAlwaysAllowBrowser,
alwaysAllowMcp, alwaysAllowMcp,
setAlwaysAllowMcp, setAlwaysAllowMcp,
alwaysAllowModeSwitch,
setAlwaysAllowModeSwitch,
alwaysApproveResubmit, alwaysApproveResubmit,
setAlwaysApproveResubmit, setAlwaysApproveResubmit,
autoApprovalEnabled, autoApprovalEnabled,
@@ -71,6 +73,13 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => {
enabled: alwaysAllowMcp ?? false, enabled: alwaysAllowMcp ?? false,
description: "Allows use of configured MCP servers which may modify filesystem or interact with APIs.", description: "Allows use of configured MCP servers which may modify filesystem or interact with APIs.",
}, },
{
id: "switchModes",
label: "Switch between modes",
shortName: "Modes",
enabled: alwaysAllowModeSwitch ?? false,
description: "Allows automatic switching between different AI modes without requiring approval.",
},
{ {
id: "retryRequests", id: "retryRequests",
label: "Retry failed requests", label: "Retry failed requests",
@@ -120,6 +129,12 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => {
vscode.postMessage({ type: "alwaysAllowMcp", bool: newValue }) vscode.postMessage({ type: "alwaysAllowMcp", bool: newValue })
}, [alwaysAllowMcp, setAlwaysAllowMcp]) }, [alwaysAllowMcp, setAlwaysAllowMcp])
const handleModeSwitchChange = useCallback(() => {
const newValue = !(alwaysAllowModeSwitch ?? false)
setAlwaysAllowModeSwitch(newValue)
vscode.postMessage({ type: "alwaysAllowModeSwitch", bool: newValue })
}, [alwaysAllowModeSwitch, setAlwaysAllowModeSwitch])
const handleRetryChange = useCallback(() => { const handleRetryChange = useCallback(() => {
const newValue = !(alwaysApproveResubmit ?? false) const newValue = !(alwaysApproveResubmit ?? false)
setAlwaysApproveResubmit(newValue) setAlwaysApproveResubmit(newValue)
@@ -133,6 +148,7 @@ const AutoApproveMenu = ({ style }: AutoApproveMenuProps) => {
executeCommands: handleExecuteChange, executeCommands: handleExecuteChange,
useBrowser: handleBrowserChange, useBrowser: handleBrowserChange,
useMcp: handleMcpChange, useMcp: handleMcpChange,
switchModes: handleModeSwitchChange,
retryRequests: handleRetryChange, retryRequests: handleRetryChange,
} }

View File

@@ -55,6 +55,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
mode, mode,
setMode, setMode,
autoApprovalEnabled, autoApprovalEnabled,
alwaysAllowModeSwitch,
} = useExtensionState() } = useExtensionState()
//const task = messages.length > 0 ? (messages[0].say === "task" ? messages[0] : undefined) : undefined) : undefined //const task = messages.length > 0 ? (messages[0].say === "task" ? messages[0] : undefined) : undefined) : undefined
@@ -565,7 +566,10 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
(alwaysAllowReadOnly && message.ask === "tool" && isReadOnlyToolAction(message)) || (alwaysAllowReadOnly && message.ask === "tool" && isReadOnlyToolAction(message)) ||
(alwaysAllowWrite && message.ask === "tool" && isWriteToolAction(message)) || (alwaysAllowWrite && message.ask === "tool" && isWriteToolAction(message)) ||
(alwaysAllowExecute && message.ask === "command" && isAllowedCommand(message)) || (alwaysAllowExecute && message.ask === "command" && isAllowedCommand(message)) ||
(alwaysAllowMcp && message.ask === "use_mcp_server" && isMcpToolAlwaysAllowed(message)) (alwaysAllowMcp && message.ask === "use_mcp_server" && isMcpToolAlwaysAllowed(message)) ||
(alwaysAllowModeSwitch &&
message.ask === "tool" &&
JSON.parse(message.text || "{}")?.tool === "switchMode")
) )
}, },
[ [
@@ -579,6 +583,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
isAllowedCommand, isAllowedCommand,
alwaysAllowMcp, alwaysAllowMcp,
isMcpToolAlwaysAllowed, isMcpToolAlwaysAllowed,
alwaysAllowModeSwitch,
], ],
) )
@@ -915,6 +920,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
cacheWrites={apiMetrics.totalCacheWrites} cacheWrites={apiMetrics.totalCacheWrites}
cacheReads={apiMetrics.totalCacheReads} cacheReads={apiMetrics.totalCacheReads}
totalCost={apiMetrics.totalCost} totalCost={apiMetrics.totalCost}
contextTokens={apiMetrics.contextTokens}
onClose={handleTaskCloseButtonClick} onClose={handleTaskCloseButtonClick}
/> />
) : ( ) : (

View File

@@ -16,6 +16,7 @@ interface TaskHeaderProps {
cacheWrites?: number cacheWrites?: number
cacheReads?: number cacheReads?: number
totalCost: number totalCost: number
contextTokens: number
onClose: () => void onClose: () => void
} }
@@ -27,6 +28,7 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
cacheWrites, cacheWrites,
cacheReads, cacheReads,
totalCost, totalCost,
contextTokens,
onClose, onClose,
}) => { }) => {
const { apiConfiguration } = useExtensionState() const { apiConfiguration } = useExtensionState()
@@ -272,6 +274,13 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
{!isCostAvailable && <ExportButton />} {!isCostAvailable && <ExportButton />}
</div> </div>
<div style={{ display: "flex", alignItems: "center", gap: "4px", flexWrap: "wrap" }}>
<span style={{ fontWeight: "bold" }}>Context:</span>
<span style={{ display: "flex", alignItems: "center", gap: "3px" }}>
{contextTokens ? formatLargeNumber(contextTokens) : '-'}
</span>
</div>
{shouldShowPromptCacheInfo && (cacheReads !== undefined || cacheWrites !== undefined) && ( {shouldShowPromptCacheInfo && (cacheReads !== undefined || cacheWrites !== undefined) && (
<div style={{ display: "flex", alignItems: "center", gap: "4px", flexWrap: "wrap" }}> <div style={{ display: "flex", alignItems: "center", gap: "4px", flexWrap: "wrap" }}>
<span style={{ fontWeight: "bold" }}>Cache:</span> <span style={{ fontWeight: "bold" }}>Cache:</span>

View File

@@ -313,4 +313,168 @@ describe("ChatView - Auto Approval Tests", () => {
}) })
}) })
}) })
it("auto-approves mode switch when enabled", async () => {
render(
<ExtensionStateContextProvider>
<ChatView
isHidden={false}
showAnnouncement={false}
hideAnnouncement={() => {}}
showHistoryView={() => {}}
/>
</ExtensionStateContextProvider>,
)
// First hydrate state with initial task
mockPostMessage({
alwaysAllowModeSwitch: true,
autoApprovalEnabled: true,
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Then send the mode switch ask message
mockPostMessage({
alwaysAllowModeSwitch: true,
autoApprovalEnabled: true,
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "ask",
ask: "tool",
ts: Date.now(),
text: JSON.stringify({ tool: "switchMode" }),
partial: false,
},
],
})
// Wait for the auto-approval message
await waitFor(() => {
expect(vscode.postMessage).toHaveBeenCalledWith({
type: "askResponse",
askResponse: "yesButtonClicked",
})
})
})
it("does not auto-approve mode switch when disabled", async () => {
render(
<ExtensionStateContextProvider>
<ChatView
isHidden={false}
showAnnouncement={false}
hideAnnouncement={() => {}}
showHistoryView={() => {}}
/>
</ExtensionStateContextProvider>,
)
// First hydrate state with initial task
mockPostMessage({
alwaysAllowModeSwitch: false,
autoApprovalEnabled: true,
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Then send the mode switch ask message
mockPostMessage({
alwaysAllowModeSwitch: false,
autoApprovalEnabled: true,
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "ask",
ask: "tool",
ts: Date.now(),
text: JSON.stringify({ tool: "switchMode" }),
partial: false,
},
],
})
// Verify no auto-approval message was sent
expect(vscode.postMessage).not.toHaveBeenCalledWith({
type: "askResponse",
askResponse: "yesButtonClicked",
})
})
it("does not auto-approve mode switch when auto-approval is disabled", async () => {
render(
<ExtensionStateContextProvider>
<ChatView
isHidden={false}
showAnnouncement={false}
hideAnnouncement={() => {}}
showHistoryView={() => {}}
/>
</ExtensionStateContextProvider>,
)
// First hydrate state with initial task
mockPostMessage({
alwaysAllowModeSwitch: true,
autoApprovalEnabled: false,
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
],
})
// Then send the mode switch ask message
mockPostMessage({
alwaysAllowModeSwitch: true,
autoApprovalEnabled: false,
clineMessages: [
{
type: "say",
say: "task",
ts: Date.now() - 2000,
text: "Initial task",
},
{
type: "ask",
ask: "tool",
ts: Date.now(),
text: JSON.stringify({ tool: "switchMode" }),
partial: false,
},
],
})
// Verify no auto-approval message was sent
expect(vscode.postMessage).not.toHaveBeenCalledWith({
type: "askResponse",
askResponse: "yesButtonClicked",
})
})
}) })

View File

@@ -120,7 +120,7 @@ const CodeBlock = memo(({ source, forceWrap = false }: CodeBlockProps) => {
if (!node.lang) { if (!node.lang) {
node.lang = "javascript" node.lang = "javascript"
} else if (node.lang.includes(".")) { } else if (node.lang.includes(".")) {
// if the langauge is a file, get the extension // if the language is a file, get the extension
node.lang = node.lang.split(".").slice(-1)[0] node.lang = node.lang.split(".").slice(-1)[0]
} }
}) })

View File

@@ -0,0 +1,36 @@
import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react"
interface ExperimentalFeatureProps {
name: string
description: string
enabled: boolean
onChange: (value: boolean) => void
}
const ExperimentalFeature = ({ name, description, enabled, onChange }: ExperimentalFeatureProps) => {
return (
<div
style={{
marginTop: 10,
paddingLeft: 10,
borderLeft: "2px solid var(--vscode-button-background)",
}}>
<div style={{ display: "flex", alignItems: "center", gap: "5px" }}>
<span style={{ color: "var(--vscode-errorForeground)" }}></span>
<VSCodeCheckbox checked={enabled} onChange={(e: any) => onChange(e.target.checked)}>
<span style={{ fontWeight: "500" }}>{name}</span>
</VSCodeCheckbox>
</div>
<p
style={{
fontSize: "12px",
marginBottom: 15,
color: "var(--vscode-descriptionForeground)",
}}>
{description}
</p>
</div>
)
}
export default ExperimentalFeature

View File

@@ -25,6 +25,7 @@ const OpenAiModelPicker: React.FC = () => {
} }
setApiConfiguration(apiConfig) setApiConfiguration(apiConfig)
onUpdateApiConfig(apiConfig) onUpdateApiConfig(apiConfig)
setSearchTerm(newModelId)
} }
useEffect(() => { useEffect(() => {

View File

@@ -4,6 +4,8 @@ import { useExtensionState } from "../../context/ExtensionStateContext"
import { validateApiConfiguration, validateModelId } from "../../utils/validate" import { validateApiConfiguration, validateModelId } from "../../utils/validate"
import { vscode } from "../../utils/vscode" import { vscode } from "../../utils/vscode"
import ApiOptions from "./ApiOptions" import ApiOptions from "./ApiOptions"
import ExperimentalFeature from "./ExperimentalFeature"
import { EXPERIMENT_IDS, experimentConfigsMap } from "../../../../src/shared/experiments"
import ApiConfigManager from "./ApiConfigManager" import ApiConfigManager from "./ApiConfigManager"
type SettingsViewProps = { type SettingsViewProps = {
@@ -51,8 +53,10 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
setRequestDelaySeconds, setRequestDelaySeconds,
currentApiConfigName, currentApiConfigName,
listApiConfigMeta, listApiConfigMeta,
experimentalDiffStrategy, experiments,
setExperimentalDiffStrategy, setExperimentEnabled,
alwaysAllowModeSwitch,
setAlwaysAllowModeSwitch,
} = useExtensionState() } = useExtensionState()
const [apiErrorMessage, setApiErrorMessage] = useState<string | undefined>(undefined) const [apiErrorMessage, setApiErrorMessage] = useState<string | undefined>(undefined)
const [modelIdErrorMessage, setModelIdErrorMessage] = useState<string | undefined>(undefined) const [modelIdErrorMessage, setModelIdErrorMessage] = useState<string | undefined>(undefined)
@@ -92,7 +96,13 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
text: currentApiConfigName, text: currentApiConfigName,
apiConfiguration, apiConfiguration,
}) })
vscode.postMessage({ type: "experimentalDiffStrategy", bool: experimentalDiffStrategy })
vscode.postMessage({
type: "updateExperimental",
values: experiments,
})
vscode.postMessage({ type: "alwaysAllowModeSwitch", bool: alwaysAllowModeSwitch })
onDone() onDone()
} }
} }
@@ -328,6 +338,17 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
</p> </p>
</div> </div>
<div style={{ marginBottom: 15 }}>
<VSCodeCheckbox
checked={alwaysAllowModeSwitch}
onChange={(e: any) => setAlwaysAllowModeSwitch(e.target.checked)}>
<span style={{ fontWeight: "500" }}>Always approve mode switching</span>
</VSCodeCheckbox>
<p style={{ fontSize: "12px", marginTop: "5px", color: "var(--vscode-descriptionForeground)" }}>
Automatically switch between different AI modes without requiring approval
</p>
</div>
<div style={{ marginBottom: 15 }}> <div style={{ marginBottom: 15 }}>
<VSCodeCheckbox <VSCodeCheckbox
checked={alwaysAllowExecute} checked={alwaysAllowExecute}
@@ -569,7 +590,7 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
setDiffEnabled(e.target.checked) setDiffEnabled(e.target.checked)
if (!e.target.checked) { if (!e.target.checked) {
// Reset experimental strategy when diffs are disabled // Reset experimental strategy when diffs are disabled
setExperimentalDiffStrategy(false) setExperimentEnabled(EXPERIMENT_IDS.DIFF_STRATEGY, false)
} }
}}> }}>
<span style={{ fontWeight: "500" }}>Enable editing through diffs</span> <span style={{ fontWeight: "500" }}>Enable editing through diffs</span>
@@ -585,35 +606,14 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
</p> </p>
{diffEnabled && ( {diffEnabled && (
<div <div style={{ marginTop: 10 }}>
style={{ <ExperimentalFeature
marginTop: 10, key={EXPERIMENT_IDS.DIFF_STRATEGY}
paddingLeft: 10, {...experimentConfigsMap.DIFF_STRATEGY}
borderLeft: "2px solid var(--vscode-button-background)", enabled={experiments[EXPERIMENT_IDS.DIFF_STRATEGY] ?? false}
}}> onChange={(enabled) => setExperimentEnabled(EXPERIMENT_IDS.DIFF_STRATEGY, enabled)}
<div style={{ display: "flex", alignItems: "center", gap: "5px" }}> />
<span style={{ color: "var(--vscode-errorForeground)" }}>⚠️</span> <div style={{ display: "flex", alignItems: "center", gap: "5px", marginTop: "15px" }}>
<VSCodeCheckbox
checked={experimentalDiffStrategy}
onChange={(e: any) => setExperimentalDiffStrategy(e.target.checked)}>
<span style={{ fontWeight: "500" }}>
Use experimental unified diff strategy
</span>
</VSCodeCheckbox>
</div>
<p
style={{
fontSize: "12px",
marginBottom: 15,
color: "var(--vscode-descriptionForeground)",
}}>
Enable the experimental unified diff strategy. This strategy might reduce the number
of retries caused by model errors but may cause unexpected behavior or incorrect
edits. Only enable if you understand the risks and are willing to carefully review
all changes.
</p>
<div style={{ display: "flex", alignItems: "center", gap: "5px" }}>
<span style={{ fontWeight: "500", minWidth: "100px" }}>Match precision</span> <span style={{ fontWeight: "500", minWidth: "100px" }}>Match precision</span>
<input <input
type="range" type="range"
@@ -646,6 +646,23 @@ const SettingsView = ({ onDone }: SettingsViewProps) => {
</p> </p>
</div> </div>
)} )}
{Object.entries(experimentConfigsMap)
.filter((config) => config[0] !== "DIFF_STRATEGY")
.map((config) => (
<ExperimentalFeature
key={config[0]}
{...config[1]}
enabled={
experiments[EXPERIMENT_IDS[config[0] as keyof typeof EXPERIMENT_IDS]] ?? false
}
onChange={(enabled) =>
setExperimentEnabled(
EXPERIMENT_IDS[config[0] as keyof typeof EXPERIMENT_IDS],
enabled,
)
}
/>
))}
</div> </div>
</div> </div>

View File

@@ -16,6 +16,7 @@ import { McpServer } from "../../../src/shared/mcp"
import { checkExistKey } from "../../../src/shared/checkExistApiConfig" import { checkExistKey } from "../../../src/shared/checkExistApiConfig"
import { Mode, CustomModePrompts, defaultModeSlug, defaultPrompts, ModeConfig } from "../../../src/shared/modes" import { Mode, CustomModePrompts, defaultModeSlug, defaultPrompts, ModeConfig } from "../../../src/shared/modes"
import { CustomSupportPrompts } from "../../../src/shared/support-prompt" import { CustomSupportPrompts } from "../../../src/shared/support-prompt"
import { experimentDefault, ExperimentId } from "../../../src/shared/experiments"
export interface ExtensionStateContextType extends ExtensionState { export interface ExtensionStateContextType extends ExtensionState {
didHydrateState: boolean didHydrateState: boolean
@@ -33,6 +34,7 @@ export interface ExtensionStateContextType extends ExtensionState {
setAlwaysAllowExecute: (value: boolean) => void setAlwaysAllowExecute: (value: boolean) => void
setAlwaysAllowBrowser: (value: boolean) => void setAlwaysAllowBrowser: (value: boolean) => void
setAlwaysAllowMcp: (value: boolean) => void setAlwaysAllowMcp: (value: boolean) => void
setAlwaysAllowModeSwitch: (value: boolean) => void
setShowAnnouncement: (value: boolean) => void setShowAnnouncement: (value: boolean) => void
setAllowedCommands: (value: string[]) => void setAllowedCommands: (value: string[]) => void
setSoundEnabled: (value: boolean) => void setSoundEnabled: (value: boolean) => void
@@ -62,9 +64,7 @@ export interface ExtensionStateContextType extends ExtensionState {
setCustomSupportPrompts: (value: CustomSupportPrompts) => void setCustomSupportPrompts: (value: CustomSupportPrompts) => void
enhancementApiConfigId?: string enhancementApiConfigId?: string
setEnhancementApiConfigId: (value: string) => void setEnhancementApiConfigId: (value: string) => void
experimentalDiffStrategy: boolean setExperimentEnabled: (id: ExperimentId, enabled: boolean) => void
setExperimentalDiffStrategy: (value: boolean) => void
autoApprovalEnabled?: boolean
setAutoApprovalEnabled: (value: boolean) => void setAutoApprovalEnabled: (value: boolean) => void
handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void handleInputChange: (field: keyof ApiConfiguration) => (event: any) => void
customModes: ModeConfig[] customModes: ModeConfig[]
@@ -97,8 +97,8 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
mode: defaultModeSlug, mode: defaultModeSlug,
customModePrompts: defaultPrompts, customModePrompts: defaultPrompts,
customSupportPrompts: {}, customSupportPrompts: {},
experiments: experimentDefault,
enhancementApiConfigId: "", enhancementApiConfigId: "",
experimentalDiffStrategy: false,
autoApprovalEnabled: false, autoApprovalEnabled: false,
customModes: [], customModes: [],
}) })
@@ -241,7 +241,8 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
fuzzyMatchThreshold: state.fuzzyMatchThreshold, fuzzyMatchThreshold: state.fuzzyMatchThreshold,
writeDelayMs: state.writeDelayMs, writeDelayMs: state.writeDelayMs,
screenshotQuality: state.screenshotQuality, screenshotQuality: state.screenshotQuality,
experimentalDiffStrategy: state.experimentalDiffStrategy ?? false, setExperimentEnabled: (id, enabled) =>
setState((prevState) => ({ ...prevState, experiments: { ...prevState.experiments, [id]: enabled } })),
setApiConfiguration: (value) => setApiConfiguration: (value) =>
setState((prevState) => ({ setState((prevState) => ({
...prevState, ...prevState,
@@ -253,6 +254,7 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
setAlwaysAllowExecute: (value) => setState((prevState) => ({ ...prevState, alwaysAllowExecute: value })), setAlwaysAllowExecute: (value) => setState((prevState) => ({ ...prevState, alwaysAllowExecute: value })),
setAlwaysAllowBrowser: (value) => setState((prevState) => ({ ...prevState, alwaysAllowBrowser: value })), setAlwaysAllowBrowser: (value) => setState((prevState) => ({ ...prevState, alwaysAllowBrowser: value })),
setAlwaysAllowMcp: (value) => setState((prevState) => ({ ...prevState, alwaysAllowMcp: value })), setAlwaysAllowMcp: (value) => setState((prevState) => ({ ...prevState, alwaysAllowMcp: value })),
setAlwaysAllowModeSwitch: (value) => setState((prevState) => ({ ...prevState, alwaysAllowModeSwitch: value })),
setShowAnnouncement: (value) => setState((prevState) => ({ ...prevState, shouldShowAnnouncement: value })), setShowAnnouncement: (value) => setState((prevState) => ({ ...prevState, shouldShowAnnouncement: value })),
setAllowedCommands: (value) => setState((prevState) => ({ ...prevState, allowedCommands: value })), setAllowedCommands: (value) => setState((prevState) => ({ ...prevState, allowedCommands: value })),
setSoundEnabled: (value) => setState((prevState) => ({ ...prevState, soundEnabled: value })), setSoundEnabled: (value) => setState((prevState) => ({ ...prevState, soundEnabled: value })),
@@ -277,8 +279,6 @@ export const ExtensionStateContextProvider: React.FC<{ children: React.ReactNode
setCustomSupportPrompts: (value) => setState((prevState) => ({ ...prevState, customSupportPrompts: value })), setCustomSupportPrompts: (value) => setState((prevState) => ({ ...prevState, customSupportPrompts: value })),
setEnhancementApiConfigId: (value) => setEnhancementApiConfigId: (value) =>
setState((prevState) => ({ ...prevState, enhancementApiConfigId: value })), setState((prevState) => ({ ...prevState, enhancementApiConfigId: value })),
setExperimentalDiffStrategy: (value) =>
setState((prevState) => ({ ...prevState, experimentalDiffStrategy: value })),
setAutoApprovalEnabled: (value) => setState((prevState) => ({ ...prevState, autoApprovalEnabled: value })), setAutoApprovalEnabled: (value) => setState((prevState) => ({ ...prevState, autoApprovalEnabled: value })),
handleInputChange, handleInputChange,
setCustomModes: (value) => setState((prevState) => ({ ...prevState, customModes: value })), setCustomModes: (value) => setState((prevState) => ({ ...prevState, customModes: value })),