From 971ac0fdebd5b9ce3e6c573525f9e10fffc440fb Mon Sep 17 00:00:00 2001 From: Ara Date: Wed, 27 Aug 2025 13:05:35 -0700 Subject: [PATCH] Refactor Tool Executor (#5667) * Refactor Tool Executor * Adding diff fix * Fixing ordering of diff stuff --- .changeset/healthy-waves-eat.md | 5 + src/core/task/ToolExecutor.ts | 2524 ++--------------- .../task/tools/ToolExecutorCoordinator.ts | 81 + src/core/task/tools/ToolValidator.ts | 42 + .../handlers/AccessMcpResourceHandler.ts | 145 + .../AskFollowupQuestionToolHandler.ts | 104 + .../handlers/AttemptCompletionHandler.ts | 179 ++ .../task/tools/handlers/BrowserToolHandler.ts | 221 ++ .../task/tools/handlers/CondenseHandler.ts | 92 + .../handlers/ExecuteCommandToolHandler.ts | 150 + .../ListCodeDefinitionNamesToolHandler.ts | 121 + .../tools/handlers/ListFilesToolHandler.ts | 128 + .../handlers/LoadMcpDocumentationHandler.ts | 41 + .../task/tools/handlers/NewTaskHandler.ts | 72 + .../tools/handlers/PlanModeRespondHandler.ts | 131 + .../tools/handlers/ReadFileToolHandler.ts | 146 + .../task/tools/handlers/ReportBugHandler.ts | 143 + .../tools/handlers/SearchFilesToolHandler.ts | 144 + .../tools/handlers/SummarizeTaskHandler.ts | 103 + .../task/tools/handlers/UseMcpToolHandler.ts | 193 ++ .../tools/handlers/WebFetchToolHandler.ts | 111 + .../tools/handlers/WriteToFileToolHandler.ts | 464 +++ src/core/task/tools/types/TaskConfig.ts | 147 + src/core/task/tools/types/UIHelpers.ts | 71 + src/core/task/tools/utils/ToolConstants.ts | 127 + src/core/task/tools/utils/ToolDisplayUtils.ts | 33 + src/core/task/tools/utils/ToolResultUtils.ts | 76 + src/core/task/tools/utils/index.ts | 3 + src/services/browser/BrowserSession.ts | 36 +- src/utils/path.ts | 1 - .../settings/common/ModelInfoView.tsx | 2 - .../settings/utils/providerUtils.ts | 8 +- 32 files changed, 3524 insertions(+), 2320 deletions(-) create mode 100644 .changeset/healthy-waves-eat.md create mode 100644 src/core/task/tools/ToolExecutorCoordinator.ts create mode 100644 src/core/task/tools/ToolValidator.ts create mode 100644 src/core/task/tools/handlers/AccessMcpResourceHandler.ts create mode 100644 src/core/task/tools/handlers/AskFollowupQuestionToolHandler.ts create mode 100644 src/core/task/tools/handlers/AttemptCompletionHandler.ts create mode 100644 src/core/task/tools/handlers/BrowserToolHandler.ts create mode 100644 src/core/task/tools/handlers/CondenseHandler.ts create mode 100644 src/core/task/tools/handlers/ExecuteCommandToolHandler.ts create mode 100644 src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts create mode 100644 src/core/task/tools/handlers/ListFilesToolHandler.ts create mode 100644 src/core/task/tools/handlers/LoadMcpDocumentationHandler.ts create mode 100644 src/core/task/tools/handlers/NewTaskHandler.ts create mode 100644 src/core/task/tools/handlers/PlanModeRespondHandler.ts create mode 100644 src/core/task/tools/handlers/ReadFileToolHandler.ts create mode 100644 src/core/task/tools/handlers/ReportBugHandler.ts create mode 100644 src/core/task/tools/handlers/SearchFilesToolHandler.ts create mode 100644 src/core/task/tools/handlers/SummarizeTaskHandler.ts create mode 100644 src/core/task/tools/handlers/UseMcpToolHandler.ts create mode 100644 src/core/task/tools/handlers/WebFetchToolHandler.ts create mode 100644 src/core/task/tools/handlers/WriteToFileToolHandler.ts create mode 100644 src/core/task/tools/types/TaskConfig.ts create mode 100644 src/core/task/tools/types/UIHelpers.ts create mode 100644 src/core/task/tools/utils/ToolConstants.ts create mode 100644 src/core/task/tools/utils/ToolDisplayUtils.ts create mode 100644 src/core/task/tools/utils/ToolResultUtils.ts create mode 100644 src/core/task/tools/utils/index.ts diff --git a/.changeset/healthy-waves-eat.md b/.changeset/healthy-waves-eat.md new file mode 100644 index 00000000..cab6c102 --- /dev/null +++ b/.changeset/healthy-waves-eat.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +REfactoring Tool Executor diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 93f71d29..fa436718 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -1,65 +1,53 @@ -import { setTimeout as setTimeoutPromise } from "node:timers/promises" -import Anthropic from "@anthropic-ai/sdk" import { ApiHandler } from "@core/api" import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker" import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" import { DiffViewProvider } from "@integrations/editor/DiffViewProvider" -import { extractFileContent } from "@integrations/misc/extract-file-content" -import { processFilesIntoText } from "@integrations/misc/extract-text" import { BrowserSession } from "@services/browser/BrowserSession" import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" import { McpHub } from "@services/mcp/McpHub" import { AutoApprovalSettings } from "@shared/AutoApprovalSettings" import { BrowserSettings } from "@shared/BrowserSettings" -import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences" -import { - BrowserAction, - BrowserActionResult, - browserActions, - ClineAsk, - ClineAskQuestion, - ClineAskUseMcpServer, - ClinePlanModeResponse, - ClineSay, - ClineSayBrowserAction, - ClineSayTool, - COMPLETION_RESULT_CHANGES_FLAG, -} from "@shared/ExtensionMessage" +import { ClineAsk, ClineSay } from "@shared/ExtensionMessage" import { FocusChainSettings } from "@shared/FocusChainSettings" import { Mode } from "@shared/storage/types" import { ClineAskResponse } from "@shared/WebviewMessage" -import { fileExistsAtPath } from "@utils/fs" -import { modelDoesntSupportWebp } from "@utils/model-utils" -import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string" -import os from "os" -import * as path from "path" -import { serializeError } from "serialize-error" import * as vscode from "vscode" -import { HostProvider } from "@/hosts/host-provider" -import { showSystemNotification } from "@/integrations/notifications" -import { listFiles } from "@/services/glob/list-files" -import { telemetryService } from "@/services/posthog/PostHogClientProvider" -import { regexSearchFiles } from "@/services/ripgrep" -import { parseSourceCodeForDefinitionsTopLevel } from "@/services/tree-sitter" -import { findLast, findLastIndex, parsePartialArrayString } from "@/shared/array" -import { createAndOpenGitHubIssue } from "@/utils/github-url-utils" -import { getReadablePath, isLocatedInWorkspace } from "@/utils/path" -import { ToolParamName, ToolUse, ToolUseName } from "../assistant-message" -import { constructNewFileContent } from "../assistant-message/diff" +import { ToolUse, ToolUseName } from "../assistant-message" import { ContextManager } from "../context/context-management/ContextManager" -import { continuationPrompt } from "../prompts/contextManagement" -import { loadMcpDocumentation } from "../prompts/loadMcpDocumentation" import { formatResponse } from "../prompts/responses" -import { ensureTaskDirectoryExists } from "../storage/disk" import { StateManager } from "../storage/StateManager" import { ToolResponse } from "." import { MessageStateHandler } from "./message-state" import { TaskState } from "./TaskState" import { AutoApprove } from "./tools/autoApprove" -import { showNotificationForApprovalIfAutoApprovalEnabled } from "./utils" +import { AccessMcpResourceHandler } from "./tools/handlers/AccessMcpResourceHandler" +import { AskFollowupQuestionToolHandler } from "./tools/handlers/AskFollowupQuestionToolHandler" +import { AttemptCompletionHandler } from "./tools/handlers/AttemptCompletionHandler" +import { BrowserToolHandler } from "./tools/handlers/BrowserToolHandler" +import { CondenseHandler } from "./tools/handlers/CondenseHandler" +import { ExecuteCommandToolHandler } from "./tools/handlers/ExecuteCommandToolHandler" +import { ListCodeDefinitionNamesToolHandler } from "./tools/handlers/ListCodeDefinitionNamesToolHandler" +import { ListFilesToolHandler } from "./tools/handlers/ListFilesToolHandler" +import { LoadMcpDocumentationHandler } from "./tools/handlers/LoadMcpDocumentationHandler" +import { NewTaskHandler } from "./tools/handlers/NewTaskHandler" +import { PlanModeRespondHandler } from "./tools/handlers/PlanModeRespondHandler" +import { ReadFileToolHandler } from "./tools/handlers/ReadFileToolHandler" +import { ReportBugHandler } from "./tools/handlers/ReportBugHandler" +import { SearchFilesToolHandler } from "./tools/handlers/SearchFilesToolHandler" +import { SummarizeTaskHandler } from "./tools/handlers/SummarizeTaskHandler" +import { UseMcpToolHandler } from "./tools/handlers/UseMcpToolHandler" +import { WebFetchToolHandler } from "./tools/handlers/WebFetchToolHandler" +import { WriteToFileToolHandler } from "./tools/handlers/WriteToFileToolHandler" +import { IPartialBlockHandler, SharedToolHandler, ToolExecutorCoordinator } from "./tools/ToolExecutorCoordinator" +import { ToolValidator } from "./tools/ToolValidator" +import { TaskConfig, validateTaskConfig } from "./tools/types/TaskConfig" +import { createUIHelpers } from "./tools/types/UIHelpers" +import { ToolDisplayUtils } from "./tools/utils/ToolDisplayUtils" +import { ToolResultUtils } from "./tools/utils/ToolResultUtils" export class ToolExecutor { private autoApprover: AutoApprove + private coordinator: ToolExecutorCoordinator // Auto-approval methods using the AutoApprove class private shouldAutoApproveTool(toolName: ToolUseName): boolean | [boolean, boolean] { @@ -105,7 +93,7 @@ export class ToolExecutor { images?: string[], files?: string[], partial?: boolean, - ) => Promise, + ) => Promise, private ask: ( type: ClineAsk, text?: string, @@ -116,7 +104,7 @@ export class ToolExecutor { images?: string[] files?: string[] }>, - private saveCheckpoint: (isAttemptCompletionMessage?: boolean) => Promise, + private saveCheckpoint: (isAttemptCompletionMessage?: boolean, completionMessageTs?: number) => Promise, private sayAndCreateMissingParamError: (toolName: ToolUseName, paramName: string, relPath?: string) => Promise, private removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise, private executeCommandTool: (command: string) => Promise<[boolean, any]>, @@ -124,6 +112,92 @@ export class ToolExecutor { private updateFCListFromToolResponse: (taskProgress: string | undefined) => Promise, ) { this.autoApprover = new AutoApprove(autoApprovalSettings) + + // Initialize the coordinator and register all tool handlers + this.coordinator = new ToolExecutorCoordinator() + this.registerToolHandlers() + } + + // Create a properly typed TaskConfig object for handlers + private asToolConfig(): TaskConfig { + const config: TaskConfig = { + taskId: this.taskId, + ulid: this.ulid, + context: this.context, + mode: this.mode, + strictPlanModeEnabled: this.strictPlanModeEnabled, + cwd: this.cwd, + taskState: this.taskState, + messageState: this.messageStateHandler, + api: this.api, + autoApprovalSettings: this.autoApprovalSettings, + autoApprover: this.autoApprover, + browserSettings: this.browserSettings, + focusChainSettings: this.focusChainSettings, + services: { + mcpHub: this.mcpHub, + browserSession: this.browserSession, + urlContentFetcher: this.urlContentFetcher, + diffViewProvider: this.diffViewProvider, + fileContextTracker: this.fileContextTracker, + clineIgnoreController: this.clineIgnoreController, + contextManager: this.contextManager, + stateManager: this.stateManager, + }, + callbacks: { + say: this.say, + ask: this.ask, + saveCheckpoint: this.saveCheckpoint, + postStateToWebview: async () => {}, + reinitExistingTaskFromId: async () => {}, + cancelTask: async () => {}, + updateTaskHistory: async (_: any) => [], + executeCommandTool: this.executeCommandTool, + doesLatestTaskCompletionHaveNewChanges: this.doesLatestTaskCompletionHaveNewChanges, + updateFCListFromToolResponse: this.updateFCListFromToolResponse, + sayAndCreateMissingParamError: this.sayAndCreateMissingParamError, + removeLastPartialMessageIfExistsWithType: this.removeLastPartialMessageIfExistsWithType, + shouldAutoApproveToolWithPath: this.shouldAutoApproveToolWithPath.bind(this), + }, + coordinator: this.coordinator, + } + + // Validate the config at runtime to catch any missing properties + validateTaskConfig(config) + return config + } + + /** + * Register all tool handlers with the coordinator + */ + private registerToolHandlers(): void { + const validator = new ToolValidator(this.clineIgnoreController) + + // Register all tool handlers + this.coordinator.register(new ListFilesToolHandler(validator)) + this.coordinator.register(new ReadFileToolHandler(validator)) + this.coordinator.register(new BrowserToolHandler()) + this.coordinator.register(new AskFollowupQuestionToolHandler()) + this.coordinator.register(new WebFetchToolHandler()) + + // Register WriteToFileToolHandler for all three file tools with proper typing + const writeHandler = new WriteToFileToolHandler(validator) + this.coordinator.register(writeHandler) // registers as "write_to_file" + this.coordinator.register(new SharedToolHandler("replace_in_file", writeHandler)) + this.coordinator.register(new SharedToolHandler("new_rule", writeHandler)) + + this.coordinator.register(new ListCodeDefinitionNamesToolHandler(validator)) + this.coordinator.register(new SearchFilesToolHandler(validator)) + this.coordinator.register(new ExecuteCommandToolHandler(validator)) + this.coordinator.register(new UseMcpToolHandler()) + this.coordinator.register(new AccessMcpResourceHandler()) + this.coordinator.register(new LoadMcpDocumentationHandler()) + this.coordinator.register(new PlanModeRespondHandler()) + this.coordinator.register(new NewTaskHandler()) + this.coordinator.register(new AttemptCompletionHandler()) + this.coordinator.register(new CondenseHandler()) + this.coordinator.register(new SummarizeTaskHandler()) + this.coordinator.register(new ReportBugHandler()) } /** @@ -133,14 +207,6 @@ export class ToolExecutor { this.autoApprover.updateSettings(settings) } - /** - * Defines the tools which should be restricted in plan mode - */ - private isPlanModeToolRestricted(toolName: ToolUseName): boolean { - const planModeRestrictedTools: ToolUseName[] = ["write_to_file", "replace_in_file"] - return planModeRestrictedTools.includes(toolName) - } - public updateMode(mode: Mode): void { this.mode = mode } @@ -149,2253 +215,151 @@ export class ToolExecutor { this.strictPlanModeEnabled = strictPlanModeEnabled } + /** + * Main entry point for tool execution - called by Task class + */ + public async executeTool(block: ToolUse): Promise { + await this.execute(block) + } + + /** + * Handles errors during tool execution + */ + private async handleError(action: string, error: Error, block: ToolUse): Promise { + const errorString = `Error ${action}: ${error.message}` + await this.say("error", errorString) + + // Create error response for the tool + const errorResponse = formatResponse.toolError(errorString) + this.pushToolResult(errorResponse, block) + } + private pushToolResult = (content: ToolResponse, block: ToolUse) => { - if (typeof content === "string") { - const resultText = content || "(tool did not return anything)" - - this.taskState.userMessageContent.push({ - type: "text", - text: `${this.toolDescription(block)} Result:`, - }) - this.taskState.userMessageContent.push({ - type: "text", - text: resultText, - }) - } else { - this.taskState.userMessageContent.push(...content) - } - // once a tool result has been collected, ignore all other tool uses since we should only ever present one tool result per message - this.taskState.didAlreadyUseTool = true - } - - private toolDescription = (block: ToolUse) => { - switch (block.name) { - case "execute_command": - return `[${block.name} for '${block.params.command}']` - case "read_file": - return `[${block.name} for '${block.params.path}']` - case "write_to_file": - return `[${block.name} for '${block.params.path}']` - case "replace_in_file": - return `[${block.name} for '${block.params.path}']` - case "search_files": - return `[${block.name} for '${block.params.regex}'${ - block.params.file_pattern ? ` in '${block.params.file_pattern}'` : "" - }]` - case "list_files": - return `[${block.name} for '${block.params.path}']` - case "list_code_definition_names": - return `[${block.name} for '${block.params.path}']` - case "browser_action": - return `[${block.name} for '${block.params.action}']` - case "use_mcp_tool": - return `[${block.name} for '${block.params.server_name}']` - case "access_mcp_resource": - return `[${block.name} for '${block.params.server_name}']` - case "ask_followup_question": - return `[${block.name} for '${block.params.question}']` - case "plan_mode_respond": - return `[${block.name}]` - case "load_mcp_documentation": - return `[${block.name}]` - case "attempt_completion": - return `[${block.name}]` - case "new_task": - return `[${block.name} for creating a new task]` - case "condense": - return `[${block.name}]` - case "summarize_task": - return `[${block.name}]` - case "report_bug": - return `[${block.name}]` - case "new_rule": - return `[${block.name} for '${block.params.path}']` - case "web_fetch": - return `[${block.name} for '${block.params.url}']` - } - } - - // The user can approve, reject, or provide feedback (rejection). However the user may also send a message along with an approval, in which case we add a separate user message with this feedback. - private pushAdditionalToolFeedback = (feedback?: string, images?: string[], fileContentString?: string) => { - if (!feedback && (!images || images.length === 0) && !fileContentString) { - return - } - const content = formatResponse.toolResult( - `The user provided the following feedback:\n\n${feedback}\n`, - images, - fileContentString, + // Use the ToolResultUtils to properly format and push the tool result + ToolResultUtils.pushToolResult( + content, + block, + this.taskState.userMessageContent, + (block: ToolUse) => ToolDisplayUtils.getToolDescription(block), + this.api, + () => { + this.taskState.didAlreadyUseTool = true + }, + this.coordinator, ) - if (typeof content === "string") { - this.taskState.userMessageContent.push({ - type: "text", - text: content, - }) - } else { - this.taskState.userMessageContent.push(...content) - } } - private askApproval = async (type: ClineAsk, block: ToolUse, partialMessage: string) => { - const { response, text, images, files } = await this.ask(type, partialMessage, false) - if (response !== "yesButtonClicked") { - // User pressed reject button or responded with a message, which we treat as a rejection - this.pushToolResult(formatResponse.toolDenied(), block) - if (text || (images && images.length > 0) || (files && files.length > 0)) { - let fileContentString = "" - if (files && files.length > 0) { - fileContentString = await processFilesIntoText(files) - } + /** + * Tools that are restricted in plan mode and can only be used in act mode + */ + private static readonly PLAN_MODE_RESTRICTED_TOOLS: ToolUseName[] = ["write_to_file", "replace_in_file", "new_rule"] - this.pushAdditionalToolFeedback(text, images, fileContentString) - await this.say("user_feedback", text, images, files) - await this.saveCheckpoint() - } - this.taskState.didRejectTool = true // Prevent further tool uses in this message - return false - } else { - // User hit the approve button, and may have provided feedback - if (text || (images && images.length > 0) || (files && files.length > 0)) { - let fileContentString = "" - if (files && files.length > 0) { - fileContentString = await processFilesIntoText(files) - } + /** + * Execute a tool through the coordinator if it's registered + */ + private async execute(block: ToolUse): Promise { + if (!this.coordinator.has(block.name)) { + return false // Tool not handled by coordinator + } - this.pushAdditionalToolFeedback(text, images, fileContentString) - await this.say("user_feedback", text, images, files) - await this.saveCheckpoint() + const config = this.asToolConfig() + + try { + // Check if user rejected a previous tool + if (this.taskState.didRejectTool) { + const reason = block.partial + ? "Tool was interrupted and not executed due to user rejecting a previous tool." + : "Skipping tool due to user rejecting a previous tool." + this.createToolRejectionMessage(block, reason) + return true } + + // Check if a tool has already been used in this message + if (this.taskState.didAlreadyUseTool) { + this.taskState.userMessageContent.push({ + type: "text", + text: formatResponse.toolAlreadyUsed(block.name), + }) + return true + } + + // Logic for plan-mode tool call restrictions + if (this.strictPlanModeEnabled && this.mode === "plan" && block.name && this.isPlanModeToolRestricted(block.name)) { + const errorMessage = `Tool '${block.name}' is not available in PLAN MODE. This tool is restricted to ACT MODE for file modifications. Only use tools available for PLAN MODE when in that mode.` + await this.say("error", errorMessage) + this.pushToolResult(formatResponse.toolError(errorMessage), block) + await this.saveCheckpoint() + return true + } + + // Close browser for non-browser tools + if (block.name !== "browser_action") { + await this.browserSession.closeBrowser() + } + + // Handle partial blocks + if (block.partial) { + await this.handlePartialBlock(block, config) + return true + } + + // Handle complete blocks + await this.handleCompleteBlock(block, config) + return true + } catch (error) { + await this.handleError(`executing ${block.name}`, error as Error, block) + await this.saveCheckpoint() return true } } - private handleError = async (action: string, error: Error, block: ToolUse) => { - if (this.taskState.abandoned) { - console.log("Ignoring error since task was abandoned (i.e. from task cancellation after resetting)") - return - } - const errorString = `Error ${action}: ${JSON.stringify(serializeError(error))}` - await this.say("error", `Error ${action}:\n${error.message ?? JSON.stringify(serializeError(error), null, 2)}`) - - this.pushToolResult(formatResponse.toolError(errorString), block) + /** + * Check if a tool is restricted in plan mode + */ + private isPlanModeToolRestricted(toolName: ToolUseName): boolean { + return ToolExecutor.PLAN_MODE_RESTRICTED_TOOLS.includes(toolName) } - // If block is partial, remove partial closing tag so its not presented to user - private removeClosingTag = (block: ToolUse, tag: ToolParamName, text?: string) => { - if (!block.partial) { - return text || "" - } - if (!text) { - return "" - } - // This regex dynamically constructs a pattern to match the closing tag: - // - Optionally matches whitespace before the tag - // - Matches '<' or ' `(?:${char})?`) - .join("")}$`, - "g", - ) - return text.replace(tagRegex, "") + /** + * Create a tool rejection message and add it to user message content + */ + private createToolRejectionMessage(block: ToolUse, reason: string): void { + this.taskState.userMessageContent.push({ + type: "text", + text: `${reason} ${ToolDisplayUtils.getToolDescription(block, this.coordinator)}`, + }) } - public async executeTool(block: ToolUse): Promise { - if (this.taskState.didRejectTool) { - // ignore any tool content after user has rejected tool once - if (!block.partial) { - this.taskState.userMessageContent.push({ - type: "text", - text: `Skipping tool ${this.toolDescription(block)} due to user rejecting a previous tool.`, - }) - } else { - // partial tool after user rejected a previous tool - this.taskState.userMessageContent.push({ - type: "text", - text: `Tool ${this.toolDescription(block)} was interrupted and not executed due to user rejecting a previous tool.`, - }) - } - return + /** + * Handle partial block streaming UI updates + */ + private async handlePartialBlock(block: ToolUse, config: TaskConfig): Promise { + // NOTE: We don't push tool results in partial blocks because this is only for UI streaming. + // The ToolExecutor will handle pushToolResult() when the complete block is processed. + // This maintains separation of concerns: partial = UI updates, complete = final state changes. + const handler = this.coordinator.getHandler(block.name) + + // Check if handler supports partial blocks with proper typing + if (handler && "handlePartialBlock" in handler) { + const uiHelpers = createUIHelpers(config) + const partialHandler = handler as IPartialBlockHandler + await partialHandler.handlePartialBlock(block, uiHelpers) + } + } + + /** + * Handle complete block execution + */ + private async handleCompleteBlock(block: ToolUse, config: any): Promise { + // All tools are now fully self-managed and implement IPartialBlockHandler + const result = await this.coordinator.execute(config, block) + this.pushToolResult(result, block) + + // Handle focus chain updates + if (!block.partial && this.focusChainSettings.enabled) { + await this.updateFCListFromToolResponse(block.params.task_progress) } - if (this.taskState.didAlreadyUseTool) { - // ignore any content after a tool has already been used - this.taskState.userMessageContent.push({ - type: "text", - text: formatResponse.toolAlreadyUsed(block.name), - }) - return - } - - // Logic for plan-model tool call restrictions - if (this.strictPlanModeEnabled && this.mode === "plan" && block.name && this.isPlanModeToolRestricted(block.name)) { - const errorMessage = `Tool '${block.name}' is not available in PLAN MODE. This tool is restricted to ACT MODE for file modifications. Only use tools available for PLAN MODE when in that mode.` - await this.say("error", errorMessage) - this.pushToolResult(formatResponse.toolError(errorMessage), block) - await this.saveCheckpoint() - return - } - - if (block.name !== "browser_action") { - await this.browserSession.closeBrowser() - } - - switch (block.name) { - case "new_rule": - case "write_to_file": - case "replace_in_file": { - const relPath: string | undefined = block.params.path - const content: string | undefined = block.params.content // for write_to_file - let diff: string | undefined = block.params.diff // for replace_in_file - if (!relPath || (!content && !diff)) { - // checking for content/diff ensures relPath is complete - // wait so we can determine if it's a new file or editing an existing file - break - } - - const accessAllowed = this.clineIgnoreController.validateAccess(relPath) - if (!accessAllowed) { - await this.say("clineignore_error", relPath) - this.pushToolResult(formatResponse.toolError(formatResponse.clineIgnoreError(relPath)), block) - await this.saveCheckpoint() - break - } - - // Check if file exists using cached map or fs.access - let fileExists: boolean - if (this.diffViewProvider.editType !== undefined) { - fileExists = this.diffViewProvider.editType === "modify" - } else { - const absolutePath = path.resolve(this.cwd, relPath) - fileExists = await fileExistsAtPath(absolutePath) - this.diffViewProvider.editType = fileExists ? "modify" : "create" - } - - try { - // Construct newContent from diff - let newContent: string - newContent = "" // default to original content if not editing - if (diff) { - if (!this.api.getModel().id.includes("claude")) { - // deepseek models tend to use unescaped html entities in diffs - diff = fixModelHtmlEscaping(diff) - diff = removeInvalidChars(diff) - } - - // open the editor if not done already. This is to fix diff error when model provides correct search-replace text but Cline throws error - // because file is not open. - if (!this.diffViewProvider.isEditing) { - await this.diffViewProvider.open(relPath) - } - - try { - newContent = await constructNewFileContent( - diff, - this.diffViewProvider.originalContent || "", - !block.partial, - ) - } catch (error) { - await this.say("diff_error", relPath) - - // Extract error type from error message if possible, or use a generic type - const errorType = - error instanceof Error && error.message.includes("does not match anything") - ? "search_not_found" - : "other_diff_error" - - // Add telemetry for diff edit failure - telemetryService.captureDiffEditFailure(this.ulid, this.api.getModel().id, errorType) - - this.pushToolResult( - formatResponse.toolError( - `${(error as Error)?.message}\n\n` + - formatResponse.diffError(relPath, this.diffViewProvider.originalContent), - ), - block, - ) - await this.diffViewProvider.revertChanges() - await this.diffViewProvider.reset() - await this.saveCheckpoint() - break - } - } else if (content) { - newContent = content - - // pre-processing newContent for cases where weaker models might add artifacts like markdown codeblock markers (deepseek/llama) or extra escape characters (gemini) - if (newContent.startsWith("```")) { - // this handles cases where it includes language specifiers like ```python ```js - newContent = newContent.split("\n").slice(1).join("\n").trim() - } - if (newContent.endsWith("```")) { - newContent = newContent.split("\n").slice(0, -1).join("\n").trim() - } - - if (!this.api.getModel().id.includes("claude")) { - // it seems not just llama models are doing this, but also gemini and potentially others - newContent = fixModelHtmlEscaping(newContent) - newContent = removeInvalidChars(newContent) - } - } else { - // can't happen, since we already checked for content/diff above. but need to do this for type error - break - } - - newContent = newContent.trimEnd() // remove any trailing newlines, since it's automatically inserted by the editor - - const sharedMessageProps: ClineSayTool = { - tool: fileExists ? "editedExistingFile" : "newFileCreated", - path: getReadablePath(this.cwd, this.removeClosingTag(block, "path", relPath)), - content: diff || content, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), - } - - if (block.partial) { - // update gui message - const partialMessage = JSON.stringify(sharedMessageProps) - - if (await this.shouldAutoApproveToolWithPath(block.name, relPath)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") // in case the user changes auto-approval settings mid stream - await this.say("tool", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "tool") - await this.ask("tool", partialMessage, block.partial).catch(() => {}) - } - // update editor - if (!this.diffViewProvider.isEditing) { - // open the editor and prepare to stream content in - await this.diffViewProvider.open(relPath) - } - // editor is open, stream content in - await this.diffViewProvider.update(newContent, false) - break - } else { - if (!relPath) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError(block.name, "path"), block) - await this.diffViewProvider.reset() - await this.saveCheckpoint() - break - } - if (block.name === "replace_in_file" && !diff) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("replace_in_file", "diff"), block) - await this.diffViewProvider.reset() - await this.saveCheckpoint() - break - } - if (block.name === "write_to_file" && !content) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("write_to_file", "content"), block) - await this.diffViewProvider.reset() - await this.saveCheckpoint() - break - } - if (block.name === "new_rule" && !content) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("new_rule", "content"), block) - await this.diffViewProvider.reset() - await this.saveCheckpoint() - break - } - - this.taskState.consecutiveMistakeCount = 0 - - // if isEditingFile false, that means we have the full contents of the file already. - // it's important to note how this function works, you can't make the assumption that the block.partial conditional will always be called since it may immediately get complete, non-partial data. So this part of the logic will always be called. - // in other words, you must always repeat the block.partial logic here - if (!this.diffViewProvider.isEditing) { - // show gui message before showing edit animation - const partialMessage = JSON.stringify(sharedMessageProps) - await this.ask("tool", partialMessage, true).catch(() => {}) // sending true for partial even though it's not a partial, this shows the edit row before the content is streamed into the editor - await this.diffViewProvider.open(relPath) - } - await this.diffViewProvider.update(newContent, true) - await setTimeoutPromise(300) // wait for diff view to update - await this.diffViewProvider.scrollToFirstDiff() - // showOmissionWarning(this.diffViewProvider.originalContent || "", newContent) - - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - content: diff || content, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), - // ? formatResponse.createPrettyPatch( - // relPath, - // this.diffViewProvider.originalContent, - // newContent, - // ) - // : undefined, - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, relPath)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) - - // we need an artificial delay to let the diagnostics catch up to the changes - await setTimeoutPromise(3_500) - } else { - // If auto-approval is enabled but this tool wasn't auto-approved, send notification - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to ${fileExists ? "edit" : "create"} ${path.basename(relPath)}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "tool") - - // Need a more customized tool response for file edits to highlight the fact that the file was not updated (particularly important for deepseek) - let didApprove = true - const { response, text, images, files: askFiles } = await this.ask("tool", completeMessage, false) - if (response !== "yesButtonClicked") { - // User either sent a message or pressed reject button - // TODO: add similar context for other tool denial responses, to emphasize ie that a command was not run - const fileDeniedNote = fileExists - ? "The file was not updated, and maintains its original contents." - : "The file was not created." - this.pushToolResult(`The user denied this operation. ${fileDeniedNote}`, block) - if (text || (images && images.length > 0) || (askFiles && askFiles.length > 0)) { - let fileContentString = "" - if (askFiles && askFiles.length > 0) { - fileContentString = await processFilesIntoText(askFiles) - } - - this.pushAdditionalToolFeedback(text, images, fileContentString) - await this.say("user_feedback", text, images, askFiles) - await this.saveCheckpoint() - } - this.taskState.didRejectTool = true - didApprove = false - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) - } else { - // User hit the approve button, and may have provided feedback - if (text || (images && images.length > 0) || (askFiles && askFiles.length > 0)) { - let fileContentString = "" - if (askFiles && askFiles.length > 0) { - fileContentString = await processFilesIntoText(askFiles) - } - - this.pushAdditionalToolFeedback(text, images, fileContentString) - await this.say("user_feedback", text, images, askFiles) - await this.saveCheckpoint() - } - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) - } - - if (!didApprove) { - await this.diffViewProvider.revertChanges() - await this.saveCheckpoint() - break - } - } - - // Mark the file as edited by Cline to prevent false "recently modified" warnings - this.fileContextTracker.markFileAsEditedByCline(relPath) - - const { newProblemsMessage, userEdits, autoFormattingEdits, finalContent } = - await this.diffViewProvider.saveChanges() - this.taskState.didEditFile = true // used to determine if we should wait for busy terminal to update before sending api request - - // Track file edit operation - await this.fileContextTracker.trackFileContext(relPath, "cline_edited") - - if (userEdits) { - // Track file edit operation - await this.fileContextTracker.trackFileContext(relPath, "user_edited") - - await this.say( - "user_feedback_diff", - JSON.stringify({ - tool: fileExists ? "editedExistingFile" : "newFileCreated", - path: getReadablePath(this.cwd, relPath), - diff: userEdits, - } satisfies ClineSayTool), - ) - this.pushToolResult( - formatResponse.fileEditWithUserChanges( - relPath, - userEdits, - autoFormattingEdits, - finalContent, - newProblemsMessage, - ), - block, - ) - } else { - this.pushToolResult( - formatResponse.fileEditWithoutUserChanges( - relPath, - autoFormattingEdits, - finalContent, - newProblemsMessage, - ), - block, - ) - } - - await this.diffViewProvider.reset() - - if (!block.partial && this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - await this.saveCheckpoint() - - break - } - } catch (error) { - await this.handleError("writing file", error, block) - await this.diffViewProvider.revertChanges() - await this.diffViewProvider.reset() - await this.saveCheckpoint() - break - } - } - case "read_file": { - const relPath: string | undefined = block.params.path - const sharedMessageProps: ClineSayTool = { - tool: "readFile", - path: getReadablePath(this.cwd, this.removeClosingTag(block, "path", relPath)), - } - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - ...sharedMessageProps, - content: undefined, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "tool") - await this.ask("tool", partialMessage, block.partial).catch(() => {}) - } - break - } else { - if (!relPath) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("read_file", "path"), block) - await this.saveCheckpoint() - break - } - - const accessAllowed = this.clineIgnoreController.validateAccess(relPath) - if (!accessAllowed) { - await this.say("clineignore_error", relPath) - this.pushToolResult(formatResponse.toolError(formatResponse.clineIgnoreError(relPath)), block) - await this.saveCheckpoint() - break - } - - this.taskState.consecutiveMistakeCount = 0 - const absolutePath = path.resolve(this.cwd, relPath) - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - content: absolutePath, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", completeMessage, undefined, undefined, false) // need to be sending partialValue bool, since undefined has its own purpose in that the message is treated neither as a partial or completion of a partial, but as a single complete message - this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to read ${path.basename(absolutePath)}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "tool") - const didApprove = await this.askApproval("tool", block, completeMessage) - if (!didApprove) { - await this.saveCheckpoint() - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) - break - } - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) - } - // now execute the tool like normal - const supportsImages = this.api.getModel().info.supportsImages ?? false - const result = await extractFileContent(absolutePath, supportsImages) - - // Track file read operation - await this.fileContextTracker.trackFileContext(relPath, "read_tool") - - this.pushToolResult(result.text, block) - - if (result.imageBlock) { - this.taskState.userMessageContent.push(result.imageBlock) - } - - if (!block.partial && this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("reading file", error, block) - await this.saveCheckpoint() - break - } - } - case "list_files": { - const relDirPath: string | undefined = block.params.path - const recursiveRaw: string | undefined = block.params.recursive - const recursive = recursiveRaw?.toLowerCase() === "true" - const sharedMessageProps: ClineSayTool = { - tool: !recursive ? "listFilesTopLevel" : "listFilesRecursive", - path: getReadablePath(this.cwd, this.removeClosingTag(block, "path", relDirPath)), - } - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - ...sharedMessageProps, - content: "", - operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "tool") - await this.ask("tool", partialMessage, block.partial).catch(() => {}) - } - break - } else { - if (!relDirPath) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("list_files", "path"), block) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - const absolutePath = path.resolve(this.cwd, relDirPath) - - const [files, didHitLimit] = await listFiles(absolutePath, recursive, 200) - - const result = formatResponse.formatFilesList( - absolutePath, - files, - didHitLimit, - this.clineIgnoreController, - ) - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - content: result, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to view directory ${path.basename(absolutePath)}/`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "tool") - const didApprove = await this.askApproval("tool", block, completeMessage) - if (!didApprove) { - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) - await this.saveCheckpoint() - break - } - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) - } - this.pushToolResult(result, block) - - if (!block.partial && this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("listing files", error, block) - await this.saveCheckpoint() - break - } - } - case "list_code_definition_names": { - const relDirPath: string | undefined = block.params.path - const sharedMessageProps: ClineSayTool = { - tool: "listCodeDefinitionNames", - path: getReadablePath(this.cwd, this.removeClosingTag(block, "path", relDirPath)), - } - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - ...sharedMessageProps, - content: "", - operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "tool") - await this.ask("tool", partialMessage, block.partial).catch(() => {}) - } - break - } else { - if (!relDirPath) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("list_code_definition_names", "path"), - block, - ) - await this.saveCheckpoint() - break - } - - this.taskState.consecutiveMistakeCount = 0 - - const absolutePath = path.resolve(this.cwd, relDirPath) - const result = await parseSourceCodeForDefinitionsTopLevel(absolutePath, this.clineIgnoreController) - - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - content: result, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to view source code definitions in ${path.basename(absolutePath)}/`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "tool") - const didApprove = await this.askApproval("tool", block, completeMessage) - if (!didApprove) { - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) - await this.saveCheckpoint() - break - } - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) - } - this.pushToolResult(result, block) - - if (!block.partial) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("parsing source code definitions", error, block) - await this.saveCheckpoint() - break - } - } - case "search_files": { - const relDirPath: string | undefined = block.params.path - const regex: string | undefined = block.params.regex - const filePattern: string | undefined = block.params.file_pattern - const sharedMessageProps: ClineSayTool = { - tool: "searchFiles", - path: getReadablePath(this.cwd, this.removeClosingTag(block, "path", relDirPath)), - regex: this.removeClosingTag(block, "regex", regex), - filePattern: this.removeClosingTag(block, "file_pattern", filePattern), - } - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - ...sharedMessageProps, - content: "", - operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "tool") - await this.ask("tool", partialMessage, block.partial).catch(() => {}) - } - break - } else { - if (!relDirPath) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("search_files", "path"), block) - await this.saveCheckpoint() - break - } - if (!regex) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("search_files", "regex"), block) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - const absolutePath = path.resolve(this.cwd, relDirPath) - const results = await regexSearchFiles( - this.cwd, - absolutePath, - regex, - filePattern, - this.clineIgnoreController, - ) - - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - content: results, - operationIsLocatedInWorkspace: await isLocatedInWorkspace(block.params.path), - } satisfies ClineSayTool) - if (await this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, true, true) - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to search files in ${path.basename(absolutePath)}/`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "tool") - const didApprove = await this.askApproval("tool", block, completeMessage) - if (!didApprove) { - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, false) - await this.saveCheckpoint() - break - } - telemetryService.captureToolUsage(this.ulid, block.name, this.api.getModel().id, false, true) - } - this.pushToolResult(results, block) - - if (!block.partial) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("searching files", error, block) - await this.saveCheckpoint() - break - } - } - case "browser_action": { - const action: BrowserAction | undefined = block.params.action as BrowserAction - const url: string | undefined = block.params.url - const coordinate: string | undefined = block.params.coordinate - const text: string | undefined = block.params.text - if (!action || !browserActions.includes(action)) { - // checking for action to ensure it is complete and valid - if (!block.partial) { - // if the block is complete and we don't have a valid action this is a mistake - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("browser_action", "action"), block) - await this.browserSession.closeBrowser() - await this.saveCheckpoint() - } - break - } - - try { - if (block.partial) { - if (action === "launch") { - if (this.shouldAutoApproveTool(block.name)) { - this.removeLastPartialMessageIfExistsWithType("ask", "browser_action_launch") - await this.say( - "browser_action_launch", - this.removeClosingTag(block, "url", url), - undefined, - undefined, - block.partial, - ) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "browser_action_launch") - await this.ask( - "browser_action_launch", - this.removeClosingTag(block, "url", url), - block.partial, - ).catch(() => {}) - } - } else { - await this.say( - "browser_action", - JSON.stringify({ - action: action as BrowserAction, - coordinate: this.removeClosingTag(block, "coordinate", coordinate), - text: this.removeClosingTag(block, "text", text), - } satisfies ClineSayBrowserAction), - undefined, - undefined, - block.partial, - ) - } - break - } else { - let browserActionResult: BrowserActionResult - if (action === "launch") { - if (!url) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("browser_action", "url"), block) - await this.browserSession.closeBrowser() - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - if (this.shouldAutoApproveTool(block.name)) { - this.removeLastPartialMessageIfExistsWithType("ask", "browser_action_launch") - await this.say("browser_action_launch", url, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to use a browser and launch ${url}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "browser_action_launch") - const didApprove = await this.askApproval("browser_action_launch", block, url) - if (!didApprove) { - await this.saveCheckpoint() - break - } - } - - // NOTE: it's okay that we call this message since the partial inspect_site is finished streaming. The only scenario we have to avoid is sending messages WHILE a partial message exists at the end of the messages array. For example the api_req_finished message would interfere with the partial message, so we needed to remove that. - // await this.say("inspect_site_result", "") // no result, starts the loading spinner waiting for result - await this.say("browser_action_result", "") // starts loading spinner - - // Re-make browserSession to make sure latest settings apply - if (this.context) { - await this.browserSession.dispose() - - const apiHandlerModel = this.api.getModel() - const useWebp = this.api ? !modelDoesntSupportWebp(apiHandlerModel) : true - this.browserSession = new BrowserSession(this.context, this.browserSettings, useWebp) - } else { - console.warn("no controller context available for browserSession") - } - await this.browserSession.launchBrowser() - browserActionResult = await this.browserSession.navigateToUrl(url) - } else { - if (action === "click") { - if (!coordinate) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("browser_action", "coordinate"), - block, - ) - await this.browserSession.closeBrowser() - await this.saveCheckpoint() - break // can't be within an inner switch - } - } - if (action === "type") { - if (!text) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("browser_action", "text"), block) - await this.browserSession.closeBrowser() - await this.saveCheckpoint() - break - } - } - this.taskState.consecutiveMistakeCount = 0 - await this.say( - "browser_action", - JSON.stringify({ - action: action as BrowserAction, - coordinate, - text, - } satisfies ClineSayBrowserAction), - undefined, - undefined, - false, - ) - switch (action) { - case "click": - browserActionResult = await this.browserSession.click(coordinate!) - break - case "type": - browserActionResult = await this.browserSession.type(text!) - break - case "scroll_down": - browserActionResult = await this.browserSession.scrollDown() - break - case "scroll_up": - browserActionResult = await this.browserSession.scrollUp() - break - case "close": - browserActionResult = await this.browserSession.closeBrowser() - break - } - } - - switch (action) { - case "launch": - case "click": - case "type": - case "scroll_down": - case "scroll_up": - await this.say("browser_action_result", JSON.stringify(browserActionResult)) - this.pushToolResult( - formatResponse.toolResult( - `The browser action has been executed. The console logs and screenshot have been captured for your analysis.\n\nConsole logs:\n${ - browserActionResult.logs || "(No new logs)" - }\n\n(REMEMBER: if you need to proceed to using non-\`browser_action\` tools or launch a new browser, you MUST first close this browser. For example, if after analyzing the logs and screenshot you need to edit a file, you must first close the browser before you can use the write_to_file tool.)`, - browserActionResult.screenshot ? [browserActionResult.screenshot] : [], - ), - block, - ) - - if (!block.partial) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - await this.saveCheckpoint() - break - case "close": - this.pushToolResult( - formatResponse.toolResult( - `The browser has been closed. You may now proceed to using other tools.`, - ), - block, - ) - await this.saveCheckpoint() - break - } - - break - } - } catch (error) { - await this.browserSession.closeBrowser() // if any error occurs, the browser session is terminated - await this.handleError("executing browser action", error, block) - await this.saveCheckpoint() - break - } - } - case "execute_command": { - let command: string | undefined = block.params.command - const requiresApprovalRaw: string | undefined = block.params.requires_approval - const requiresApprovalPerLLM = requiresApprovalRaw?.toLowerCase() === "true" - - try { - if (block.partial) { - if (this.shouldAutoApproveTool(block.name)) { - // since depending on an upcoming parameter, requiresApproval this may become an ask - we can't partially stream a say prematurely. So in this particular case we have to wait for the requiresApproval parameter to be completed before presenting it. - // await this.say( - // "command", - // removeClosingTag("command", command), - // undefined, - // block.partial, - // ).catch(() => {}) - } else { - // don't need to remove last partial since we couldn't have streamed a say - await this.ask("command", this.removeClosingTag(block, "command", command), block.partial).catch( - () => {}, - ) - } - break - } else { - if (!command) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("execute_command", "command"), block) - await this.saveCheckpoint() - break - } - if (!requiresApprovalRaw) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("execute_command", "requires_approval"), - block, - ) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - // gemini models tend to use unescaped html entities in commands - if (this.api.getModel().id.includes("gemini")) { - command = fixModelHtmlEscaping(command) - } - - const ignoredFileAttemptedToAccess = this.clineIgnoreController.validateCommand(command) - if (ignoredFileAttemptedToAccess) { - await this.say("clineignore_error", ignoredFileAttemptedToAccess) - this.pushToolResult( - formatResponse.toolError(formatResponse.clineIgnoreError(ignoredFileAttemptedToAccess)), - block, - ) - await this.saveCheckpoint() - break - } - - let didAutoApprove = false - - // If the model says this command is safe and auto approval for safe commands is true, execute the command - // If the model says the command is risky, but *BOTH* auto approve settings are true, execute the command - const autoApproveResult = this.shouldAutoApproveTool(block.name) - const [autoApproveSafe, autoApproveAll] = Array.isArray(autoApproveResult) - ? autoApproveResult - : [autoApproveResult, false] - - if ( - (!requiresApprovalPerLLM && autoApproveSafe) || - (requiresApprovalPerLLM && autoApproveSafe && autoApproveAll) - ) { - this.removeLastPartialMessageIfExistsWithType("ask", "command") - await this.say("command", command, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - didAutoApprove = true - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to execute a command: ${command}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - // this.removeLastPartialMessageIfExistsWithType("say", "command") - const didApprove = await this.askApproval( - "command", - block, - command + - `${this.shouldAutoApproveTool(block.name) && requiresApprovalPerLLM ? COMMAND_REQ_APP_STRING : ""}`, // ugly hack until we refactor combineCommandSequences - ) - if (!didApprove) { - await this.saveCheckpoint() - break - } - } - - let timeoutId: NodeJS.Timeout | undefined - if (didAutoApprove && this.autoApprovalSettings.enableNotifications) { - // if the command was auto-approved, and it's long running we need to notify the user after some time has passed without proceeding - timeoutId = setTimeout(() => { - showSystemNotification({ - subtitle: "Command is still running", - message: "An auto-approved command has been running for 30s, and may need your attention.", - }) - }, 30_000) - } - - const [userRejected, result] = await this.executeCommandTool(command) - if (timeoutId) { - clearTimeout(timeoutId) - } - if (userRejected) { - this.taskState.didRejectTool = true - } - - this.pushToolResult(result, block) - - await this.saveCheckpoint() - - break - } - } catch (error) { - await this.handleError("executing command", error, block) - await this.saveCheckpoint() - break - } - } - case "use_mcp_tool": { - const server_name: string | undefined = block.params.server_name - const tool_name: string | undefined = block.params.tool_name - const mcp_arguments: string | undefined = block.params.arguments - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - type: "use_mcp_tool", - serverName: this.removeClosingTag(block, "server_name", server_name), - toolName: this.removeClosingTag(block, "tool_name", tool_name), - arguments: this.removeClosingTag(block, "arguments", mcp_arguments), - } satisfies ClineAskUseMcpServer) - - if (this.shouldAutoApproveTool(block.name)) { - this.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") - await this.say("use_mcp_server", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") - await this.ask("use_mcp_server", partialMessage, block.partial).catch(() => {}) - } - - break - } else { - if (!server_name) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("use_mcp_tool", "server_name"), block) - await this.saveCheckpoint() - break - } - if (!tool_name) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("use_mcp_tool", "tool_name"), block) - await this.saveCheckpoint() - break - } - // arguments are optional, but if they are provided they must be valid JSON - // if (!mcp_arguments) { - // this.consecutiveMistakeCount++ - // pushToolResult(await this.sayAndCreateMissingParamError("use_mcp_tool", "arguments")) - // break - // } - let parsedArguments: Record | undefined - if (mcp_arguments) { - try { - parsedArguments = JSON.parse(mcp_arguments) - } catch (_error) { - this.taskState.consecutiveMistakeCount++ - await this.say( - "error", - `Cline tried to use ${tool_name} with an invalid JSON argument. Retrying...`, - ) - this.pushToolResult( - formatResponse.toolError(formatResponse.invalidMcpToolArgumentError(server_name, tool_name)), - block, - ) - await this.saveCheckpoint() - break - } - } - this.taskState.consecutiveMistakeCount = 0 - const completeMessage = JSON.stringify({ - type: "use_mcp_tool", - serverName: server_name, - toolName: tool_name, - arguments: mcp_arguments, - } satisfies ClineAskUseMcpServer) - - const isToolAutoApproved = this.mcpHub.connections - ?.find((conn) => conn.server.name === server_name) - ?.server.tools?.find((tool) => tool.name === tool_name)?.autoApprove - - if (this.shouldAutoApproveTool(block.name) && isToolAutoApproved) { - this.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") - await this.say("use_mcp_server", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to use ${tool_name} on ${server_name}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") - const didApprove = await this.askApproval("use_mcp_server", block, completeMessage) - if (!didApprove) { - await this.saveCheckpoint() - break - } - } - - // now execute the tool - await this.say("mcp_server_request_started") // same as browser_action_result - - // Check for any pending notifications before the tool call - const notificationsBefore = this.mcpHub.getPendingNotifications() - for (const notification of notificationsBefore) { - await this.say("mcp_notification", `[${notification.serverName}] ${notification.message}`) - } - - const toolResult = await this.mcpHub.callTool(server_name, tool_name, parsedArguments, this.ulid) - - // Check for any pending notifications after the tool call - const notificationsAfter = this.mcpHub.getPendingNotifications() - for (const notification of notificationsAfter) { - await this.say("mcp_notification", `[${notification.serverName}] ${notification.message}`) - } - - // TODO: add progress indicator - - const toolResultImages = - toolResult?.content - .filter((item) => item.type === "image") - .map((item) => `data:${item.mimeType};base64,${item.data}`) || [] - let toolResultText = - (toolResult?.isError ? "Error:\n" : "") + - toolResult?.content - .map((item) => { - if (item.type === "text") { - return item.text - } - if (item.type === "resource") { - const { blob, ...rest } = item.resource - return JSON.stringify(rest, null, 2) - } - return "" - }) - .filter(Boolean) - .join("\n\n") || "(No response)" - // webview extracts images from the text response to display in the UI - const toolResultToDisplay = toolResultText + toolResultImages?.map((image) => `\n\n${image}`).join("") - await this.say("mcp_server_response", toolResultToDisplay) - - // MCP's might return images to display to the user, but the model may not support them - const supportsImages = this.api.getModel().info.supportsImages ?? false - if (toolResultImages.length > 0 && !supportsImages) { - toolResultText += `\n\n[${toolResultImages.length} images were provided in the response, and while they are displayed to the user, you do not have the ability to view them.]` - } - - // only passes in images if model supports them - this.pushToolResult( - formatResponse.toolResult(toolResultText, supportsImages ? toolResultImages : undefined), - block, - ) - - await this.saveCheckpoint() - - break - } - } catch (error) { - await this.handleError("executing MCP tool", error, block) - await this.saveCheckpoint() - break - } - } - case "access_mcp_resource": { - const server_name: string | undefined = block.params.server_name - const uri: string | undefined = block.params.uri - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - type: "access_mcp_resource", - serverName: this.removeClosingTag(block, "server_name", server_name), - uri: this.removeClosingTag(block, "uri", uri), - } satisfies ClineAskUseMcpServer) - - if (this.shouldAutoApproveTool(block.name)) { - this.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") - await this.say("use_mcp_server", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") - await this.ask("use_mcp_server", partialMessage, block.partial).catch(() => {}) - } - - break - } else { - if (!server_name) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("access_mcp_resource", "server_name"), - block, - ) - await this.saveCheckpoint() - break - } - if (!uri) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("access_mcp_resource", "uri"), block) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - const completeMessage = JSON.stringify({ - type: "access_mcp_resource", - serverName: server_name, - uri, - } satisfies ClineAskUseMcpServer) - - if (this.shouldAutoApproveTool(block.name)) { - this.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") - await this.say("use_mcp_server", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to access ${uri} on ${server_name}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") - const didApprove = await this.askApproval("use_mcp_server", block, completeMessage) - if (!didApprove) { - await this.saveCheckpoint() - break - } - } - - // now execute the tool - await this.say("mcp_server_request_started") - const resourceResult = await this.mcpHub.readResource(server_name, uri) - const resourceResultPretty = - resourceResult?.contents - .map((item) => { - if (item.text) { - return item.text - } - return "" - }) - .filter(Boolean) - .join("\n\n") || "(Empty response)" - await this.say("mcp_server_response", resourceResultPretty) - this.pushToolResult(formatResponse.toolResult(resourceResultPretty), block) - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("accessing MCP resource", error, block) - await this.saveCheckpoint() - break - } - } - case "ask_followup_question": { - const question: string | undefined = block.params.question - const optionsRaw: string | undefined = block.params.options - const sharedMessage = { - question: this.removeClosingTag(block, "question", question), - options: parsePartialArrayString(this.removeClosingTag(block, "options", optionsRaw)), - } satisfies ClineAskQuestion - try { - if (block.partial) { - await this.ask("followup", JSON.stringify(sharedMessage), block.partial).catch(() => {}) - break - } else { - if (!question) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("ask_followup_question", "question"), - block, - ) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - showSystemNotification({ - subtitle: "Cline has a question...", - message: question.replace(/\n/g, " "), - }) - } - - // Store the number of options for telemetry - const options = parsePartialArrayString(optionsRaw || "[]") - - const { - text, - images, - files: followupFiles, - } = await this.ask("followup", JSON.stringify(sharedMessage), false) - - // Check if options contains the text response - if (optionsRaw && text && parsePartialArrayString(optionsRaw).includes(text)) { - telemetryService.captureOptionSelected(this.ulid, options.length, "act") - // Valid option selected, don't show user message in UI - // Update last followup message with selected option - const lastFollowupMessage = findLast( - this.messageStateHandler.getClineMessages(), - (m) => m.ask === "followup", - ) - if (lastFollowupMessage) { - lastFollowupMessage.text = JSON.stringify({ - ...sharedMessage, - selected: text, - } satisfies ClineAskQuestion) - await this.messageStateHandler.saveClineMessagesAndUpdateHistory() - } - } else { - // Option not selected, send user feedback - telemetryService.captureOptionsIgnored(this.ulid, options.length, "act") - await this.say("user_feedback", text ?? "", images, followupFiles) - } - - let fileContentString = "" - if (followupFiles && followupFiles.length > 0) { - fileContentString = await processFilesIntoText(followupFiles) - } - - this.pushToolResult( - formatResponse.toolResult(`\n${text}\n`, images, fileContentString), - block, - ) - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("asking question", error, block) - await this.saveCheckpoint() - break - } - } - case "new_task": { - const context: string | undefined = block.params.context - try { - if (block.partial) { - await this.ask("new_task", this.removeClosingTag(block, "context", context), block.partial).catch( - () => {}, - ) - break - } else { - if (!context) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("new_task", "context"), block) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - showSystemNotification({ - subtitle: "Cline wants to start a new task...", - message: `Cline is suggesting to start a new task with: ${context}`, - }) - } - - const { text, images, files: newTaskFiles } = await this.ask("new_task", context, false) - - // If the user provided a response, treat it as feedback - if (text || (images && images.length > 0) || (newTaskFiles && newTaskFiles.length > 0)) { - let fileContentString = "" - if (newTaskFiles && newTaskFiles.length > 0) { - fileContentString = await processFilesIntoText(newTaskFiles) - } - - await this.say("user_feedback", text ?? "", images, newTaskFiles) - this.pushToolResult( - formatResponse.toolResult( - `The user provided feedback instead of creating a new task:\n\n${text}\n`, - images, - fileContentString, - ), - block, - ) - } else { - // If no response, the user clicked the "Create New Task" button - this.pushToolResult( - formatResponse.toolResult(`The user has created a new task with the provided context.`), - block, - ) - } - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("creating new task", error, block) - await this.saveCheckpoint() - break - } - } - case "summarize_task": { - const context: string | undefined = block.params.context - try { - if (block.partial) { - // Show streaming summary generation in tool UI - const partialMessage = JSON.stringify({ - tool: "summarizeTask", - content: this.removeClosingTag(block, "context", context), - } satisfies ClineSayTool) - - await this.say("tool", partialMessage, undefined, undefined, block.partial) - break - } else { - if (!context) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("summarize_task", "context"), block) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - // Show completed summary in tool UI - const completeMessage = JSON.stringify({ - tool: "summarizeTask", - content: context, - } satisfies ClineSayTool) - - await this.say("tool", completeMessage, undefined, undefined, false) - - // Use the continuationPrompt to format the tool result - this.pushToolResult(formatResponse.toolResult(continuationPrompt(context)), block) - - const apiConversationHistory = this.messageStateHandler.getApiConversationHistory() - const keepStrategy = "none" - - // clear the context history at this point in time. note that this will not include the assistant message - // for summarizing, which we will need to delete later - this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange( - apiConversationHistory, - this.taskState.conversationHistoryDeletedRange, - keepStrategy, - ) - await this.messageStateHandler.saveClineMessagesAndUpdateHistory() - await this.contextManager.triggerApplyStandardContextTruncationNoticeChange( - Date.now(), - await ensureTaskDirectoryExists(this.context, this.taskId), - apiConversationHistory, - ) - } - await this.saveCheckpoint() - this.taskState.currentlySummarizing = true - - // Capture telemetry after main business logic is complete - const telemetryData = this.contextManager.getContextTelemetryData( - this.messageStateHandler.getClineMessages(), - this.api, - this.taskState.lastAutoCompactTriggerIndex, - ) - - if (telemetryData) { - telemetryService.captureSummarizeTask( - this.ulid, - this.api.getModel().id, - telemetryData.tokensUsed, - telemetryData.maxContextWindow, - ) - } - - if (!block.partial && this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - break - } catch (error) { - await this.handleError("summarizing context window", error, block) - await this.saveCheckpoint() - break - } - } - case "condense": { - const context: string | undefined = block.params.context - try { - if (block.partial) { - await this.ask("condense", this.removeClosingTag(block, "context", context), block.partial).catch( - () => {}, - ) - break - } else { - if (!context) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("condense", "context"), block) - await this.saveCheckpoint() - break - } - this.taskState.consecutiveMistakeCount = 0 - - if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - showSystemNotification({ - subtitle: "Cline wants to condense the conversation...", - message: `Cline is suggesting to condense your conversation with: ${context}`, - }) - } - - const { text, images, files: condenseFiles } = await this.ask("condense", context, false) - - // If the user provided a response, treat it as feedback - if (text || (images && images.length > 0) || (condenseFiles && condenseFiles.length > 0)) { - let fileContentString = "" - if (condenseFiles && condenseFiles.length > 0) { - fileContentString = await processFilesIntoText(condenseFiles) - } - - await this.say("user_feedback", text ?? "", images, condenseFiles) - this.pushToolResult( - formatResponse.toolResult( - `The user provided feedback on the condensed conversation summary:\n\n${text}\n`, - images, - fileContentString, - ), - block, - ) - } else { - // If no response, the user accepted the condensed version - this.pushToolResult(formatResponse.toolResult(formatResponse.condense()), block) - const apiConversationHistory = this.messageStateHandler.getApiConversationHistory() - const lastMessage = apiConversationHistory[apiConversationHistory.length - 1] - const summaryAlreadyAppended = lastMessage && lastMessage.role === "assistant" - const keepStrategy = summaryAlreadyAppended ? "lastTwo" : "none" - - // clear the context history at this point in time - this.taskState.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange( - apiConversationHistory, - this.taskState.conversationHistoryDeletedRange, - keepStrategy, - ) - await this.messageStateHandler.saveClineMessagesAndUpdateHistory() - await this.contextManager.triggerApplyStandardContextTruncationNoticeChange( - Date.now(), - await ensureTaskDirectoryExists(this.context, this.taskId), - apiConversationHistory, - ) - } - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("condensing context window", error, block) - await this.saveCheckpoint() - break - } - } - case "report_bug": { - const title = block.params.title - const what_happened = block.params.what_happened - const steps_to_reproduce = block.params.steps_to_reproduce - const api_request_output = block.params.api_request_output - const additional_context = block.params.additional_context - - try { - if (block.partial) { - await this.ask( - "report_bug", - JSON.stringify({ - title: this.removeClosingTag(block, "title", title), - what_happened: this.removeClosingTag(block, "what_happened", what_happened), - steps_to_reproduce: this.removeClosingTag(block, "steps_to_reproduce", steps_to_reproduce), - api_request_output: this.removeClosingTag(block, "api_request_output", api_request_output), - additional_context: this.removeClosingTag(block, "additional_context", additional_context), - }), - block.partial, - ).catch(() => {}) - break - } else { - if (!title) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "title"), block) - await this.saveCheckpoint() - break - } - if (!what_happened) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "what_happened"), block) - await this.saveCheckpoint() - break - } - if (!steps_to_reproduce) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("report_bug", "steps_to_reproduce"), - block, - ) - await this.saveCheckpoint() - break - } - if (!api_request_output) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("report_bug", "api_request_output"), - block, - ) - await this.saveCheckpoint() - break - } - if (!additional_context) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult( - await this.sayAndCreateMissingParamError("report_bug", "additional_context"), - block, - ) - await this.saveCheckpoint() - break - } - - this.taskState.consecutiveMistakeCount = 0 - - if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - showSystemNotification({ - subtitle: "Cline wants to create a github issue...", - message: `Cline is suggesting to create a github issue with the title: ${title}`, - }) - } - - // Derive system information values algorithmically - const operatingSystem = os.platform() + " " + os.release() - const clineVersion = this.context.extension.packageJSON.version || "Unknown" - const host = await HostProvider.env.getHostVersion({}) - const systemInfo = `${host.platform}: ${host.version}, Node.js: ${process.version}, Architecture: ${os.arch()}` - const currentMode = this.mode - const apiConfig = this.stateManager.getApiConfiguration() - const apiProvider = currentMode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider - const providerAndModel = `${apiProvider} / ${this.api.getModel().id}` - - // Ask user for confirmation - const bugReportData = JSON.stringify({ - title, - what_happened, - steps_to_reproduce, - api_request_output, - additional_context, - // Include derived values in the JSON for display purposes - provider_and_model: providerAndModel, - operating_system: operatingSystem, - system_info: systemInfo, - cline_version: clineVersion, - }) - - const { text, images, files: reportBugFiles } = await this.ask("report_bug", bugReportData, false) - - // If the user provided a response, treat it as feedback - if (text || (images && images.length > 0) || (reportBugFiles && reportBugFiles.length > 0)) { - let fileContentString = "" - if (reportBugFiles && reportBugFiles.length > 0) { - fileContentString = await processFilesIntoText(reportBugFiles) - } - - await this.say("user_feedback", text ?? "", images, reportBugFiles) - this.pushToolResult( - formatResponse.toolResult( - `The user did not submit the bug, and provided feedback on the Github issue generated instead:\n\n${text}\n`, - images, - fileContentString, - ), - block, - ) - } else { - // If no response, the user accepted the condensed version - this.pushToolResult( - formatResponse.toolResult(`The user accepted the creation of the Github issue.`), - block, - ) - - try { - // Create a Map of parameters for the GitHub issue - const params = new Map() - params.set("title", title) - params.set("operating-system", operatingSystem) - params.set("cline-version", clineVersion) - params.set("system-info", systemInfo) - params.set("additional-context", additional_context) - params.set("what-happened", what_happened) - params.set("steps", steps_to_reproduce) - params.set("provider-model", providerAndModel) - params.set("logs", api_request_output) - - // Use our utility function to create and open the GitHub issue URL - // This bypasses VS Code's URI handling issues with special characters - await createAndOpenGitHubIssue("cline", "cline", "bug_report.yml", params) - } catch (error) { - console.error(`An error occurred while attempting to report the bug: ${error}`) - } - } - await this.saveCheckpoint() - break - } - } catch (error) { - await this.handleError("reporting bug", error, block) - await this.saveCheckpoint() - break - } - } - case "web_fetch": { - const url: string | undefined = block.params.url - // TODO: Implement caching for web_fetch - const sharedMessageProps: ClineSayTool = { - tool: "webFetch", - path: this.removeClosingTag(block, "url", url), - content: `Fetching URL: ${this.removeClosingTag(block, "url", url)}`, - } - - try { - if (block.partial) { - const partialMessage = JSON.stringify({ - ...sharedMessageProps, - operationIsLocatedInWorkspace: false, // web_fetch is always external - } satisfies ClineSayTool) - - // WebFetch is a read-only operation, generally safe. - // Let's assume it follows similar auto-approval logic to read_file for now. - // We might need a dedicated auto-approval setting for it later. - if (this.shouldAutoApproveTool("web_fetch" as ToolUseName)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", partialMessage, undefined, undefined, block.partial) - } else { - this.removeLastPartialMessageIfExistsWithType("say", "tool") - await this.ask("tool", partialMessage, block.partial).catch(() => {}) - } - break - } else { - if (!url) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("web_fetch", "url"), block) - await this.saveCheckpoint() - break - } - - this.taskState.consecutiveMistakeCount = 0 - const completeMessage = JSON.stringify({ - ...sharedMessageProps, - operationIsLocatedInWorkspace: false, - } satisfies ClineSayTool) - - if (this.shouldAutoApproveTool("web_fetch" as ToolUseName)) { - this.removeLastPartialMessageIfExistsWithType("ask", "tool") - await this.say("tool", completeMessage, undefined, undefined, false) - this.taskState.consecutiveAutoApprovedRequestsCount++ - telemetryService.captureToolUsage( - this.ulid, - "web_fetch" as ToolUseName, - this.api.getModel().id, - true, - true, - ) - } else { - showNotificationForApprovalIfAutoApprovalEnabled( - `Cline wants to fetch content from ${url}`, - this.autoApprovalSettings.enabled, - this.autoApprovalSettings.enableNotifications, - ) - this.removeLastPartialMessageIfExistsWithType("say", "tool") - const didApprove = await this.askApproval("tool", block, completeMessage) - if (!didApprove) { - telemetryService.captureToolUsage( - this.ulid, - "web_fetch" as ToolUseName, - this.api.getModel().id, - false, - false, - ) - await this.saveCheckpoint() - break - } - telemetryService.captureToolUsage( - this.ulid, - "web_fetch" as ToolUseName, - this.api.getModel().id, - false, - true, - ) - } - - // Fetch Markdown contentcc - await this.urlContentFetcher.launchBrowser() - const markdownContent = await this.urlContentFetcher.urlToMarkdown(url) - await this.urlContentFetcher.closeBrowser() - - // TODO: Implement secondary AI call to process markdownContent with prompt - // For now, returning markdown directly. - // This will be a significant sub-task. - // Placeholder for processed summary: - const processedSummary = `Fetched Markdown for ${url}:\n\n${markdownContent}` - - this.pushToolResult(formatResponse.toolResult(processedSummary), block) - await this.saveCheckpoint() - break - } - } catch (error) { - await this.urlContentFetcher.closeBrowser() // Ensure browser is closed on error - await this.handleError("fetching web content", error, block) - await this.saveCheckpoint() - break - } - } - case "plan_mode_respond": { - const response: string | undefined = block.params.response - const optionsRaw: string | undefined = block.params.options - const needsMoreExploration: boolean = block.params.needs_more_exploration === "true" - const sharedMessage = { - response: this.removeClosingTag(block, "response", response), - options: parsePartialArrayString(this.removeClosingTag(block, "options", optionsRaw)), - } satisfies ClinePlanModeResponse - try { - if (block.partial) { - await this.ask("plan_mode_respond", JSON.stringify(sharedMessage), block.partial).catch(() => {}) - break - } else { - if (!response) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("plan_mode_respond", "response"), block) - // - break - } - this.taskState.consecutiveMistakeCount = 0 - - // if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - // showSystemNotification({ - // subtitle: "Cline has a response...", - // message: response.replace(/\n/g, " "), - // }) - // } - - // The plan_mode_respond tool tends to run into this issue where the model realizes mid-tool call that it should have called another tool before calling plan_mode_respond. And it ends the plan_mode_respond tool call with 'Proceeding to reading files...' which doesn't do anything because we restrict to 1 tool call per message. As an escape hatch for the model, we provide it the optionality to tack on a parameter at the end of its response `needs_more_exploration`, which will allow the loop to continue. - if (needsMoreExploration) { - this.pushToolResult( - formatResponse.toolResult( - `[You have indicated that you need more exploration. Proceed with calling tools to continue the planning process.]`, - ), - block, - ) - break - } - - // Store the number of options for telemetry - const options = parsePartialArrayString(optionsRaw || "[]") - - this.taskState.isAwaitingPlanResponse = true - let { - text, - images, - files: planResponseFiles, - } = await this.ask("plan_mode_respond", JSON.stringify(sharedMessage), false) - this.taskState.isAwaitingPlanResponse = false - - // webview invoke sendMessage will send this marker in order to put webview into the proper state (responding to an ask) and as a flag to extension that the user switched to ACT mode. - if (text === "PLAN_MODE_TOGGLE_RESPONSE") { - text = "" - } - - // Check if options contains the text response - if (optionsRaw && text && parsePartialArrayString(optionsRaw).includes(text)) { - telemetryService.captureOptionSelected(this.ulid, options.length, "plan") - // Valid option selected, don't show user message in UI - // Update last followup message with selected option - const lastPlanMessage = findLast( - this.messageStateHandler.getClineMessages(), - (m) => m.ask === "plan_mode_respond", - ) - if (lastPlanMessage) { - lastPlanMessage.text = JSON.stringify({ - ...sharedMessage, - selected: text, - } satisfies ClinePlanModeResponse) - await this.messageStateHandler.saveClineMessagesAndUpdateHistory() - } - } else { - // Option not selected, send user feedback - if (text || (images && images.length > 0) || (planResponseFiles && planResponseFiles.length > 0)) { - telemetryService.captureOptionsIgnored(this.ulid, options.length, "plan") - await this.say("user_feedback", text ?? "", images, planResponseFiles) - await this.saveCheckpoint() - } - } - - let fileContentString = "" - if (planResponseFiles && planResponseFiles.length > 0) { - fileContentString = await processFilesIntoText(planResponseFiles) - } - - if (this.taskState.didRespondToPlanAskBySwitchingMode) { - this.pushToolResult( - formatResponse.toolResult( - `[The user has switched to ACT MODE, so you may now proceed with the task.]` + - (text - ? `\n\nThe user also provided the following message when switching to ACT MODE:\n\n${text}\n` - : ""), - images, - fileContentString, - ), - block, - ) - // Reset the flag after using it to prevent it from persisting - this.taskState.didRespondToPlanAskBySwitchingMode = false - } else { - // if we didn't switch to ACT MODE, then we can just send the user_feedback message - this.pushToolResult( - formatResponse.toolResult(`\n${text}\n`, images, fileContentString), - block, - ) - } - - if (!block.partial && this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - - // - break - } - } catch (error) { - await this.handleError("responding to inquiry", error, block) - // - break - } - } - case "load_mcp_documentation": { - try { - if (block.partial) { - // shouldn't happen - break - } else { - await this.say("load_mcp_documentation", "", undefined, undefined, false) - this.pushToolResult(await loadMcpDocumentation(this.mcpHub), block) - break - } - } catch (error) { - await this.handleError("loading MCP documentation", error, block) - break - } - } - case "attempt_completion": { - const result: string | undefined = block.params.result - const command: string | undefined = block.params.command - - const addNewChangesFlagToLastCompletionResultMessage = async () => { - // Add newchanges flag if there are new changes to the workspace - - const hasNewChanges = await this.doesLatestTaskCompletionHaveNewChanges() - - const clineMessages = this.messageStateHandler.getClineMessages() - - const lastCompletionResultMessageIndex = findLastIndex(clineMessages, (m) => m.say === "completion_result") - const lastCompletionResultMessage = - lastCompletionResultMessageIndex !== -1 ? clineMessages[lastCompletionResultMessageIndex] : undefined - if ( - lastCompletionResultMessage && - lastCompletionResultMessageIndex !== -1 && - hasNewChanges && - !lastCompletionResultMessage.text?.endsWith(COMPLETION_RESULT_CHANGES_FLAG) - ) { - await this.messageStateHandler.updateClineMessage(lastCompletionResultMessageIndex, { - text: lastCompletionResultMessage.text + COMPLETION_RESULT_CHANGES_FLAG, - }) - } - } - - try { - const lastMessage = this.messageStateHandler.getClineMessages().at(-1) - if (block.partial) { - if (command) { - // the attempt_completion text is done, now we're getting command - // remove the previous partial attempt_completion ask, replace with say, post state to webview, then stream command - - // const secondLastMessage = this.clineMessages.at(-2) - // NOTE: we do not want to auto approve a command run as part of the attempt_completion tool - if (lastMessage && lastMessage.ask === "command") { - // we are not going to stream the attempt_completion's command anymore since we might also need to send out a task_progress message before waiting for the user to approve the command, so the tool call checks everything on the progress check list. - // update command - // await this.ask("command", this.removeClosingTag(block, "command", command), block.partial).catch( - // () => {}, - // ) - } else { - // Now that we don't stream a command, we shouldn't be completing the attempt_completion tool in the block.partial conditional, and instead do it when partial is false below - // - // last message is completion_result, we have command string, which means we have the result as well, so finish it (doesn't have to exist yet) - // await this.say( - // "completion_result", - // this.removeClosingTag(block, "result", result), - // undefined, - // undefined, - // false, - // ) - // await this.saveCheckpoint(true) - // await addNewChangesFlagToLastCompletionResultMessage() - // await this.ask("command", this.removeClosingTag(block, "command", command), block.partial).catch( - // () => {}, - // ) - } - } else { - // no command, still outputting partial result - await this.say( - "completion_result", - this.removeClosingTag(block, "result", result), - undefined, - undefined, - block.partial, - ) - } - break - } else { - if (!result) { - this.taskState.consecutiveMistakeCount++ - this.pushToolResult(await this.sayAndCreateMissingParamError("attempt_completion", "result"), block) - break - } - this.taskState.consecutiveMistakeCount = 0 - - if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - showSystemNotification({ - subtitle: "Task Completed", - message: result.replace(/\n/g, " "), - }) - } - - let commandResult: ToolResponse | undefined - if (command) { - if (lastMessage && lastMessage.ask !== "command") { - // haven't sent a command message yet so first send completion_result then command - await this.say("completion_result", result, undefined, undefined, false) - await this.saveCheckpoint(true) - await addNewChangesFlagToLastCompletionResultMessage() - telemetryService.captureTaskCompleted(this.ulid) - - if (this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - } else { - // we already sent a command message, meaning the complete completion message has also been sent - await this.saveCheckpoint(true) - - if (this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - } - - // complete command message - const didApprove = await this.askApproval("command", block, command) - if (!didApprove) { - await this.saveCheckpoint() - break - } - const [userRejected, execCommandResult] = await this.executeCommandTool(command!) - if (userRejected) { - this.taskState.didRejectTool = true - this.pushToolResult(execCommandResult, block) - await this.saveCheckpoint() - break - } - // user didn't reject, but the command may have output - commandResult = execCommandResult - } else { - await this.say("completion_result", result, undefined, undefined, false) - await this.saveCheckpoint(true) - await addNewChangesFlagToLastCompletionResultMessage() - telemetryService.captureTaskCompleted(this.ulid) - - if (this.focusChainSettings.enabled) { - await this.updateFCListFromToolResponse(block.params.task_progress) - } - } - - // we already sent completion_result says, an empty string asks relinquishes control over button and field - const { response, text, images, files: completionFiles } = await this.ask("completion_result", "", false) - if (response === "yesButtonClicked") { - this.pushToolResult("", block) // signals to recursive loop to stop (for now this never happens since yesButtonClicked will trigger a new task) - break - } - await this.say("user_feedback", text ?? "", images, completionFiles) - await this.saveCheckpoint() - - const toolResults: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = [] - if (commandResult) { - if (typeof commandResult === "string") { - toolResults.push({ - type: "text", - text: commandResult, - }) - } else if (Array.isArray(commandResult)) { - toolResults.push(...commandResult) - } - } - toolResults.push({ - type: "text", - text: `The user has provided feedback on the results. Consider their input to continue the task, and then attempt completion again.\n\n${text}\n`, - }) - toolResults.push(...formatResponse.imageBlocks(images)) - this.taskState.userMessageContent.push({ - type: "text", - text: `${this.toolDescription(block)} Result:`, - }) - this.taskState.userMessageContent.push(...toolResults) - - let fileContentString = "" - if (completionFiles && completionFiles.length > 0) { - fileContentString = await processFilesIntoText(completionFiles) - } - - if (fileContentString) { - this.taskState.userMessageContent.push({ - type: "text", - text: fileContentString, - }) - } - break - } - } catch (error) { - await this.handleError("attempting completion", error, block) - await this.saveCheckpoint() - break - } - } - } + await this.saveCheckpoint() } } diff --git a/src/core/task/tools/ToolExecutorCoordinator.ts b/src/core/task/tools/ToolExecutorCoordinator.ts new file mode 100644 index 00000000..a9c01ff7 --- /dev/null +++ b/src/core/task/tools/ToolExecutorCoordinator.ts @@ -0,0 +1,81 @@ +import type { ToolUse } from "@core/assistant-message" +import type { ToolResponse } from "../index" +import type { TaskConfig } from "./types/TaskConfig" +import type { StronglyTypedUIHelpers } from "./types/UIHelpers" + +export interface IToolHandler { + readonly name: string + execute(config: TaskConfig, block: ToolUse): Promise + getDescription(block: ToolUse): string +} + +export interface IPartialBlockHandler { + handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise +} + +export interface IFullyManagedTool extends IToolHandler, IPartialBlockHandler { + // Marker interface for tools that handle their own complete approval flow +} + +/** + * A wrapper class that allows a single tool handler to be registered under multiple names. + * This provides proper typing for tools that share the same implementation logic. + */ +export class SharedToolHandler implements IFullyManagedTool { + constructor( + public readonly name: string, + private baseHandler: IFullyManagedTool, + ) {} + + getDescription(block: ToolUse): string { + return this.baseHandler.getDescription(block) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + return this.baseHandler.execute(config, block) + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + return this.baseHandler.handlePartialBlock(block, uiHelpers) + } +} + +/** + * Coordinates tool execution by routing to registered handlers. + * Falls back to legacy switch for unregistered tools. + */ +export class ToolExecutorCoordinator { + private handlers = new Map() + + /** + * Register a tool handler + */ + register(handler: IToolHandler): void { + this.handlers.set(handler.name, handler) + } + + /** + * Check if a handler is registered for the given tool + */ + has(toolName: string): boolean { + return this.handlers.has(toolName) + } + + /** + * Get a handler for the given tool name + */ + getHandler(toolName: string): IToolHandler | undefined { + return this.handlers.get(toolName) + } + + /** + * Execute a tool through its registered handler + */ + async execute(config: TaskConfig, block: ToolUse): Promise { + const handler = this.handlers.get(block.name) + if (!handler) { + throw new Error(`No handler registered for tool: ${block.name}`) + } + return handler.execute(config, block) + } +} diff --git a/src/core/task/tools/ToolValidator.ts b/src/core/task/tools/ToolValidator.ts new file mode 100644 index 00000000..0aa3f2b9 --- /dev/null +++ b/src/core/task/tools/ToolValidator.ts @@ -0,0 +1,42 @@ +import type { ToolParamName, ToolUse } from "@core/assistant-message" +import type { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" + +export type ValidationResult = { ok: true } | { ok: false; error: string } + +/** + * Lightweight validator used by new tool handlers. + * The legacy ToolExecutor switch remains unchanged and does not depend on this. + */ +export class ToolValidator { + constructor(private readonly clineIgnoreController: ClineIgnoreController) {} + + /** + * Verifies required parameters exist on the tool block. + * Returns a message suitable for displaying in an error. + */ + assertRequiredParams(block: ToolUse, ...params: ToolParamName[]): ValidationResult { + for (const p of params) { + // params are stored under block.params using their tag name + const val = (block as any)?.params?.[p] + if (val === undefined || val === null || String(val).trim() === "") { + return { ok: false, error: `Missing required parameter '${p}' for tool '${block.name}'.` } + } + } + return { ok: true } + } + + /** + * Verifies access is allowed to a given path via .clineignore rules. + * Callers should pass a repo-relative (workspace-relative) path. + */ + checkClineIgnorePath(relPath: string): ValidationResult { + const accessAllowed = this.clineIgnoreController.validateAccess(relPath) + if (!accessAllowed) { + return { + ok: false, + error: `Access to path '${relPath}' is blocked by .clineignore settings.`, + } + } + return { ok: true } + } +} diff --git a/src/core/task/tools/handlers/AccessMcpResourceHandler.ts b/src/core/task/tools/handlers/AccessMcpResourceHandler.ts new file mode 100644 index 00000000..649586a1 --- /dev/null +++ b/src/core/task/tools/handlers/AccessMcpResourceHandler.ts @@ -0,0 +1,145 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { ClineAsk } from "@shared/ExtensionMessage" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class AccessMcpResourceHandler implements IFullyManagedTool { + readonly name = "access_mcp_resource" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.server_name}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const server_name = block.params.server_name + const uri = block.params.uri + + // Early return if we don't have enough data yet + if (!server_name || !uri) { + return + } + + const partialMessage = JSON.stringify({ + type: "access_mcp_resource", + serverName: uiHelpers.removeClosingTag(block, "server_name", server_name), + toolName: undefined, + uri: uiHelpers.removeClosingTag(block, "uri", uri), + arguments: undefined, + }) + + // Check if tool should be auto-approved (access_mcp_resource uses general auto-approval) + const shouldAutoApprove = uiHelpers.shouldAutoApproveTool("access_mcp_resource") + + if (shouldAutoApprove) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") + await uiHelpers.say("use_mcp_server" as any, partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") + await uiHelpers.ask("use_mcp_server" as ClineAsk, partialMessage, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const server_name: string | undefined = block.params.server_name + const uri: string | undefined = block.params.uri + + // Validate required parameters + if (!server_name) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("access_mcp_resource", "server_name") + } + + if (!uri) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("access_mcp_resource", "uri") + } + + config.taskState.consecutiveMistakeCount = 0 + + // Handle approval flow + const completeMessage = JSON.stringify({ + type: "access_mcp_resource", + serverName: server_name, + toolName: undefined, + uri: uri, + arguments: undefined, + }) + + // access_mcp_resource uses general auto-approval + const shouldAutoApprove = config.autoApprovalSettings.actions.useMcp + + if (shouldAutoApprove) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") + await config.callbacks.say("use_mcp_server", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + } else { + // Manual approval flow + const notificationMessage = `Cline wants to access ${uri || "unknown resource"} on ${server_name || "unknown server"}` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") + + // Ask for approval + const { response } = await config.callbacks.ask("use_mcp_server", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return "The user denied this operation." + } else { + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + // Show MCP request started message + await config.callbacks.say("mcp_server_request_started") + + try { + // Execute the MCP resource access + const resourceResult = await config.services.mcpHub.readResource(server_name, uri) + + // Process the resource result + const resourceResultPretty = + resourceResult?.contents + .map((item: any) => { + if (item.text) { + return item.text + } + return "" + }) + .filter(Boolean) + .join("\n\n") || "(Empty response)" + + // Display result to user + await config.callbacks.say("mcp_server_response", resourceResultPretty) + + // Return formatted result + return formatResponse.toolResult(resourceResultPretty) + } catch (error) { + return `Error accessing MCP resource: ${(error as Error)?.message}` + } + } +} diff --git a/src/core/task/tools/handlers/AskFollowupQuestionToolHandler.ts b/src/core/task/tools/handlers/AskFollowupQuestionToolHandler.ts new file mode 100644 index 00000000..563c2f32 --- /dev/null +++ b/src/core/task/tools/handlers/AskFollowupQuestionToolHandler.ts @@ -0,0 +1,104 @@ +import { processFilesIntoText } from "@integrations/misc/extract-text" +import { showSystemNotification } from "@integrations/notifications" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { findLast, parsePartialArrayString } from "@shared/array" +import { ClineAsk, ClineAskQuestion } from "@shared/ExtensionMessage" +import { ToolUse, ToolUseName } from "../../../assistant-message" +import { formatResponse } from "../../../prompts/responses" +import { ToolResponse } from "../.." +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class AskFollowupQuestionToolHandler implements IToolHandler, IPartialBlockHandler { + name = "ask_followup_question" + supportedTools: ToolUseName[] = ["ask_followup_question"] + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.question}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const question = block.params.question || "" + const optionsRaw = block.params.options || "[]" + const sharedMessage = { + question: uiHelpers.removeClosingTag(block, "question", question), + options: parsePartialArrayString(uiHelpers.removeClosingTag(block, "options", optionsRaw)), + } satisfies ClineAskQuestion + + // For followup, just stream ask messages + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "followup") + await uiHelpers.ask("followup" as ClineAsk, JSON.stringify(sharedMessage), block.partial).catch(() => {}) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + try { + const question: string | undefined = block.params.question + const optionsRaw: string | undefined = block.params.options + + // Validate required parameter + if (!question) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("ask_followup_question", "question") + } + config.taskState.consecutiveMistakeCount = 0 + + // Show notification if auto-approval is enabled + if (config.autoApprovalSettings.enabled && config.autoApprovalSettings.enableNotifications) { + showSystemNotification({ + subtitle: "Cline has a question...", + message: question.replace(/\n/g, " "), + }) + } + + const sharedMessage = { + question: question, + options: parsePartialArrayString(optionsRaw || "[]"), + } satisfies ClineAskQuestion + + const options = parsePartialArrayString(optionsRaw || "[]") + + // Ask the question + const { + text, + images, + files: followupFiles, + } = await config.callbacks.ask("followup", JSON.stringify(sharedMessage), false) + + // Check if options contains the text response + if (optionsRaw && text && options.includes(text)) { + telemetryService.captureOptionSelected(config.ulid, options.length, "act") + + // Valid option selected, update last followup message with selected option + const clineMessages = config.messageState.getClineMessages() + const lastFollowupMessage = findLast(clineMessages, (m: any) => m.ask === "followup") + if (lastFollowupMessage) { + lastFollowupMessage.text = JSON.stringify({ + ...sharedMessage, + selected: text, + } satisfies ClineAskQuestion) + await config.messageState.saveClineMessagesAndUpdateHistory() + } + } else { + // Option not selected, send user feedback + telemetryService.captureOptionsIgnored(config.ulid, options.length, "act") + await config.callbacks.say("user_feedback", text ?? "", images, followupFiles) + } + + // Process any attached files + let fileContentString = "" + if (followupFiles && followupFiles.length > 0) { + fileContentString = await processFilesIntoText(followupFiles) + } + + return formatResponse.toolResult(`\n${text}\n`, images, fileContentString) + } catch (error) { + return `Error asking question: ${(error as Error).message}` + } + } +} diff --git a/src/core/task/tools/handlers/AttemptCompletionHandler.ts b/src/core/task/tools/handlers/AttemptCompletionHandler.ts new file mode 100644 index 00000000..36336841 --- /dev/null +++ b/src/core/task/tools/handlers/AttemptCompletionHandler.ts @@ -0,0 +1,179 @@ +import type Anthropic from "@anthropic-ai/sdk" +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { processFilesIntoText } from "@integrations/misc/extract-text" +import { showSystemNotification } from "@integrations/notifications" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { findLastIndex } from "@shared/array" +import { COMPLETION_RESULT_CHANGES_FLAG } from "@shared/ExtensionMessage" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class AttemptCompletionHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "attempt_completion" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name}]` + } + + /** + * Handle partial block streaming for attempt_completion + * Matches the original conditional logic structure for command vs no-command cases + */ + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const result = block.params.result + const command = block.params.command + + if (command) { + // the attempt_completion text is done, now we're getting command + // Original had complex logic here but most was commented out + // For now, we'll keep it simple and not stream command (matching original's disabled approach) + // But we can still stream result if we have it + if (result) { + const cleanResult = uiHelpers.removeClosingTag(block, "result", result) + await uiHelpers.say("completion_result", cleanResult, undefined, undefined, true) + } + } else { + // no command, still outputting partial result - MATCH ORIGINAL EXACTLY + if (result) { + const cleanResult = uiHelpers.removeClosingTag(block, "result", result) + await uiHelpers.say("completion_result", cleanResult, undefined, undefined, true) + } + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + const result: string | undefined = block.params.result + const command: string | undefined = block.params.command + + // Validate required parameters + if (!result) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: result" + } + + config.taskState.consecutiveMistakeCount = 0 + + // Show notification if auto-approval is enabled + if (config.autoApprovalSettings.enabled && config.autoApprovalSettings.enableNotifications) { + showSystemNotification({ + subtitle: "Task Completed", + message: result.replace(/\n/g, " "), + }) + } + + const addNewChangesFlagToLastCompletionResultMessage = async () => { + // Add newchanges flag if there are new changes to the workspace + const hasNewChanges = await config.callbacks.doesLatestTaskCompletionHaveNewChanges() + const clineMessages = config.messageState.getClineMessages() + + const lastCompletionResultMessageIndex = findLastIndex(clineMessages, (m: any) => m.say === "completion_result") + const lastCompletionResultMessage = + lastCompletionResultMessageIndex !== -1 ? clineMessages[lastCompletionResultMessageIndex] : undefined + if ( + lastCompletionResultMessage && + lastCompletionResultMessageIndex !== -1 && + hasNewChanges && + !lastCompletionResultMessage.text?.endsWith(COMPLETION_RESULT_CHANGES_FLAG) + ) { + await config.messageState.updateClineMessage(lastCompletionResultMessageIndex, { + text: lastCompletionResultMessage.text + COMPLETION_RESULT_CHANGES_FLAG, + }) + } + } + + let commandResult: any + const lastMessage = config.messageState.getClineMessages().at(-1) + + if (command) { + if (lastMessage && lastMessage.ask !== "command") { + // haven't sent a command message yet so first send completion_result then command + const completionMessageTs = await config.callbacks.say("completion_result", result, undefined, undefined, false) + await config.callbacks.saveCheckpoint(true, completionMessageTs) + await addNewChangesFlagToLastCompletionResultMessage() + telemetryService.captureTaskCompleted(config.ulid) + } else { + // we already sent a command message, meaning the complete completion message has also been sent + await config.callbacks.saveCheckpoint(true) + } + + // complete command message - need to ask for approval + const { response } = await config.callbacks.ask("command", command, false) + if (response !== "yesButtonClicked") { + // User rejected the command + return "The user denied the command execution." + } + + // User approved, execute the command + const [userRejected, execCommandResult] = await config.callbacks.executeCommandTool(command!) + if (userRejected) { + config.taskState.didRejectTool = true + return execCommandResult + } + // user didn't reject, but the command may have output + commandResult = execCommandResult + } else { + const completionMessageTs = await config.callbacks.say("completion_result", result, undefined, undefined, false) + await config.callbacks.saveCheckpoint(true, completionMessageTs) + await addNewChangesFlagToLastCompletionResultMessage() + telemetryService.captureTaskCompleted(config.ulid) + } + + // we already sent completion_result says, an empty string asks relinquishes control over button and field + const { response, text, images, files: completionFiles } = await config.callbacks.ask("completion_result", "", false) + if (response === "yesButtonClicked") { + return "" // signals to recursive loop to stop (for now this never happens since yesButtonClicked will trigger a new task) + } + + await config.callbacks.say("user_feedback", text ?? "", images, completionFiles) + await config.callbacks.saveCheckpoint() + + const toolResults: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = [] + if (commandResult) { + if (typeof commandResult === "string") { + toolResults.push({ + type: "text", + text: commandResult, + }) + } else if (Array.isArray(commandResult)) { + toolResults.push(...commandResult) + } + } + toolResults.push({ + type: "text", + text: `The user has provided feedback on the results. Consider their input to continue the task, and then attempt completion again.\n\n${text}\n`, + }) + toolResults.push(...formatResponse.imageBlocks(images)) + + let fileContentString = "" + if (completionFiles && completionFiles.length > 0) { + fileContentString = await processFilesIntoText(completionFiles) + } + + // Return the tool results as a complex response + return [ + { + type: "text" as const, + text: `[attempt_completion] Result:`, + }, + ...toolResults, + ...(fileContentString + ? [ + { + type: "text" as const, + text: fileContentString, + }, + ] + : []), + ] + } +} diff --git a/src/core/task/tools/handlers/BrowserToolHandler.ts b/src/core/task/tools/handlers/BrowserToolHandler.ts new file mode 100644 index 00000000..4e8f1d46 --- /dev/null +++ b/src/core/task/tools/handlers/BrowserToolHandler.ts @@ -0,0 +1,221 @@ +import { BrowserSession } from "@services/browser/BrowserSession" +import { BrowserAction, BrowserActionResult, browserActions, ClineSayBrowserAction } from "@shared/ExtensionMessage" +import { modelDoesntSupportWebp } from "@utils/model-utils" +import { ToolUse } from "../../../assistant-message" +import { formatResponse } from "../../../prompts/responses" +import { ToolResponse } from "../.." +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class BrowserToolHandler implements IFullyManagedTool { + readonly name = "browser_action" + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.action}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const action: BrowserAction | undefined = block.params.action as BrowserAction + const url: string | undefined = block.params.url + const coordinate: string | undefined = block.params.coordinate + const text: string | undefined = block.params.text + + // Validate action parameter + if (!action || !browserActions.includes(action)) { + return // Wait for more content + } + + // Handle partial block streaming - exact original logic + if (action === "launch") { + if (uiHelpers.shouldAutoApproveTool(block.name)) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "browser_action_launch") + await uiHelpers.say( + "browser_action_launch", + uiHelpers.removeClosingTag(block, "url", url), + undefined, + undefined, + block.partial, + ) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "browser_action_launch") + await uiHelpers + .ask("browser_action_launch", uiHelpers.removeClosingTag(block, "url", url), block.partial) + .catch(() => {}) + } + } else { + await uiHelpers.say( + "browser_action", + JSON.stringify({ + action: action as BrowserAction, + coordinate: uiHelpers.removeClosingTag(block, "coordinate", coordinate), + text: uiHelpers.removeClosingTag(block, "text", text), + } satisfies ClineSayBrowserAction), + undefined, + undefined, + block.partial, + ) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + const action: BrowserAction | undefined = block.params.action as BrowserAction + const url: string | undefined = block.params.url + const coordinate: string | undefined = block.params.coordinate + const text: string | undefined = block.params.text + + // Validate action parameter - following original pattern + if (!action || !browserActions.includes(action)) { + // if the block is complete and we don't have a valid action this is a mistake + config.taskState.consecutiveMistakeCount++ + const errorResult = await config.callbacks.sayAndCreateMissingParamError("browser_action", "action") + await config.services.browserSession.closeBrowser() + await config.callbacks.saveCheckpoint() + return errorResult + } + + try { + // Handle complete block execution + let browserActionResult: BrowserActionResult + + if (action === "launch") { + if (!url) { + config.taskState.consecutiveMistakeCount++ + const errorResult = await config.callbacks.sayAndCreateMissingParamError("browser_action", "url") + await config.services.browserSession.closeBrowser() + await config.callbacks.saveCheckpoint() + return errorResult + } + config.taskState.consecutiveMistakeCount = 0 + + // Handle approval flow for launch using callbacks + const autoApprover = config.autoApprover || { shouldAutoApproveTool: () => false } + if (autoApprover.shouldAutoApproveTool(block.name)) { + await config.callbacks.say("browser_action_launch", url, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + } else { + // Show notification for approval if auto approval enabled + const { showNotificationForApprovalIfAutoApprovalEnabled } = require("../../utils") + showNotificationForApprovalIfAutoApprovalEnabled( + `Cline wants to use a browser and launch ${url}`, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + const { response } = await config.callbacks.ask("browser_action_launch", url, false) + if (response !== "yesButtonClicked") { + await config.callbacks.saveCheckpoint() + return formatResponse.toolResult("The user rejected this browser action.") + } + } + + // Start loading spinner + await config.callbacks.say("browser_action_result", "") + + // Re-make browserSession to make sure latest settings apply + const browserSession = config.services.browserSession + if (config.context) { + await browserSession.dispose() + const apiHandlerModel = config.api.getModel() + const useWebp = config.api ? !modelDoesntSupportWebp(apiHandlerModel) : true + config.services.browserSession = new BrowserSession(config.context, config.browserSettings, useWebp) + } else { + console.warn("no controller context available for browserSession") + } + await config.services.browserSession.launchBrowser() + browserActionResult = await config.services.browserSession.navigateToUrl(url) + } else { + // Handle other actions (click, type, scroll, close) + if (action === "click") { + if (!coordinate) { + config.taskState.consecutiveMistakeCount++ + const errorResult = await config.callbacks.sayAndCreateMissingParamError("browser_action", "coordinate") + await config.services.browserSession.closeBrowser() + await config.callbacks.saveCheckpoint() + return errorResult + } + } + if (action === "type") { + if (!text) { + config.taskState.consecutiveMistakeCount++ + const errorResult = await config.callbacks.sayAndCreateMissingParamError("browser_action", "text") + await config.services.browserSession.closeBrowser() + await config.callbacks.saveCheckpoint() + return errorResult + } + } + config.taskState.consecutiveMistakeCount = 0 + + // Send browser action message + await config.callbacks.say( + "browser_action", + JSON.stringify({ + action: action as BrowserAction, + coordinate, + text, + } satisfies ClineSayBrowserAction), + undefined, + undefined, + false, + ) + + // Execute the action + const browserSession = config.services.browserSession + switch (action) { + case "click": + browserActionResult = await browserSession.click(coordinate!) + break + case "type": + browserActionResult = await browserSession.type(text!) + break + case "scroll_down": + browserActionResult = await browserSession.scrollDown() + break + case "scroll_up": + browserActionResult = await browserSession.scrollUp() + break + case "close": + browserActionResult = await browserSession.closeBrowser() + break + } + } + + // Handle results based on action type + switch (action) { + case "launch": + case "click": + case "type": + case "scroll_down": + case "scroll_up": + await config.callbacks.say("browser_action_result", JSON.stringify(browserActionResult)) + const result = formatResponse.toolResult( + `The browser action has been executed. The console logs and screenshot have been captured for your analysis.\n\nConsole logs:\n${ + browserActionResult.logs || "(No new logs)" + }\n\n(REMEMBER: if you need to proceed to using non-\`browser_action\` tools or launch a new browser, you MUST first close this browser. For example, if after analyzing the logs and screenshot you need to edit a file, you must first close the browser before you can use the write_to_file tool.)`, + browserActionResult.screenshot ? [browserActionResult.screenshot] : [], + ) + + await config.callbacks.saveCheckpoint() + return result + + case "close": + const closeResult = formatResponse.toolResult( + `The browser has been closed. You may now proceed to using other tools.`, + ) + await config.callbacks.saveCheckpoint() + return closeResult + } + } catch (error) { + await config.services.browserSession.closeBrowser() // if any error occurs, the browser session is terminated + return `Error executing browser action: ${(error as Error).message}` + } + + // This should never be reached, but TypeScript requires a return + return "" + } +} diff --git a/src/core/task/tools/handlers/CondenseHandler.ts b/src/core/task/tools/handlers/CondenseHandler.ts new file mode 100644 index 00000000..6931640c --- /dev/null +++ b/src/core/task/tools/handlers/CondenseHandler.ts @@ -0,0 +1,92 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { ensureTaskDirectoryExists } from "@core/storage/disk" +import { processFilesIntoText } from "@integrations/misc/extract-text" +import { showSystemNotification } from "@integrations/notifications" +import { ClineAsk } from "@shared/ExtensionMessage" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class CondenseHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "condense" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name}]` + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + const context: string | undefined = block.params.context + + // Validate required parameters + if (!context) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: context" + } + + config.taskState.consecutiveMistakeCount = 0 + + // Show notification if auto-approval is enabled + if (config.autoApprovalSettings.enabled && config.autoApprovalSettings.enableNotifications) { + showSystemNotification({ + subtitle: "Cline wants to condense the conversation...", + message: `Cline is suggesting to condense your conversation with: ${context}`, + }) + } + + // Ask user for response + const { text, images, files: condenseFiles } = await config.callbacks.ask("condense", context, false) + + // If the user provided a response, treat it as feedback + if (text || (images && images.length > 0) || (condenseFiles && condenseFiles.length > 0)) { + let fileContentString = "" + if (condenseFiles && condenseFiles.length > 0) { + fileContentString = await processFilesIntoText(condenseFiles) + } + + await config.callbacks.say("user_feedback", text ?? "", images, condenseFiles) + return formatResponse.toolResult( + `The user provided feedback on the condensed conversation summary:\n\n${text}\n`, + images, + fileContentString, + ) + } else { + // If no response, the user accepted the condensed version + const apiConversationHistory = config.messageState.getApiConversationHistory() + const lastMessage = apiConversationHistory[apiConversationHistory.length - 1] + const summaryAlreadyAppended = lastMessage && lastMessage.role === "assistant" + const keepStrategy = summaryAlreadyAppended ? "lastTwo" : "none" + + // clear the context history at this point in time + config.taskState.conversationHistoryDeletedRange = config.services.contextManager.getNextTruncationRange( + apiConversationHistory, + config.taskState.conversationHistoryDeletedRange, + keepStrategy, + ) + await config.messageState.saveClineMessagesAndUpdateHistory() + await config.services.contextManager.triggerApplyStandardContextTruncationNoticeChange( + Date.now(), + await ensureTaskDirectoryExists(config.context, config.taskId), + apiConversationHistory, + ) + + return formatResponse.toolResult(formatResponse.condense()) + } + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const context = block.params.context || "" + const cleanedContext = uiHelpers.removeClosingTag(block, "context", context) + + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "condense") + await uiHelpers.ask("condense" as ClineAsk, cleanedContext, block.partial).catch(() => {}) + } +} diff --git a/src/core/task/tools/handlers/ExecuteCommandToolHandler.ts b/src/core/task/tools/handlers/ExecuteCommandToolHandler.ts new file mode 100644 index 00000000..b53d9cc5 --- /dev/null +++ b/src/core/task/tools/handlers/ExecuteCommandToolHandler.ts @@ -0,0 +1,150 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { showSystemNotification } from "@integrations/notifications" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { COMMAND_REQ_APP_STRING } from "@shared/combineCommandSequences" +import { ClineAsk } from "@shared/ExtensionMessage" +import { fixModelHtmlEscaping } from "@utils/string" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class ExecuteCommandToolHandler implements IFullyManagedTool { + readonly name = "execute_command" + + constructor(_validator: ToolValidator) {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.command}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const command = block.params.command + + // For commands, we need to wait for the requires_approval parameter before showing UI + // This is because the approval flow depends on that parameter + if (!block.params.requires_approval) { + return // Wait for complete block + } + + // Command partial streaming is handled differently - just show the command + const partialCommand = uiHelpers.removeClosingTag(block, "command", command) + + // Check if this should be auto-approved to determine UI flow + const shouldAutoApprove = uiHelpers.shouldAutoApproveTool("execute_command") + + if (shouldAutoApprove) { + // For auto-approved commands, we can't partially stream a say prematurely + // since it may become an ask based on the requires_approval parameter + // So we wait for the complete block + return + } else { + // For manual approval, stream the ask message + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "command") + await uiHelpers.ask("command" as ClineAsk, partialCommand, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + try { + let command: string | undefined = block.params.command + const requiresApprovalRaw: string | undefined = block.params.requires_approval + const requiresApprovalPerLLM = requiresApprovalRaw?.toLowerCase() === "true" + + // Validate required parameters + if (!command) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("execute_command", "command") + } + + if (!requiresApprovalRaw) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("execute_command", "requires_approval") + } + + config.taskState.consecutiveMistakeCount = 0 + + // Pre-process command for certain models + if (config.api.getModel().id.includes("gemini")) { + command = fixModelHtmlEscaping(command) + } + + // Check clineignore validation for command + const ignoredFileAttemptedToAccess = config.services.clineIgnoreController.validateCommand(command) + if (ignoredFileAttemptedToAccess) { + await config.callbacks.say("clineignore_error", ignoredFileAttemptedToAccess) + return formatResponse.toolError(formatResponse.clineIgnoreError(ignoredFileAttemptedToAccess)) + } + + let didAutoApprove = false + + // Complex dual approval system for commands + const autoApproveResult = config.autoApprover?.shouldAutoApproveTool(block.name) + const [autoApproveSafe, autoApproveAll] = Array.isArray(autoApproveResult) + ? autoApproveResult + : [autoApproveResult, false] + + if ((!requiresApprovalPerLLM && autoApproveSafe) || (requiresApprovalPerLLM && autoApproveSafe && autoApproveAll)) { + // Auto-approve flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "command") + await config.callbacks.say("command", command, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + didAutoApprove = true + telemetryService.captureToolUsage(config.ulid, "execute_command", config.api.getModel().id, true, true) + } else { + // Manual approval flow + showNotificationForApprovalIfAutoApprovalEnabled( + `Cline wants to execute a command: ${command}`, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + const { response } = await config.callbacks.ask( + "command", + command + `${autoApproveSafe && requiresApprovalPerLLM ? COMMAND_REQ_APP_STRING : ""}`, + false, + ) + + if (response !== "yesButtonClicked") { + telemetryService.captureToolUsage(config.ulid, "execute_command", config.api.getModel().id, false, false) + return "The user denied this operation." + } + telemetryService.captureToolUsage(config.ulid, "execute_command", config.api.getModel().id, false, true) + } + + // Setup timeout notification for long-running auto-approved commands + let timeoutId: NodeJS.Timeout | undefined + if (didAutoApprove && config.autoApprovalSettings.enableNotifications) { + timeoutId = setTimeout(() => { + showSystemNotification({ + subtitle: "Command is still running", + message: "An auto-approved command has been running for 30s, and may need your attention.", + }) + }, 30_000) + } + + // Execute the command + const [userRejected, result] = await config.callbacks.executeCommandTool(command) + + if (timeoutId) { + clearTimeout(timeoutId) + } + + if (userRejected) { + config.taskState.didRejectTool = true + } + + return result + } catch (error) { + return `Error executing command: ${(error as Error).message}` + } + } +} diff --git a/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts b/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts new file mode 100644 index 00000000..321539d1 --- /dev/null +++ b/src/core/task/tools/handlers/ListCodeDefinitionNamesToolHandler.ts @@ -0,0 +1,121 @@ +import type { ToolUse } from "@core/assistant-message" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { parseSourceCodeForDefinitionsTopLevel } from "@services/tree-sitter" +import { getReadablePath, isLocatedInWorkspace } from "@utils/path" +import * as path from "path" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class ListCodeDefinitionNamesToolHandler implements IFullyManagedTool { + readonly name = "list_code_definition_names" + + constructor(private validator: ToolValidator) {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.path}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const relPath = block.params.path + + // Early return if we don't have enough data yet + if (!relPath) { + return + } + + // Get config access for services + const config = uiHelpers.getConfig() + + // Create and show partial UI message + const absolutePath = path.resolve(config.cwd, relPath) + const sharedMessageProps = { + tool: "listCodeDefinitionNames", + path: getReadablePath(config.cwd, uiHelpers.removeClosingTag(block, "path", relPath)), + content: absolutePath, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), + } + + const partialMessage = JSON.stringify(sharedMessageProps) + + // Handle auto-approval vs manual approval for partial + if (await uiHelpers.shouldAutoApproveToolWithPath(block.name, relPath)) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "tool") + await uiHelpers.say("tool", partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool") + await uiHelpers.ask("tool", partialMessage, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const relDirPath: string | undefined = block.params.path + + // Validate required parameters + const pathValidation = this.validator.assertRequiredParams(block, "path") + if (!pathValidation.ok) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("list_code_definition_names", "path") + } + + config.taskState.consecutiveMistakeCount = 0 + const absolutePath = path.resolve(config.cwd, relDirPath!) + + // Handle approval flow + const sharedMessageProps = { + tool: "listCodeDefinitionNames", + path: getReadablePath(config.cwd, relDirPath!), + content: absolutePath, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relDirPath!), + } + + const completeMessage = JSON.stringify(sharedMessageProps) + + if (await config.callbacks.shouldAutoApproveToolWithPath(block.name, relDirPath)) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "tool") + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + } else { + // Manual approval flow + const notificationMessage = `Cline wants to analyze code definitions in ${path.basename(absolutePath)}` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "tool") + + // Ask for approval + const { response } = await config.callbacks.ask("tool", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return "The user denied this operation." + } else { + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + // Execute the actual parse source code operation + const result = await parseSourceCodeForDefinitionsTopLevel(absolutePath, config.services.clineIgnoreController) + + return result + } +} diff --git a/src/core/task/tools/handlers/ListFilesToolHandler.ts b/src/core/task/tools/handlers/ListFilesToolHandler.ts new file mode 100644 index 00000000..1e50c0f6 --- /dev/null +++ b/src/core/task/tools/handlers/ListFilesToolHandler.ts @@ -0,0 +1,128 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { listFiles } from "@services/glob/list-files" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { getReadablePath, isLocatedInWorkspace } from "@utils/path" +import * as path from "path" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class ListFilesToolHandler implements IFullyManagedTool { + readonly name = "list_files" + + constructor(private validator: ToolValidator) {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.path}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const relPath = block.params.path + + // Early return if we don't have enough data yet + if (!relPath) { + return + } + + // Get config access for services + const config = uiHelpers.getConfig() + + // Create and show partial UI message + const absolutePath = path.resolve(config.cwd, relPath) + const recursiveRaw = block.params.recursive + const recursive = recursiveRaw?.toLowerCase() === "true" + const sharedMessageProps = { + tool: recursive ? "listFilesRecursive" : "listFilesTopLevel", + path: getReadablePath(config.cwd, uiHelpers.removeClosingTag(block, "path", relPath)), + content: absolutePath, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), + } + + const partialMessage = JSON.stringify(sharedMessageProps) + + // Handle auto-approval vs manual approval for partial + if (await uiHelpers.shouldAutoApproveToolWithPath(block.name, relPath)) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "tool") + await uiHelpers.say("tool", partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool") + await uiHelpers.ask("tool", partialMessage, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const relDirPath: string | undefined = block.params.path + const recursiveRaw: string | undefined = block.params.recursive + const recursive = recursiveRaw?.toLowerCase() === "true" + + // Validate required parameters + const pathValidation = this.validator.assertRequiredParams(block, "path") + if (!pathValidation.ok) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("list_files", "path") + } + + config.taskState.consecutiveMistakeCount = 0 + const absolutePath = path.resolve(config.cwd, relDirPath!) + + // Handle approval flow + const sharedMessageProps = { + tool: recursive ? "listFilesRecursive" : "listFilesTopLevel", + path: getReadablePath(config.cwd, relDirPath!), + content: absolutePath, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relDirPath!), + } + + const completeMessage = JSON.stringify(sharedMessageProps) + + if (await config.callbacks.shouldAutoApproveToolWithPath(block.name, relDirPath)) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "tool") + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + } else { + // Manual approval flow + const notificationMessage = `Cline wants to view directory ${path.basename(absolutePath)}/` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "tool") + + // Ask for approval + const { response } = await config.callbacks.ask("tool", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return "The user denied this operation." + } else { + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + // Execute the actual list files operation + const [files, didHitLimit] = await listFiles(absolutePath, recursive, 200) + + const result = formatResponse.formatFilesList(absolutePath, files, didHitLimit, config.services.clineIgnoreController) + + return result + } +} diff --git a/src/core/task/tools/handlers/LoadMcpDocumentationHandler.ts b/src/core/task/tools/handlers/LoadMcpDocumentationHandler.ts new file mode 100644 index 00000000..de199828 --- /dev/null +++ b/src/core/task/tools/handlers/LoadMcpDocumentationHandler.ts @@ -0,0 +1,41 @@ +import type { ToolUse } from "@core/assistant-message" +import { loadMcpDocumentation } from "@core/prompts/loadMcpDocumentation" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class LoadMcpDocumentationHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "load_mcp_documentation" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name}]` + } + + async handlePartialBlock(_block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + // Show loading message for partial blocks (though this tool probably won't have partials) + await uiHelpers.say("load_mcp_documentation", "", undefined, undefined, true) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet (though this tool shouldn't have partial blocks) + if (block.partial) { + return "" + } + + // Show loading message at start of execution (self-managed now) + await config.callbacks.say("load_mcp_documentation", "", undefined, undefined, false) + + config.taskState.consecutiveMistakeCount = 0 + + try { + // Load MCP documentation + const documentation = await loadMcpDocumentation(config.services.mcpHub) + return documentation + } catch (error) { + return `Error loading MCP documentation: ${(error as Error)?.message}` + } + } +} diff --git a/src/core/task/tools/handlers/NewTaskHandler.ts b/src/core/task/tools/handlers/NewTaskHandler.ts new file mode 100644 index 00000000..fa69bf2b --- /dev/null +++ b/src/core/task/tools/handlers/NewTaskHandler.ts @@ -0,0 +1,72 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { processFilesIntoText } from "@integrations/misc/extract-text" +import { showSystemNotification } from "@integrations/notifications" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class NewTaskHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "new_task" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name} for creating a new task]` + } + + /** + * Handle partial block streaming for new_task + */ + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const context = uiHelpers.removeClosingTag(block, "context", block.params.context) + await uiHelpers.ask("new_task", context, true).catch(() => {}) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + const context: string | undefined = block.params.context + + // Validate required parameters + if (!context) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: context" + } + + config.taskState.consecutiveMistakeCount = 0 + + // Show notification if auto-approval is enabled + if (config.autoApprovalSettings.enabled && config.autoApprovalSettings.enableNotifications) { + showSystemNotification({ + subtitle: "Cline wants to start a new task...", + message: `Cline is suggesting to start a new task with: ${context}`, + }) + } + + // Ask user for response + const { text, images, files: newTaskFiles } = await config.callbacks.ask("new_task", context, false) + + // If the user provided a response, treat it as feedback + if (text || (images && images.length > 0) || (newTaskFiles && newTaskFiles.length > 0)) { + let fileContentString = "" + if (newTaskFiles && newTaskFiles.length > 0) { + fileContentString = await processFilesIntoText(newTaskFiles) + } + + await config.callbacks.say("user_feedback", text ?? "", images, newTaskFiles) + return formatResponse.toolResult( + `The user provided feedback instead of creating a new task:\n\n${text}\n`, + images, + fileContentString, + ) + } else { + // If no response, the user clicked the "Create New Task" button + return formatResponse.toolResult(`The user has created a new task with the provided context.`) + } + } +} diff --git a/src/core/task/tools/handlers/PlanModeRespondHandler.ts b/src/core/task/tools/handlers/PlanModeRespondHandler.ts new file mode 100644 index 00000000..3885b094 --- /dev/null +++ b/src/core/task/tools/handlers/PlanModeRespondHandler.ts @@ -0,0 +1,131 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { findLast, parsePartialArrayString } from "@shared/array" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class PlanModeRespondHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "plan_mode_respond" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name}]` + } + + /** + * Handle partial block streaming for plan_mode_respond + */ + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const response = block.params.response + const optionsRaw = block.params.options + + const sharedMessage = { + response: uiHelpers.removeClosingTag(block, "response", response), + options: parsePartialArrayString(uiHelpers.removeClosingTag(block, "options", optionsRaw)), + } + + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "plan_mode_respond") + await uiHelpers.ask("plan_mode_respond", JSON.stringify(sharedMessage), true).catch(() => {}) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + const response: string | undefined = block.params.response + const optionsRaw: string | undefined = block.params.options + const needsMoreExploration: boolean = block.params.needs_more_exploration === "true" + + // Validate required parameters + if (!response) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: response" + } + + config.taskState.consecutiveMistakeCount = 0 + + // Handle needs_more_exploration escape hatch + if (needsMoreExploration) { + return formatResponse.toolResult( + `[You have indicated that you need more exploration. Proceed with calling tools to continue the planning process.]`, + ) + } + + // Store the number of options for telemetry + const options = parsePartialArrayString(optionsRaw || "[]") + + // Set awaiting plan response state + config.taskState.isAwaitingPlanResponse = true + + const sharedMessage = { + response: response, + options: options, + } + + // Ask for user response + let { + text, + images, + files: planResponseFiles, + } = await config.callbacks.ask("plan_mode_respond", JSON.stringify(sharedMessage), false) + + config.taskState.isAwaitingPlanResponse = false + + // Handle mode toggle marker + if (text === "PLAN_MODE_TOGGLE_RESPONSE") { + text = "" + } + + // Check if options contains the text response + if (optionsRaw && text && parsePartialArrayString(optionsRaw).includes(text)) { + telemetryService.captureOptionSelected(config.ulid, options.length, "plan") + // Valid option selected, don't show user message in UI + // Update last plan message with selected option + const lastPlanMessage = findLast(config.messageState.getClineMessages(), (m: any) => m.ask === "plan_mode_respond") + if (lastPlanMessage) { + lastPlanMessage.text = JSON.stringify({ + ...sharedMessage, + selected: text, + }) + await config.messageState.saveClineMessagesAndUpdateHistory() + } + } else { + // Option not selected, send user feedback + if (text || (images && images.length > 0) || (planResponseFiles && planResponseFiles.length > 0)) { + telemetryService.captureOptionsIgnored(config.ulid, options.length, "plan") + await config.callbacks.say("user_feedback", text ?? "", images, planResponseFiles) + await config.callbacks.saveCheckpoint() + } + } + + let fileContentString = "" + if (planResponseFiles && planResponseFiles.length > 0) { + const { processFilesIntoText } = await import("@integrations/misc/extract-text") + fileContentString = await processFilesIntoText(planResponseFiles) + } + + // Handle mode switching response + if (config.taskState.didRespondToPlanAskBySwitchingMode) { + const result = formatResponse.toolResult( + `[The user has switched to ACT MODE, so you may now proceed with the task.]` + + (text + ? `\n\nThe user also provided the following message when switching to ACT MODE:\n\n${text}\n` + : ""), + images, + fileContentString, + ) + // Reset the flag after using it to prevent it from persisting + config.taskState.didRespondToPlanAskBySwitchingMode = false + return result + } else { + // if we didn't switch to ACT MODE, then we can just send the user_feedback message + return formatResponse.toolResult(`\n${text}\n`, images, fileContentString) + } + } +} diff --git a/src/core/task/tools/handlers/ReadFileToolHandler.ts b/src/core/task/tools/handlers/ReadFileToolHandler.ts new file mode 100644 index 00000000..f2617ab6 --- /dev/null +++ b/src/core/task/tools/handlers/ReadFileToolHandler.ts @@ -0,0 +1,146 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { extractFileContent } from "@integrations/misc/extract-file-content" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { getReadablePath, isLocatedInWorkspace } from "@utils/path" +import * as path from "path" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class ReadFileToolHandler implements IFullyManagedTool { + readonly name = "read_file" + + constructor(private validator: ToolValidator) {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.path}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const relPath = block.params.path + + // Early return if we don't have enough data yet + if (!relPath) { + return + } + + // Get config access for services + const config = uiHelpers.getConfig() + + // Check clineignore access first + const accessValidation = this.validator.checkClineIgnorePath(relPath) + if (!accessValidation.ok) { + // Show error and return early + await uiHelpers.say("clineignore_error", relPath) + return + } + + // Create and show partial UI message + const absolutePath = path.resolve(config.cwd, relPath) + const sharedMessageProps = { + tool: "readFile", + path: getReadablePath(config.cwd, uiHelpers.removeClosingTag(block, "path", relPath)), + content: absolutePath, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), + } + + const partialMessage = JSON.stringify(sharedMessageProps) + + // Handle auto-approval vs manual approval for partial + if (await uiHelpers.shouldAutoApproveToolWithPath(block.name, relPath)) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "tool") + await uiHelpers.say("tool", partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool") + await uiHelpers.ask("tool", partialMessage, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const relPath: string | undefined = block.params.path + + // Validate required parameters + const pathValidation = this.validator.assertRequiredParams(block, "path") + if (!pathValidation.ok) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("read_file", "path") + } + + // Check clineignore access + const accessValidation = this.validator.checkClineIgnorePath(relPath!) + if (!accessValidation.ok) { + await config.callbacks.say("clineignore_error", relPath) + return formatResponse.toolError(formatResponse.clineIgnoreError(relPath!)) + } + + config.taskState.consecutiveMistakeCount = 0 + const absolutePath = path.resolve(config.cwd, relPath!) + + // Handle approval flow + const sharedMessageProps = { + tool: "readFile", + path: getReadablePath(config.cwd, relPath!), + content: absolutePath, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath!), + } + + const completeMessage = JSON.stringify(sharedMessageProps) + + if (await config.callbacks.shouldAutoApproveToolWithPath(block.name, relPath)) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "tool") + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + } else { + // Manual approval flow + const notificationMessage = `Cline wants to read ${path.basename(absolutePath)}` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "tool") + + // Ask for approval + const { response } = await config.callbacks.ask("tool", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return "The user denied this operation." + } else { + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + // Execute the actual file read operation + const supportsImages = config.api.getModel().info.supportsImages ?? false + const result = await extractFileContent(absolutePath, supportsImages) + + // Track file read operation + await config.services.fileContextTracker.trackFileContext(relPath!, "read_tool") + + // Handle image blocks separately - they need to be pushed to userMessageContent + if (result.imageBlock) { + config.taskState.userMessageContent.push(result.imageBlock) + } + + return result.text + } +} diff --git a/src/core/task/tools/handlers/ReportBugHandler.ts b/src/core/task/tools/handlers/ReportBugHandler.ts new file mode 100644 index 00000000..1f573732 --- /dev/null +++ b/src/core/task/tools/handlers/ReportBugHandler.ts @@ -0,0 +1,143 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { processFilesIntoText } from "@integrations/misc/extract-text" +import { showSystemNotification } from "@integrations/notifications" +import { ClineAsk } from "@shared/ExtensionMessage" +import { createAndOpenGitHubIssue } from "@utils/github-url-utils" +import * as os from "os" +import * as vscode from "vscode" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class ReportBugHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "report_bug" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name}]` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const partialMessage = JSON.stringify({ + title: uiHelpers.removeClosingTag(block, "title", block.params.title), + what_happened: uiHelpers.removeClosingTag(block, "what_happened", block.params.what_happened), + steps_to_reproduce: uiHelpers.removeClosingTag(block, "steps_to_reproduce", block.params.steps_to_reproduce), + api_request_output: uiHelpers.removeClosingTag(block, "api_request_output", block.params.api_request_output), + additional_context: uiHelpers.removeClosingTag(block, "additional_context", block.params.additional_context), + }) + + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "report_bug") + await uiHelpers.ask("report_bug" as ClineAsk, partialMessage, block.partial).catch(() => {}) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + const title = block.params.title + const what_happened = block.params.what_happened + const steps_to_reproduce = block.params.steps_to_reproduce + const api_request_output = block.params.api_request_output + const additional_context = block.params.additional_context + + // Validate required parameters + if (!title) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: title" + } + if (!what_happened) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: what_happened" + } + if (!steps_to_reproduce) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: steps_to_reproduce" + } + if (!api_request_output) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: api_request_output" + } + if (!additional_context) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: additional_context" + } + + config.taskState.consecutiveMistakeCount = 0 + + // Show notification if auto-approval is enabled + if (config.autoApprovalSettings.enabled && config.autoApprovalSettings.enableNotifications) { + showSystemNotification({ + subtitle: "Cline wants to create a github issue...", + message: `Cline is suggesting to create a github issue with the title: ${title}`, + }) + } + + // Derive system information values algorithmically + const operatingSystem = os.platform() + " " + os.release() + const clineVersion = vscode.extensions.getExtension("saoudrizwan.claude-dev")?.packageJSON.version || "Unknown" + const systemInfo = `VSCode: ${vscode.version}, Node.js: ${process.version}, Architecture: ${os.arch()}` + const currentMode = config.mode + const apiConfig = config.services.stateManager.getApiConfiguration() + const apiProvider = currentMode === "plan" ? apiConfig.planModeApiProvider : apiConfig.actModeApiProvider + const providerAndModel = `${apiProvider} / ${config.api.getModel().id}` + + // Ask user for confirmation + const bugReportData = JSON.stringify({ + title, + what_happened, + steps_to_reproduce, + api_request_output, + additional_context, + // Include derived values in the JSON for display purposes + provider_and_model: providerAndModel, + operating_system: operatingSystem, + system_info: systemInfo, + cline_version: clineVersion, + }) + + const { text, images, files: reportBugFiles } = await config.callbacks.ask("report_bug", bugReportData, false) + + // If the user provided a response, treat it as feedback + if (text || (images && images.length > 0) || (reportBugFiles && reportBugFiles.length > 0)) { + let fileContentString = "" + if (reportBugFiles && reportBugFiles.length > 0) { + fileContentString = await processFilesIntoText(reportBugFiles) + } + + await config.callbacks.say("user_feedback", text ?? "", images, reportBugFiles) + return formatResponse.toolResult( + `The user did not submit the bug, and provided feedback on the Github issue generated instead:\n\n${text}\n`, + images, + fileContentString, + ) + } else { + // If no response, the user accepted the bug report + try { + // Create a Map of parameters for the GitHub issue + const params = new Map() + params.set("title", title) + params.set("operating-system", operatingSystem) + params.set("cline-version", clineVersion) + params.set("system-info", systemInfo) + params.set("additional-context", additional_context) + params.set("what-happened", what_happened) + params.set("steps", steps_to_reproduce) + params.set("provider-model", providerAndModel) + params.set("logs", api_request_output) + + // Use our utility function to create and open the GitHub issue URL + // This bypasses VS Code's URI handling issues with special characters + await createAndOpenGitHubIssue("cline", "cline", "bug_report.yml", params) + } catch (error) { + console.error(`An error occurred while attempting to report the bug: ${error}`) + } + + return formatResponse.toolResult(`The user accepted the creation of the Github issue.`) + } + } +} diff --git a/src/core/task/tools/handlers/SearchFilesToolHandler.ts b/src/core/task/tools/handlers/SearchFilesToolHandler.ts new file mode 100644 index 00000000..7059c321 --- /dev/null +++ b/src/core/task/tools/handlers/SearchFilesToolHandler.ts @@ -0,0 +1,144 @@ +import type { ToolUse } from "@core/assistant-message" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { regexSearchFiles } from "@services/ripgrep" +import { getReadablePath, isLocatedInWorkspace } from "@utils/path" +import * as path from "path" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class SearchFilesToolHandler implements IFullyManagedTool { + readonly name = "search_files" + + constructor(private validator: ToolValidator) {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.regex}'${ + block.params.file_pattern ? ` in '${block.params.file_pattern}'` : "" + }]` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const relPath = block.params.path + const regex = block.params.regex + + // Early return if we don't have enough data yet + if (!relPath || !regex) { + return + } + + // Get config access for services + const config = uiHelpers.getConfig() + + // Create and show partial UI message + const filePattern = block.params.file_pattern + const searchDescription = `'${regex}'${filePattern ? ` in '${filePattern}'` : ""}` + + const sharedMessageProps = { + tool: "searchFiles", + path: getReadablePath(config.cwd, uiHelpers.removeClosingTag(block, "path", relPath)), + content: `Searching for ${searchDescription}`, + regex: uiHelpers.removeClosingTag(block, "regex", regex), + filePattern: filePattern ? uiHelpers.removeClosingTag(block, "file_pattern", filePattern) : undefined, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), + } + + const partialMessage = JSON.stringify(sharedMessageProps) + + // Handle auto-approval vs manual approval for partial + if (await uiHelpers.shouldAutoApproveToolWithPath(block.name, relPath)) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "tool") + await uiHelpers.say("tool", partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool") + await uiHelpers.ask("tool", partialMessage, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const relDirPath: string | undefined = block.params.path + const regex: string | undefined = block.params.regex + const filePattern: string | undefined = block.params.file_pattern + + // Validate required parameters + const pathValidation = this.validator.assertRequiredParams(block, "path") + if (!pathValidation.ok) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("search_files", "path") + } + + if (!regex) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("search_files", "regex") + } + + config.taskState.consecutiveMistakeCount = 0 + const absolutePath = path.resolve(config.cwd, relDirPath!) + + // Handle approval flow + const searchDescription = `'${regex}'${filePattern ? ` in '${filePattern}'` : ""}` + const sharedMessageProps = { + tool: "searchFiles", + path: getReadablePath(config.cwd, relDirPath!), + content: `Searching for ${searchDescription}`, + regex: regex, + filePattern: filePattern, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relDirPath!), + } + + const completeMessage = JSON.stringify(sharedMessageProps) + + if (await config.callbacks.shouldAutoApproveToolWithPath(block.name, relDirPath)) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "tool") + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + } else { + // Manual approval flow + const notificationMessage = `Cline wants to search files for ${regex}` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "tool") + + // Ask for approval + const { response } = await config.callbacks.ask("tool", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return "The user denied this operation." + } else { + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + // Execute the actual regex search operation + const results = await regexSearchFiles( + config.cwd, + absolutePath, + regex, + filePattern, + config.services.clineIgnoreController, + ) + + return results + } +} diff --git a/src/core/task/tools/handlers/SummarizeTaskHandler.ts b/src/core/task/tools/handlers/SummarizeTaskHandler.ts new file mode 100644 index 00000000..2d15833a --- /dev/null +++ b/src/core/task/tools/handlers/SummarizeTaskHandler.ts @@ -0,0 +1,103 @@ +import type { ToolUse } from "@core/assistant-message" +import { continuationPrompt } from "@core/prompts/contextManagement" +import { formatResponse } from "@core/prompts/responses" +import { ensureTaskDirectoryExists } from "@core/storage/disk" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { ClineSayTool } from "@shared/ExtensionMessage" +import type { ToolResponse } from "../../index" +import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class SummarizeTaskHandler implements IToolHandler, IPartialBlockHandler { + readonly name = "summarize_task" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name}]` + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + try { + const context: string | undefined = block.params.context + + // Validate required parameters + if (!context) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: context" + } + + config.taskState.consecutiveMistakeCount = 0 + + // Show completed summary in tool UI + const completeMessage = JSON.stringify({ + tool: "summarizeTask", + content: context, + } satisfies ClineSayTool) + + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + + // Use the continuationPrompt to format the tool result + const toolResult = formatResponse.toolResult(continuationPrompt(context)) + + // Handle context management + const apiConversationHistory = config.messageState.getApiConversationHistory() + const keepStrategy = "none" + + // clear the context history at this point in time. note that this will not include the assistant message + // for summarizing, which we will need to delete later + config.taskState.conversationHistoryDeletedRange = config.services.contextManager.getNextTruncationRange( + apiConversationHistory, + config.taskState.conversationHistoryDeletedRange, + keepStrategy, + ) + await config.messageState.saveClineMessagesAndUpdateHistory() + await config.services.contextManager.triggerApplyStandardContextTruncationNoticeChange( + Date.now(), + await ensureTaskDirectoryExists(config.context, config.taskId), + apiConversationHistory, + ) + + // Set summarizing state + config.taskState.currentlySummarizing = true + + // Capture telemetry after main business logic is complete + const telemetryData = config.services.contextManager.getContextTelemetryData( + config.messageState.getClineMessages(), + config.api, + config.taskState.lastAutoCompactTriggerIndex, + ) + + if (telemetryData) { + telemetryService.captureSummarizeTask( + config.ulid, + config.api.getModel().id, + telemetryData.tokensUsed, + telemetryData.maxContextWindow, + ) + } + + return toolResult + } catch (error) { + return `Error summarizing context window: ${(error as Error).message}` + } + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const context = block.params.context || "" + + // Show streaming summary generation in tool UI + const partialMessage = JSON.stringify({ + tool: "summarizeTask", + content: uiHelpers.removeClosingTag(block, "context", context), + } satisfies ClineSayTool) + + await uiHelpers.say("tool", partialMessage, undefined, undefined, block.partial) + } +} diff --git a/src/core/task/tools/handlers/UseMcpToolHandler.ts b/src/core/task/tools/handlers/UseMcpToolHandler.ts new file mode 100644 index 00000000..94ef4087 --- /dev/null +++ b/src/core/task/tools/handlers/UseMcpToolHandler.ts @@ -0,0 +1,193 @@ +import type { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { ClineAsk, ClineAskUseMcpServer } from "@shared/ExtensionMessage" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class UseMcpToolHandler implements IFullyManagedTool { + readonly name = "use_mcp_tool" + + constructor() {} + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.server_name}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const server_name = block.params.server_name + const tool_name = block.params.tool_name + const mcp_arguments = block.params.arguments + + const partialMessage = JSON.stringify({ + type: "use_mcp_tool", + serverName: uiHelpers.removeClosingTag(block, "server_name", server_name), + toolName: uiHelpers.removeClosingTag(block, "tool_name", tool_name), + arguments: uiHelpers.removeClosingTag(block, "arguments", mcp_arguments), + } satisfies ClineAskUseMcpServer) + + // Check if tool should be auto-approved using MCP-specific logic + const config = uiHelpers.getConfig() + const shouldAutoApprove = this.shouldAutoApproveMcpTool(config, server_name || "", tool_name || "") + + if (shouldAutoApprove) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") + await uiHelpers.say("use_mcp_server" as any, partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") + await uiHelpers.ask("use_mcp_server" as ClineAsk, partialMessage, block.partial).catch(() => {}) + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const server_name: string | undefined = block.params.server_name + const tool_name: string | undefined = block.params.tool_name + const mcp_arguments: string | undefined = block.params.arguments + + // Validate required parameters + if (!server_name) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: server_name" + } + + if (!tool_name) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: tool_name" + } + + // Parse and validate arguments if provided + let parsedArguments: Record | undefined + if (mcp_arguments) { + try { + parsedArguments = JSON.parse(mcp_arguments) + } catch (_error) { + config.taskState.consecutiveMistakeCount++ + return `Error: Invalid JSON arguments for ${tool_name} on ${server_name}` + } + } + + config.taskState.consecutiveMistakeCount = 0 + + // Handle approval flow + const completeMessage = JSON.stringify({ + type: "use_mcp_tool", + serverName: server_name, + toolName: tool_name, + uri: undefined, + arguments: mcp_arguments, + }) + + const shouldAutoApprove = this.shouldAutoApproveMcpTool(config, server_name, tool_name) + + if (shouldAutoApprove) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") + await config.callbacks.say("use_mcp_server", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + } else { + // Manual approval flow + const notificationMessage = `Cline wants to use ${tool_name || "unknown tool"} on ${server_name || "unknown server"}` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") + + // Ask for approval + const { response } = await config.callbacks.ask("use_mcp_server", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return "The user denied this operation." + } else { + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + // Show MCP request started message + await config.callbacks.say("mcp_server_request_started") + + try { + // Check for any pending notifications before the tool call + const notificationsBefore = config.services.mcpHub.getPendingNotifications() + for (const notification of notificationsBefore) { + await config.callbacks.say("mcp_notification", `[${notification.serverName}] ${notification.message}`) + } + + // Execute the MCP tool + const toolResult = await config.services.mcpHub.callTool(server_name, tool_name, parsedArguments, config.ulid) + + // Check for any pending notifications after the tool call + const notificationsAfter = config.services.mcpHub.getPendingNotifications() + for (const notification of notificationsAfter) { + await config.callbacks.say("mcp_notification", `[${notification.serverName}] ${notification.message}`) + } + + // Process tool result + const toolResultImages = + toolResult?.content + .filter((item: any) => item.type === "image") + .map((item: any) => `data:${item.mimeType};base64,${item.data}`) || [] + + let toolResultText = + (toolResult?.isError ? "Error:\n" : "") + + toolResult?.content + .map((item: any) => { + if (item.type === "text") { + return item.text + } + if (item.type === "resource") { + const { blob: _blob, ...rest } = item.resource + return JSON.stringify(rest, null, 2) + } + return "" + }) + .filter(Boolean) + .join("\n\n") || "(No response)" + + // Display result to user + const toolResultToDisplay = toolResultText + toolResultImages?.map((image: any) => `\n\n${image}`).join("") + await config.callbacks.say("mcp_server_response", toolResultToDisplay) + + // Handle model image support + const supportsImages = config.api.getModel().info.supportsImages ?? false + if (toolResultImages.length > 0 && !supportsImages) { + toolResultText += `\n\n[${toolResultImages.length} images were provided in the response, and while they are displayed to the user, you do not have the ability to view them.]` + } + + // Return formatted result (only pass images if model supports them) + return formatResponse.toolResult(toolResultText, supportsImages ? toolResultImages : undefined) + } catch (error) { + return `Error executing MCP tool: ${(error as Error)?.message}` + } + } + + /** + * Determine if MCP tool should be auto-approved (moved from ToolApprovalManager) + */ + private shouldAutoApproveMcpTool(config: TaskConfig, server_name: string, tool_name: string): boolean { + // Check if this specific tool is auto-approved on the server + const isToolAutoApproved = config.services.mcpHub.connections + ?.find((conn: any) => conn.server.name === server_name) + ?.server.tools?.find((tool: any) => tool.name === tool_name)?.autoApprove + + return config.autoApprovalSettings.enabled && (isToolAutoApproved ?? false) + } +} diff --git a/src/core/task/tools/handlers/WebFetchToolHandler.ts b/src/core/task/tools/handlers/WebFetchToolHandler.ts new file mode 100644 index 00000000..11182f70 --- /dev/null +++ b/src/core/task/tools/handlers/WebFetchToolHandler.ts @@ -0,0 +1,111 @@ +import { UrlContentFetcher } from "@services/browser/UrlContentFetcher" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { ClineAsk, ClineSayTool } from "@shared/ExtensionMessage" +import { ToolUse, ToolUseName } from "../../../assistant-message" +import { formatResponse } from "../../../prompts/responses" +import { ToolResponse } from "../.." +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" + +export class WebFetchToolHandler implements IFullyManagedTool { + name = "web_fetch" + supportedTools: ToolUseName[] = ["web_fetch"] + + getDescription(block: ToolUse): string { + return `[${block.name} for '${block.params.url}']` + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const url = block.params.url || "" + const sharedMessageProps: ClineSayTool = { + tool: "webFetch", + path: uiHelpers.removeClosingTag(block, "url", url), + content: `Fetching URL: ${uiHelpers.removeClosingTag(block, "url", url)}`, + operationIsLocatedInWorkspace: false, // web_fetch is always external + } + + const partialMessage = JSON.stringify(sharedMessageProps) + + // For partial blocks, we'll let the ToolExecutor handle auto-approval logic + // Just stream the UI update for now + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool") + await uiHelpers.ask("tool" as ClineAsk, partialMessage, block.partial).catch(() => {}) + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, don't execute yet + if (block.partial) { + return "" + } + + try { + const url: string | undefined = block.params.url + + // Validate required parameter + if (!url) { + config.taskState.consecutiveMistakeCount++ + return await config.callbacks.sayAndCreateMissingParamError("web_fetch", "url") + } + config.taskState.consecutiveMistakeCount = 0 + + // Create message for approval + const sharedMessageProps: ClineSayTool = { + tool: "webFetch", + path: url, + content: `Fetching URL: ${url}`, + operationIsLocatedInWorkspace: false, + } + const completeMessage = JSON.stringify(sharedMessageProps) + + // Check auto-approval (web_fetch uses simple boolean, not array) + const autoApprove = config.autoApprovalSettings.enabled && config.autoApprovalSettings.actions.useBrowser + + if (autoApprove) { + // Auto-approve flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "tool") + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + telemetryService.captureToolUsage(config.ulid, "web_fetch", config.api.getModel().id, true, true) + } else { + // Manual approval flow + showNotificationForApprovalIfAutoApprovalEnabled( + `Cline wants to fetch content from ${url}`, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "tool") + + const { response } = await config.callbacks.ask("tool", completeMessage, false) + if (response !== "yesButtonClicked") { + telemetryService.captureToolUsage(config.ulid, "web_fetch", config.api.getModel().id, false, false) + return "The user denied this operation." + } + telemetryService.captureToolUsage(config.ulid, "web_fetch", config.api.getModel().id, false, true) + } + + // Execute the actual fetch + const urlContentFetcher = config.services?.urlContentFetcher as UrlContentFetcher + + await urlContentFetcher.launchBrowser() + try { + // Fetch Markdown content + const markdownContent = await urlContentFetcher.urlToMarkdown(url) + + // TODO: Implement secondary AI call to process markdownContent with prompt + // For now, returning markdown directly. + // This will be a significant sub-task. + // Placeholder for processed summary: + const processedSummary = `Fetched Markdown for ${url}:\n\n${markdownContent}` + + return formatResponse.toolResult(processedSummary) + } finally { + // Ensure browser is closed even on error + await urlContentFetcher.closeBrowser() + } + } catch (error) { + return `Error fetching web content: ${(error as Error).message}` + } + } +} diff --git a/src/core/task/tools/handlers/WriteToFileToolHandler.ts b/src/core/task/tools/handlers/WriteToFileToolHandler.ts new file mode 100644 index 00000000..f4ec3acb --- /dev/null +++ b/src/core/task/tools/handlers/WriteToFileToolHandler.ts @@ -0,0 +1,464 @@ +import { setTimeout as setTimeoutPromise } from "node:timers/promises" +import type { ToolUse } from "@core/assistant-message" +import { constructNewFileContent } from "@core/assistant-message/diff" +import { formatResponse } from "@core/prompts/responses" +import { processFilesIntoText } from "@integrations/misc/extract-text" +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import { ClineSayTool } from "@shared/ExtensionMessage" +import { fileExistsAtPath } from "@utils/fs" +import { getReadablePath, isLocatedInWorkspace } from "@utils/path" +import { fixModelHtmlEscaping, removeInvalidChars } from "@utils/string" +import * as path from "path" +import type { ToolResponse } from "../../index" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import type { IFullyManagedTool } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" +import type { TaskConfig } from "../types/TaskConfig" +import type { StronglyTypedUIHelpers } from "../types/UIHelpers" +import { ToolDisplayUtils } from "../utils/ToolDisplayUtils" +import { ToolResultUtils } from "../utils/ToolResultUtils" + +export class WriteToFileToolHandler implements IFullyManagedTool { + readonly name = "write_to_file" // This handler supports write_to_file, replace_in_file, and new_rule + + constructor(private validator: ToolValidator) {} + + getDescription(block: ToolUse): string { + switch (block.name) { + case "write_to_file": + return `[${block.name} for '${block.params.path}']` + case "replace_in_file": + return `[${block.name} for '${block.params.path}']` + case "new_rule": + return `[${block.name} for '${block.params.path}']` + default: + return `[${block.name} for '${block.params.path}']` + } + } + + async handlePartialBlock(block: ToolUse, uiHelpers: StronglyTypedUIHelpers): Promise { + const relPath = block.params.path + const content = block.params.content // for write_to_file + let diff = block.params.diff // for replace_in_file + + // Early return if we don't have enough data yet + if (!relPath || (!content && !diff)) { + // Wait until we have the path and either content or diff + return + } + + // Get config access for services + const config = uiHelpers.getConfig() + + // Check clineignore access first + const accessValidation = this.validator.checkClineIgnorePath(relPath) + if (!accessValidation.ok) { + // Show error and return early (full original behavior) + await uiHelpers.say("clineignore_error", relPath) + + // Push tool result and save checkpoint using existing utilities + const errorResponse = formatResponse.toolError(formatResponse.clineIgnoreError(relPath)) + ToolResultUtils.pushToolResult( + errorResponse, + block, + config.taskState.userMessageContent, + ToolDisplayUtils.getToolDescription, + config.api, + () => { + config.taskState.didAlreadyUseTool = true + }, + config.coordinator, + ) + await config.callbacks.saveCheckpoint() + return + } + + // Check if file exists to determine the correct UI message + let fileExists: boolean + if (config.services.diffViewProvider.editType !== undefined) { + fileExists = config.services.diffViewProvider.editType === "modify" + } else { + const absolutePath = path.resolve(config.cwd, relPath) + fileExists = await fileExistsAtPath(absolutePath) + config.services.diffViewProvider.editType = fileExists ? "modify" : "create" + } + + // Create and show partial UI message + const sharedMessageProps: ClineSayTool = { + tool: fileExists ? "editedExistingFile" : "newFileCreated", + path: getReadablePath(config.cwd, uiHelpers.removeClosingTag(block, "path", relPath)), + content: uiHelpers.removeClosingTag(block, block.name === "replace_in_file" ? "diff" : "content", content || diff), + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), + } + + const partialMessage = JSON.stringify(sharedMessageProps) + + // Handle auto-approval vs manual approval for partial + if (await uiHelpers.shouldAutoApproveToolWithPath(block.name, relPath)) { + await uiHelpers.removeLastPartialMessageIfExistsWithType("ask", "tool") + await uiHelpers.say("tool", partialMessage, undefined, undefined, block.partial) + } else { + await uiHelpers.removeLastPartialMessageIfExistsWithType("say", "tool") + await uiHelpers.ask("tool", partialMessage, block.partial).catch(() => {}) + } + + // CRITICAL: Add the missing real-time diff view streaming logic from original code + try { + // Construct newContent from diff or content + let newContent: string = "" + + if (diff) { + // Handle replace_in_file with diff construction + if (!config.api.getModel().id.includes("claude")) { + // deepseek models tend to use unescaped html entities in diffs + diff = fixModelHtmlEscaping(diff) + diff = removeInvalidChars(diff) + } + + // Open the editor if not done already - CRITICAL for real-time streaming + if (!config.services.diffViewProvider.isEditing) { + await config.services.diffViewProvider.open(relPath) + } + + try { + newContent = await constructNewFileContent( + diff, + config.services.diffViewProvider.originalContent || "", + !block.partial, // Pass the partial flag correctly + ) + } catch (error) { + // Full original behavior - comprehensive error handling even for partial blocks + await config.callbacks.say("diff_error", relPath) + + // Extract error type from error message if possible + const errorType = + error instanceof Error && error.message.includes("does not match anything") + ? "search_not_found" + : "other_diff_error" + + // Add telemetry for diff edit failure + telemetryService.captureDiffEditFailure(config.ulid, config.api.getModel().id, errorType) + + // Push tool result with detailed error using existing utilities + const errorResponse = formatResponse.toolError( + `${(error as Error)?.message}\n\n` + + formatResponse.diffError(relPath, config.services.diffViewProvider.originalContent), + ) + ToolResultUtils.pushToolResult( + errorResponse, + block, + config.taskState.userMessageContent, + ToolDisplayUtils.getToolDescription, + config.api, + () => { + config.taskState.didAlreadyUseTool = true + }, + config.coordinator, + ) + + // Revert changes and reset diff view + await config.services.diffViewProvider.revertChanges() + await config.services.diffViewProvider.reset() + + // Save checkpoint after error + await config.callbacks.saveCheckpoint() + return + } + } else if (content) { + // Handle write_to_file with direct content + newContent = content + + // Pre-processing newContent for cases where weaker models might add artifacts + if (newContent.startsWith("```")) { + newContent = newContent.split("\n").slice(1).join("\n").trim() + } + if (newContent.endsWith("```")) { + newContent = newContent.split("\n").slice(0, -1).join("\n").trim() + } + + if (!config.api.getModel().id.includes("claude")) { + newContent = fixModelHtmlEscaping(newContent) + newContent = removeInvalidChars(newContent) + } + } + + // CRITICAL: Open editor and stream content in real-time (from original code) + if (!config.services.diffViewProvider.isEditing) { + // Open the editor and prepare to stream content in + await config.services.diffViewProvider.open(relPath) + } + // Editor is open, stream content in real-time (false = don't finalize yet) + await config.services.diffViewProvider.update(newContent, false) + } catch (error) { + // For partial blocks, we'll silently handle errors and wait for more content + // The complete block handler will handle actual errors + if (!block.partial) { + console.error("Error in partial write tool block:", error) + } + } + } + + async execute(config: TaskConfig, block: ToolUse): Promise { + // For partial blocks, return empty string to let coordinator handle UI + if (block.partial) { + return "" + } + + const relPath: string | undefined = block.params.path + const content: string | undefined = block.params.content // for write_to_file and new_rule + let diff: string | undefined = block.params.diff // for replace_in_file + + // Validate required parameters based on tool type + if (!relPath) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: path" + } + + if (block.name === "replace_in_file" && !diff) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: diff" + } + + if ((block.name === "write_to_file" || block.name === "new_rule") && !content) { + config.taskState.consecutiveMistakeCount++ + return "Missing required parameter: content" + } + + // Check clineignore access + const accessValidation = this.validator.checkClineIgnorePath(relPath) + if (!accessValidation.ok) { + await config.callbacks.say("clineignore_error", relPath) + return formatResponse.toolError(formatResponse.clineIgnoreError(relPath)) + } + + config.taskState.consecutiveMistakeCount = 0 + + // Check if file exists + const absolutePath = path.resolve(config.cwd, relPath) + let fileExists: boolean + if (config.services.diffViewProvider.editType !== undefined) { + fileExists = config.services.diffViewProvider.editType === "modify" + } else { + fileExists = await fileExistsAtPath(absolutePath) + config.services.diffViewProvider.editType = fileExists ? "modify" : "create" + } + + // Handle approval flow + const sharedMessageProps: ClineSayTool = { + tool: fileExists ? "editedExistingFile" : "newFileCreated", + path: getReadablePath(config.cwd, relPath), + content: diff || content, + operationIsLocatedInWorkspace: await isLocatedInWorkspace(relPath), + } + + const completeMessage = JSON.stringify(sharedMessageProps) + + if (await config.callbacks.shouldAutoApproveToolWithPath(block.name, relPath)) { + // Auto-approval flow + await config.callbacks.removeLastPartialMessageIfExistsWithType("ask", "tool") + await config.callbacks.say("tool", completeMessage, undefined, undefined, false) + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Capture telemetry + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, true, true) + + // Add diagnostic delay + await setTimeoutPromise(3_500) + } else { + // Manual approval flow with detailed feedback handling + const notificationMessage = `Cline wants to ${fileExists ? "edit" : "create"} ${path.basename(relPath)}` + + // Show notification + showNotificationForApprovalIfAutoApprovalEnabled( + notificationMessage, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + + await config.callbacks.removeLastPartialMessageIfExistsWithType("say", "tool") + + // Ask for approval with full feedback handling + const { response, text, images, files } = await config.callbacks.ask("tool", completeMessage, false) + + if (response !== "yesButtonClicked") { + // Handle rejection with detailed messages + const fileDeniedNote = fileExists + ? "The file was not updated, and maintains its original contents." + : "The file was not created." + + // Process user feedback if provided (with file content processing) + if (text || (images && images.length > 0) || (files && files.length > 0)) { + let fileContentString = "" + if (files && files.length > 0) { + fileContentString = await processFilesIntoText(files) + } + + // Push additional tool feedback using existing utilities + ToolResultUtils.pushAdditionalToolFeedback( + config.taskState.userMessageContent, + text, + images, + fileContentString, + ) + await config.callbacks.say("user_feedback", text, images, files) + await config.callbacks.saveCheckpoint() + } + + // Clean up the diff view when operation is rejected + await config.services.diffViewProvider.revertChanges() + await config.services.diffViewProvider.reset() + + config.taskState.didRejectTool = true + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, false) + return `The user denied this operation. ${fileDeniedNote}` + } else { + // Handle approval feedback if provided (with file content processing) + if (text || (images && images.length > 0) || (files && files.length > 0)) { + let fileContentString = "" + if (files && files.length > 0) { + fileContentString = await processFilesIntoText(files) + } + + // Push additional tool feedback using existing utilities + ToolResultUtils.pushAdditionalToolFeedback( + config.taskState.userMessageContent, + text, + images, + fileContentString, + ) + await config.callbacks.say("user_feedback", text, images, files) + await config.callbacks.saveCheckpoint() + } + + telemetryService.captureToolUsage(config.ulid, block.name, config.api.getModel().id, false, true) + } + } + + try { + // Construct newContent from diff or content + let newContent: string = "" + + if (diff) { + // Handle replace_in_file with diff construction + if (!config.api.getModel().id.includes("claude")) { + // deepseek models tend to use unescaped html entities in diffs + diff = fixModelHtmlEscaping(diff) + diff = removeInvalidChars(diff) + } + + // Open the editor if not done already + if (!config.services.diffViewProvider.isEditing) { + await config.services.diffViewProvider.open(relPath) + } + + try { + newContent = await constructNewFileContent( + diff, + config.services.diffViewProvider.originalContent || "", + true, // isFinal = true since we're not streaming + ) + } catch (error) { + // Show diff error UI message (from original implementation) + await config.callbacks.say("diff_error", relPath) + + // Extract error type from error message if possible + const errorType = + error instanceof Error && error.message.includes("does not match anything") + ? "search_not_found" + : "other_diff_error" + + // Add telemetry for diff edit failure + telemetryService.captureDiffEditFailure(config.ulid, config.api.getModel().id, errorType) + + await config.services.diffViewProvider.revertChanges() + await config.services.diffViewProvider.reset() + + // Save checkpoint after error (from original implementation) + await config.callbacks.saveCheckpoint() + + // Return detailed error with original content for context + return formatResponse.toolError( + `${(error as Error)?.message}\n\n` + + formatResponse.diffError(relPath, config.services.diffViewProvider.originalContent), + ) + } + } else if (content) { + // Handle write_to_file and new_rule with direct content + newContent = content + + // Pre-processing newContent for cases where weaker models might add artifacts + if (newContent.startsWith("```")) { + newContent = newContent.split("\n").slice(1).join("\n").trim() + } + if (newContent.endsWith("```")) { + newContent = newContent.split("\n").slice(0, -1).join("\n").trim() + } + + if (!config.api.getModel().id.includes("claude")) { + newContent = fixModelHtmlEscaping(newContent) + newContent = removeInvalidChars(newContent) + } + } + + // Remove trailing newlines + newContent = newContent.trimEnd() + + // CRITICAL: Handle the UI animation logic from original code + // "it's important to note how this function works, you can't make the assumption that the block.partial conditional will always be called since it may immediately get complete, non-partial data. So this part of the logic will always be called. + // in other words, you must always repeat the block.partial logic here" + if (!config.services.diffViewProvider.isEditing) { + // Show GUI message before showing edit animation + const partialMessage = JSON.stringify(sharedMessageProps) + await config.callbacks.ask("tool", partialMessage, true).catch(() => {}) // sending true for partial even though it's not a partial, this shows the edit row before the content is streamed into the editor + await config.services.diffViewProvider.open(relPath) + } + + // Update the diff view with the new content + await config.services.diffViewProvider.update(newContent, true) + await setTimeoutPromise(300) // wait for diff view to update + await config.services.diffViewProvider.scrollToFirstDiff() + + // Mark the file as edited by Cline + config.services.fileContextTracker.markFileAsEditedByCline(relPath) + + // Save the changes and get the result + const { newProblemsMessage, userEdits, autoFormattingEdits, finalContent } = + await config.services.diffViewProvider.saveChanges() + + config.taskState.didEditFile = true + + // Track file edit operation + await config.services.fileContextTracker.trackFileContext(relPath, "cline_edited") + + // Reset the diff view + await config.services.diffViewProvider.reset() + + // Handle user edits if any + if (userEdits) { + await config.services.fileContextTracker.trackFileContext(relPath, "user_edited") + await config.callbacks.say( + "user_feedback_diff", + JSON.stringify({ + tool: fileExists ? "editedExistingFile" : "newFileCreated", + path: relPath, + diff: userEdits, + }), + ) + return formatResponse.fileEditWithUserChanges( + relPath, + userEdits, + autoFormattingEdits, + finalContent, + newProblemsMessage, + ) + } else { + return formatResponse.fileEditWithoutUserChanges(relPath, autoFormattingEdits, finalContent, newProblemsMessage) + } + } catch (error) { + // Reset diff view on error + await config.services.diffViewProvider.revertChanges() + await config.services.diffViewProvider.reset() + return `Error: ${(error as Error)?.message}` + } + } +} diff --git a/src/core/task/tools/types/TaskConfig.ts b/src/core/task/tools/types/TaskConfig.ts new file mode 100644 index 00000000..890b53f0 --- /dev/null +++ b/src/core/task/tools/types/TaskConfig.ts @@ -0,0 +1,147 @@ +import type { ApiHandler } from "@core/api" +import type { FileContextTracker } from "@core/context/context-tracking/FileContextTracker" +import type { ClineIgnoreController } from "@core/ignore/ClineIgnoreController" +import type { DiffViewProvider } from "@integrations/editor/DiffViewProvider" +import type { BrowserSession } from "@services/browser/BrowserSession" +import type { UrlContentFetcher } from "@services/browser/UrlContentFetcher" +import type { McpHub } from "@services/mcp/McpHub" +import type { AutoApprovalSettings } from "@shared/AutoApprovalSettings" +import type { BrowserSettings } from "@shared/BrowserSettings" +import type { ClineAsk, ClineSay } from "@shared/ExtensionMessage" +import type { FocusChainSettings } from "@shared/FocusChainSettings" +import type { Mode } from "@shared/storage/types" +import type { ClineAskResponse } from "@shared/WebviewMessage" +import * as vscode from "vscode" +import type { ToolUseName } from "../../../assistant-message" +import type { ContextManager } from "../../../context/context-management/ContextManager" +import type { StateManager } from "../../../storage/StateManager" +import type { MessageStateHandler } from "../../message-state" +import type { TaskState } from "../../TaskState" +import type { AutoApprove } from "../../tools/autoApprove" +import type { ToolExecutorCoordinator } from "../ToolExecutorCoordinator" +import { TASK_CALLBACKS_KEYS, TASK_CONFIG_KEYS, TASK_SERVICES_KEYS } from "../utils/ToolConstants" + +/** + * Strongly-typed configuration object passed to tool handlers + */ +export interface TaskConfig { + // Core identifiers + taskId: string + ulid: string + cwd: string + mode: Mode + strictPlanModeEnabled: boolean + context: vscode.ExtensionContext + + // State management + taskState: TaskState + messageState: MessageStateHandler + + // API and services + api: ApiHandler + services: TaskServices + + // Settings + autoApprovalSettings: AutoApprovalSettings + autoApprover: AutoApprove + browserSettings: BrowserSettings + focusChainSettings: FocusChainSettings + + // Callbacks (strongly typed) + callbacks: TaskCallbacks + + // Tool coordination + coordinator: ToolExecutorCoordinator +} + +/** + * All services available to tool handlers + */ +export interface TaskServices { + mcpHub: McpHub + browserSession: BrowserSession + urlContentFetcher: UrlContentFetcher + diffViewProvider: DiffViewProvider + fileContextTracker: FileContextTracker + clineIgnoreController: ClineIgnoreController + contextManager: ContextManager + stateManager: StateManager +} + +/** + * All callback functions available to tool handlers + */ +export interface TaskCallbacks { + say: (type: ClineSay, text?: string, images?: string[], files?: string[], partial?: boolean) => Promise + + ask: ( + type: ClineAsk, + text?: string, + partial?: boolean, + ) => Promise<{ + response: ClineAskResponse + text?: string + images?: string[] + files?: string[] + }> + + saveCheckpoint: (isAttemptCompletionMessage?: boolean, completionMessageTs?: number) => Promise + + sayAndCreateMissingParamError: (toolName: ToolUseName, paramName: string, relPath?: string) => Promise + + removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise + + executeCommandTool: (command: string) => Promise<[boolean, any]> + + doesLatestTaskCompletionHaveNewChanges: () => Promise + + updateFCListFromToolResponse: (taskProgress: string | undefined) => Promise + + shouldAutoApproveToolWithPath: (toolName: ToolUseName, path?: string) => Promise + + // Additional callbacks for task management + postStateToWebview: () => Promise + reinitExistingTaskFromId: (taskId: string) => Promise + cancelTask: () => Promise + updateTaskHistory: (update: any) => Promise +} + +/** + * Runtime validation function to ensure config has all required properties + * Automatically derives expected keys from the interface definitions + */ +export function validateTaskConfig(config: any): asserts config is TaskConfig { + if (!config) { + throw new Error("TaskConfig is null or undefined") + } + + // Validate all expected keys exist + for (const key of TASK_CONFIG_KEYS) { + if (!(key in config)) { + throw new Error(`Missing ${key} in TaskConfig`) + } + } + + // Special validation for boolean type + if (typeof config.strictPlanModeEnabled !== "boolean") { + throw new Error("strictPlanModeEnabled must be a boolean in TaskConfig") + } + + // Validate services object + if (config.services) { + for (const key of TASK_SERVICES_KEYS) { + if (!(key in config.services)) { + throw new Error(`Missing services.${key} in TaskConfig`) + } + } + } + + // Validate callbacks object + if (config.callbacks) { + for (const key of TASK_CALLBACKS_KEYS) { + if (typeof config.callbacks[key] !== "function") { + throw new Error(`Missing or invalid callbacks.${key} in TaskConfig (must be a function)`) + } + } + } +} diff --git a/src/core/task/tools/types/UIHelpers.ts b/src/core/task/tools/types/UIHelpers.ts new file mode 100644 index 00000000..a99f65f7 --- /dev/null +++ b/src/core/task/tools/types/UIHelpers.ts @@ -0,0 +1,71 @@ +import { telemetryService } from "@services/posthog/PostHogClientProvider" +import type { ClineAsk, ClineSay } from "@shared/ExtensionMessage" +import type { ClineAskResponse } from "@shared/WebviewMessage" +import type { ToolParamName, ToolUse, ToolUseName } from "../../../assistant-message" +import { showNotificationForApprovalIfAutoApprovalEnabled } from "../../utils" +import { removeClosingTag } from "../utils/ToolConstants" +import type { TaskConfig } from "./TaskConfig" + +/** + * Strongly-typed UI helper functions for tool handlers + */ +export interface StronglyTypedUIHelpers { + // Core UI methods + say: (type: ClineSay, text?: string, images?: string[], files?: string[], partial?: boolean) => Promise + + ask: ( + type: ClineAsk, + text?: string, + partial?: boolean, + ) => Promise<{ + response: ClineAskResponse + text?: string + images?: string[] + files?: string[] + }> + + // Utility methods + removeClosingTag: (block: ToolUse, tag: ToolParamName, text?: string) => string + removeLastPartialMessageIfExistsWithType: (type: "ask" | "say", askOrSay: ClineAsk | ClineSay) => Promise + + // Approval methods + shouldAutoApproveTool: (toolName: ToolUseName) => boolean | [boolean, boolean] + shouldAutoApproveToolWithPath: (toolName: ToolUseName, path?: string) => Promise + askApproval: (messageType: ClineAsk, message: string) => Promise + + // Telemetry and notifications + captureTelemetry: (toolName: ToolUseName, autoApproved: boolean, approved: boolean) => void + showNotificationIfEnabled: (message: string) => void + + // Config access - returns the proper typed config + getConfig: () => TaskConfig +} + +/** + * Creates strongly-typed UI helpers from a TaskConfig + */ +export function createUIHelpers(config: TaskConfig): StronglyTypedUIHelpers { + return { + say: config.callbacks.say, + ask: config.callbacks.ask, + removeClosingTag: (block: ToolUse, tag: ToolParamName, text?: string) => removeClosingTag(block, tag, text), + removeLastPartialMessageIfExistsWithType: config.callbacks.removeLastPartialMessageIfExistsWithType, + shouldAutoApproveTool: (toolName: ToolUseName) => config.autoApprover.shouldAutoApproveTool(toolName), + shouldAutoApproveToolWithPath: config.callbacks.shouldAutoApproveToolWithPath, + askApproval: async (messageType: ClineAsk, message: string): Promise => { + const { response } = await config.callbacks.ask(messageType, message, false) + return response === "yesButtonClicked" + }, + captureTelemetry: (toolName: ToolUseName, autoApproved: boolean, approved: boolean) => { + telemetryService.captureToolUsage(config.ulid, toolName, config.api.getModel().id, autoApproved, approved) + }, + showNotificationIfEnabled: (message: string) => { + showNotificationForApprovalIfAutoApprovalEnabled( + message, + config.autoApprovalSettings.enabled, + config.autoApprovalSettings.enableNotifications, + ) + }, + getConfig: () => config, + } +} diff --git a/src/core/task/tools/utils/ToolConstants.ts b/src/core/task/tools/utils/ToolConstants.ts new file mode 100644 index 00000000..27b86dcb --- /dev/null +++ b/src/core/task/tools/utils/ToolConstants.ts @@ -0,0 +1,127 @@ +import type { ToolParamName, ToolUse } from "@core/assistant-message" + +/** + * Shared constants for tool validation and configuration + * This file serves as a single source of truth for tool-related constants + */ + +/** + * Expected keys for TaskConfig interface validation + * Keep this in sync with the TaskConfig interface + */ +export const TASK_CONFIG_KEYS = [ + "taskId", + "ulid", + "cwd", + "mode", + "strictPlanModeEnabled", + "context", + "taskState", + "messageState", + "api", + "services", + "autoApprovalSettings", + "autoApprover", + "browserSettings", + "focusChainSettings", + "callbacks", + "coordinator", +] as const + +/** + * Expected keys for TaskServices interface validation + * Keep this in sync with the TaskServices interface + */ +export const TASK_SERVICES_KEYS = [ + "mcpHub", + "browserSession", + "urlContentFetcher", + "diffViewProvider", + "fileContextTracker", + "clineIgnoreController", + "contextManager", + "stateManager", +] as const + +/** + * Expected keys for TaskCallbacks interface validation + * Keep this in sync with the TaskCallbacks interface + */ +export const TASK_CALLBACKS_KEYS = [ + "say", + "ask", + "saveCheckpoint", + "sayAndCreateMissingParamError", + "removeLastPartialMessageIfExistsWithType", + "executeCommandTool", + "doesLatestTaskCompletionHaveNewChanges", + "updateFCListFromToolResponse", + "shouldAutoApproveToolWithPath", + "postStateToWebview", + "reinitExistingTaskFromId", + "cancelTask", + "updateTaskHistory", +] as const + +/** + * Tools that require a path parameter + * Used for validation in ToolErrorHandler + */ +export const PATH_REQUIRED_TOOLS = [ + "read_file", + "write_to_file", + "replace_in_file", + "new_rule", + "list_files", + "list_code_definition_names", + "search_files", +] as const + +/** + * Browser action types for validation + */ +export const BROWSER_ACTIONS = ["launch", "click", "type", "scroll_down", "scroll_up", "close"] as const + +/** + * Common validation error patterns + */ +export const VALIDATION_ERROR_PATTERNS = ["Missing required parameter", "blocked by .clineignore"] as const + +/** + * Type helpers for better type safety + */ +export type TaskConfigKey = (typeof TASK_CONFIG_KEYS)[number] +export type TaskServicesKey = (typeof TASK_SERVICES_KEYS)[number] +export type TaskCallbacksKey = (typeof TASK_CALLBACKS_KEYS)[number] +export type PathRequiredTool = (typeof PATH_REQUIRED_TOOLS)[number] +export type BrowserAction = (typeof BROWSER_ACTIONS)[number] + +/** + * Shared utility functions for tools + */ + +/** + * Remove partial closing tag from tool parameter text + * If block is partial, remove partial closing tag so it's not presented to user + * + * This regex dynamically constructs a pattern to match the closing tag: + * - Optionally matches whitespace before the tag + * - Matches '<' or ' `(?:${char})?`) + .join("")}$`, + "g", + ) + return text.replace(tagRegex, "") +} diff --git a/src/core/task/tools/utils/ToolDisplayUtils.ts b/src/core/task/tools/utils/ToolDisplayUtils.ts new file mode 100644 index 00000000..dcc81c50 --- /dev/null +++ b/src/core/task/tools/utils/ToolDisplayUtils.ts @@ -0,0 +1,33 @@ +import { ToolParamName, ToolUse } from "@core/assistant-message" +import type { ToolExecutorCoordinator } from "../ToolExecutorCoordinator" +import { removeClosingTag } from "./ToolConstants" + +/** + * Utility functions for tool display and formatting + */ +export class ToolDisplayUtils { + /** + * Generate a descriptive string for a tool execution + * @param block - The tool use block + * @param coordinator - Optional tool coordinator to get description from tool handler + */ + static getToolDescription(block: ToolUse, coordinator?: ToolExecutorCoordinator): string { + // Try to get description from the tool handler first + if (coordinator) { + const handler = coordinator.getHandler(block.name) + if (handler) { + return handler.getDescription(block) + } + } + + return `[${block.name}]` + } + + /** + * Remove partial closing tag from tool parameter text + * If block is partial, remove partial closing tag so it's not presented to user + */ + static removeClosingTag(block: ToolUse, tag: ToolParamName, text?: string): string { + return removeClosingTag(block, tag, text) + } +} diff --git a/src/core/task/tools/utils/ToolResultUtils.ts b/src/core/task/tools/utils/ToolResultUtils.ts new file mode 100644 index 00000000..aa4de88a --- /dev/null +++ b/src/core/task/tools/utils/ToolResultUtils.ts @@ -0,0 +1,76 @@ +import { ApiHandler } from "@core/api" +import { ToolUse } from "@core/assistant-message" +import { formatResponse } from "@core/prompts/responses" +import { ToolResponse } from "@core/task" +import type { ToolExecutorCoordinator } from "../ToolExecutorCoordinator" + +/** + * Utility functions for handling tool results and feedback + */ +export class ToolResultUtils { + /** + * Push tool result to user message content with proper formatting + */ + static pushToolResult( + content: ToolResponse, + block: ToolUse, + userMessageContent: any[], + toolDescription: (block: ToolUse) => string, + _api: ApiHandler, + markToolAsUsed: () => void, + coordinator?: ToolExecutorCoordinator, + ): void { + if (typeof content === "string") { + const resultText = content || "(tool did not return anything)" + + // Try to get description from coordinator first, otherwise use the provided function + const description = coordinator + ? (() => { + const handler = coordinator.getHandler(block.name) + return handler ? handler.getDescription(block) : toolDescription(block) + })() + : toolDescription(block) + + // Non-Claude 4: Use traditional format with header + userMessageContent.push({ + type: "text", + text: `${description} Result:`, + }) + userMessageContent.push({ + type: "text", + text: resultText, + }) + } else { + userMessageContent.push(...content) + } + // once a tool result has been collected, ignore all other tool uses since we should only ever present one tool result per message + markToolAsUsed() + } + + /** + * Push additional tool feedback from user to message content + */ + static pushAdditionalToolFeedback( + userMessageContent: any[], + feedback?: string, + images?: string[], + fileContentString?: string, + ): void { + if (!feedback && (!images || images.length === 0) && !fileContentString) { + return + } + const content = formatResponse.toolResult( + `The user provided the following feedback:\n\n${feedback}\n`, + images, + fileContentString, + ) + if (typeof content === "string") { + userMessageContent.push({ + type: "text", + text: content, + }) + } else { + userMessageContent.push(...content) + } + } +} diff --git a/src/core/task/tools/utils/index.ts b/src/core/task/tools/utils/index.ts new file mode 100644 index 00000000..b292c280 --- /dev/null +++ b/src/core/task/tools/utils/index.ts @@ -0,0 +1,3 @@ +export * from "./ToolConstants" +export { ToolDisplayUtils } from "./ToolDisplayUtils" +export { ToolResultUtils } from "./ToolResultUtils" diff --git a/src/services/browser/BrowserSession.ts b/src/services/browser/BrowserSession.ts index 6e410fac..7ff25f78 100644 --- a/src/services/browser/BrowserSession.ts +++ b/src/services/browser/BrowserSession.ts @@ -4,7 +4,7 @@ import { BrowserSettings } from "@shared/BrowserSettings" import { BrowserActionResult } from "@shared/ExtensionMessage" import { fileExistsAtPath } from "@utils/fs" import axios from "axios" -import { exec, spawn } from "child_process" +import { spawn } from "child_process" import * as chromeLauncher from "chrome-launcher" import * as fs from "fs/promises" import os from "os" @@ -371,40 +371,6 @@ export class BrowserSession { ) } - /** - * Kill all Chrome instances, including those not launched by chrome-launcher - */ - private async killAllChromeBrowsers(): Promise { - // First try chrome-launcher's killAll to handle instances it launched - try { - await chromeLauncher.killAll() - } catch (err: unknown) { - console.log("Error in chrome-launcher killAll:", err) - } - - // Then kill other Chrome instances using platform-specific commands - try { - if (process.platform === "win32") { - // Windows: Use taskkill to forcefully terminate Chrome processes - await new Promise((resolve, reject) => { - exec("taskkill /F /IM chrome.exe /T", () => resolve()) - }) - } else if (process.platform === "darwin") { - // macOS: Use pkill to terminate Chrome processes - await new Promise((resolve) => { - exec('pkill -x "Google Chrome"', () => resolve()) - }) - } else { - // Linux: Use pkill for Chrome and chromium - await new Promise((resolve) => { - exec('pkill -f "chrome|chromium"', () => resolve()) - }) - } - } catch (error) { - console.error("Error killing Chrome processes:", error) - } - } - async closeBrowser(): Promise { if (this.browser || this.page) { // Send telemetry for browser tool end if we have a task ID and session was started diff --git a/src/utils/path.ts b/src/utils/path.ts index ba01b015..4205efa6 100644 --- a/src/utils/path.ts +++ b/src/utils/path.ts @@ -1,6 +1,5 @@ import os from "os" import * as path from "path" -import * as vscode from "vscode" import { HostProvider } from "@/hosts/host-provider" /* diff --git a/webview-ui/src/components/settings/common/ModelInfoView.tsx b/webview-ui/src/components/settings/common/ModelInfoView.tsx index 2dd91d8e..2e902e0b 100644 --- a/webview-ui/src/components/settings/common/ModelInfoView.tsx +++ b/webview-ui/src/components/settings/common/ModelInfoView.tsx @@ -1,6 +1,5 @@ import { geminiModels, ModelInfo } from "@shared/api" import { Fragment, useState } from "react" -import { useExtensionState } from "@/context/ExtensionStateContext" import { ModelDescriptionMarkdown } from "../OpenRouterModelPicker" import { formatPrice, @@ -11,7 +10,6 @@ import { supportsImages, supportsPromptCache, } from "../utils/pricingUtils" -import { normalizeApiConfiguration } from "../utils/providerUtils" /** * Returns an array of formatted tier strings diff --git a/webview-ui/src/components/settings/utils/providerUtils.ts b/webview-ui/src/components/settings/utils/providerUtils.ts index 505afd03..c6414c17 100644 --- a/webview-ui/src/components/settings/utils/providerUtils.ts +++ b/webview-ui/src/components/settings/utils/providerUtils.ts @@ -476,12 +476,16 @@ export async function syncModeConfigurations( sourceMode: Mode, handleFieldsChange: (updates: Partial) => Promise, ): Promise { - if (!apiConfiguration) return + if (!apiConfiguration) { + return + } const sourceFields = getModeSpecificFields(apiConfiguration, sourceMode) const { apiProvider } = sourceFields - if (!apiProvider) return + if (!apiProvider) { + return + } // Build the complete update object with both plan and act mode fields const updates: Partial = {