| 1 | // @ts-ignore |
| 2 | import { ContinueError, ContinueErrorReason } from "core/util/errors.js"; |
| 3 | |
| 4 | import { posthogService } from "src/telemetry/posthogService.js"; |
| 5 | |
| 6 | import { |
| 7 | getServiceSync, |
| 8 | MCPServiceState, |
| 9 | SERVICE_NAMES, |
| 10 | serviceContainer, |
| 11 | } from "../services/index.js"; |
| 12 | import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; |
| 13 | import type { ModelServiceState } from "../services/types.js"; |
| 14 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 15 | import { logger } from "../util/logger.js"; |
| 16 | import { isModelCapable } from "../utils/index.js"; |
| 17 | |
| 18 | import { editTool } from "./edit.js"; |
| 19 | import { exitTool } from "./exit.js"; |
| 20 | import { fetchTool } from "./fetch.js"; |
| 21 | import { listFilesTool } from "./listFiles.js"; |
| 22 | import { multiEditTool } from "./multiEdit.js"; |
| 23 | import { readFileTool } from "./readFile.js"; |
| 24 | import { runTerminalCommandTool } from "./runTerminalCommand.js"; |
| 25 | import { searchCodeTool } from "./searchCode.js"; |
| 26 | import { |
| 27 | type Tool, |
| 28 | type ToolCall, |
| 29 | type ToolParametersSchema, |
| 30 | ParameterSchema, |
| 31 | PreprocessedToolCall, |
| 32 | } from "./types.js"; |
| 33 | import { writeChecklistTool } from "./writeChecklist.js"; |
| 34 | import { writeFileTool } from "./writeFile.js"; |
| 35 | |
| 36 | export type { Tool, ToolCall, ToolParametersSchema }; |
| 37 | |
| 38 | // Base tools that are always available |
| 39 | const BASE_BUILTIN_TOOLS: Tool[] = [ |
| 40 | readFileTool, |
| 41 | editTool, |
| 42 | multiEditTool, |
| 43 | writeFileTool, |
| 44 | // searchAndReplaceInFileTool, |
| 45 | listFilesTool, |
| 46 | searchCodeTool, |
| 47 | runTerminalCommandTool, |
| 48 | fetchTool, |
| 49 | writeChecklistTool, |
| 50 | ]; |
| 51 | |
| 52 | // Export BUILTIN_TOOLS as the base set of tools |
| 53 | // Dynamic tools (like exit tool in headless mode) are added separately |
| 54 | export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; |
| 55 | |
| 56 | // Get dynamic tools based on current state |
| 57 | function getDynamicTools(): Tool[] { |
| 58 | const dynamicTools: Tool[] = []; |
| 59 | |
| 60 | // Add headless-specific tools if in headless mode |
| 61 | try { |
| 62 | const serviceResult = getServiceSync<ToolPermissionServiceState>( |
| 63 | SERVICE_NAMES.TOOL_PERMISSIONS, |
| 64 | ); |
| 65 | const isHeadless = serviceResult.value?.isHeadless ?? false; |
| 66 | if (isHeadless) { |
| 67 | dynamicTools.push(exitTool); |
| 68 | } |
| 69 | } catch { |
| 70 | // Service not ready yet, no dynamic tools |
| 71 | } |
| 72 | |
| 73 | return dynamicTools; |
| 74 | } |
| 75 | |
| 76 | // Check if the current model is capable and should exclude Edit tool |
| 77 | function shouldExcludeEditTool(): boolean { |
| 78 | try { |
| 79 | const modelServiceResult = getServiceSync<ModelServiceState>( |
| 80 | SERVICE_NAMES.MODEL, |
| 81 | ); |
| 82 | |
| 83 | if ( |
| 84 | modelServiceResult.state === "ready" && |
| 85 | modelServiceResult.value?.model |
| 86 | ) { |
| 87 | const { name, provider, model } = modelServiceResult.value.model; |
| 88 | |
| 89 | // Check if model is capable |
| 90 | const isCapable = isModelCapable(provider, name, model); |
| 91 | |
| 92 | logger.debug("Capability-based tool filtering", { |
| 93 | provider, |
| 94 | name, |
| 95 | isCapable, |
| 96 | willExcludeEdit: isCapable, |
| 97 | }); |
| 98 | |
| 99 | return isCapable; |
| 100 | } |
| 101 | } catch (error) { |
| 102 | logger.debug("Error checking model capability for tool filtering", { |
| 103 | error, |
| 104 | }); |
| 105 | } |
| 106 | return false; |
| 107 | } |
| 108 | |
| 109 | // Get all builtin tools including dynamic ones, with capability-based filtering |
| 110 | export function getAllBuiltinTools(): Tool[] { |
| 111 | let builtinTools = [...BUILTIN_TOOLS]; |
| 112 | |
| 113 | // Apply capability-based filtering for edit tools |
| 114 | // If model is capable, exclude editTool in favor of multiEditTool |
| 115 | if (shouldExcludeEditTool()) { |
| 116 | builtinTools = builtinTools.filter((tool) => tool.name !== editTool.name); |
| 117 | logger.debug( |
| 118 | "Excluded Edit tool for capable model - MultiEdit will be used instead", |
| 119 | ); |
| 120 | } |
| 121 | |
| 122 | return [...builtinTools, ...getDynamicTools()]; |
| 123 | } |
| 124 | |
| 125 | export function getToolDisplayName(toolName: string): string { |
| 126 | const allTools = getAllBuiltinTools(); |
| 127 | const tool = allTools.find((t) => t.name === toolName); |
| 128 | return tool?.displayName || toolName; |
| 129 | } |
| 130 | |
| 131 | export function extractToolCalls( |
| 132 | response: string, |
| 133 | ): Array<{ name: string; arguments: Record<string, any> }> { |
| 134 | const toolCallRegex = /<tool>([\s\S]*?)<\/tool>/g; |
| 135 | const matches = [...response.matchAll(toolCallRegex)]; |
| 136 | |
| 137 | const toolCalls = []; |
| 138 | |
| 139 | for (const match of matches) { |
| 140 | try { |
| 141 | const toolCallJson = JSON.parse(match[1]); |
| 142 | if (toolCallJson.name && toolCallJson.arguments) { |
| 143 | toolCalls.push({ |
| 144 | name: toolCallJson.name, |
| 145 | arguments: toolCallJson.arguments, |
| 146 | }); |
| 147 | } |
| 148 | } catch { |
| 149 | logger.error("Failed to parse tool call:", { toolCall: match[1] }); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | return toolCalls; |
| 154 | } |
| 155 | |
| 156 | export async function getAvailableTools() { |
| 157 | // Load MCP tools |
| 158 | const mcpState = await serviceContainer.get<MCPServiceState>( |
| 159 | SERVICE_NAMES.MCP, |
| 160 | ); |
| 161 | const tools = mcpState.tools ?? []; |
| 162 | const mcpTools: Tool[] = |
| 163 | tools.map((t) => ({ |
| 164 | name: t.name, |
| 165 | displayName: t.name.replace("mcp__", "").replace("ide__", ""), |
| 166 | description: t.description ?? "", |
| 167 | parameters: { |
| 168 | type: "object", |
| 169 | properties: (t.inputSchema.properties ?? {}) as Record< |
| 170 | string, |
| 171 | ParameterSchema |
| 172 | >, |
| 173 | required: t.inputSchema.required, |
| 174 | }, |
| 175 | readonly: undefined, // MCP tools don't have readonly property |
| 176 | isBuiltIn: false, |
| 177 | run: async (args: any) => { |
| 178 | const result = await mcpState.mcpService?.runTool(t.name, args); |
| 179 | return JSON.stringify(result?.content) ?? ""; |
| 180 | }, |
| 181 | })) || []; |
| 182 | |
| 183 | const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools]; |
| 184 | return allTools; |
| 185 | } |
| 186 | |
| 187 | export async function executeToolCall( |
| 188 | toolCall: PreprocessedToolCall, |
| 189 | ): Promise<string> { |
| 190 | const startTime = Date.now(); |
| 191 | |
| 192 | try { |
| 193 | logger.debug("Executing tool", { |
| 194 | toolName: toolCall.name, |
| 195 | arguments: toolCall.arguments, |
| 196 | }); |
| 197 | |
| 198 | // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args |
| 199 | // Preprocessed arg names may be different |
| 200 | const result = await toolCall.tool.run( |
| 201 | toolCall.preprocessResult?.args ?? toolCall.arguments, |
| 202 | ); |
| 203 | const duration = Date.now() - startTime; |
| 204 | |
| 205 | telemetryService.logToolResult({ |
| 206 | toolName: toolCall.name, |
| 207 | success: true, |
| 208 | durationMs: duration, |
| 209 | toolParameters: JSON.stringify(toolCall.arguments), |
| 210 | }); |
| 211 | void posthogService.capture("tool_call_outcome", { |
| 212 | succeeded: true, |
| 213 | toolName: toolCall.name, |
| 214 | duration_ms: duration, |
| 215 | }); |
| 216 | |
| 217 | logger.debug("Tool execution completed", { |
| 218 | toolName: toolCall.name, |
| 219 | resultLength: result?.length || 0, |
| 220 | }); |
| 221 | |
| 222 | return result; |
| 223 | } catch (error) { |
| 224 | const duration = Date.now() - startTime; |
| 225 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 226 | const errorReason = |
| 227 | error instanceof ContinueError |
| 228 | ? error.reason |
| 229 | : ContinueErrorReason.Unknown; |
| 230 | |
| 231 | telemetryService.logToolResult({ |
| 232 | toolName: toolCall.name, |
| 233 | success: false, |
| 234 | durationMs: duration, |
| 235 | error: errorMessage, |
| 236 | errorReason, |
| 237 | toolParameters: JSON.stringify(toolCall.arguments), |
| 238 | }); |
| 239 | void posthogService.capture("tool_call_outcome", { |
| 240 | succeeded: false, |
| 241 | toolName: toolCall.name, |
| 242 | duration_ms: duration, |
| 243 | errorReason, |
| 244 | }); |
| 245 | |
| 246 | return `Error executing tool "${toolCall.name}": ${errorMessage}`; |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // Only checks top-level required |
| 251 | export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { |
| 252 | const requiredParams = tool.parameters.required ?? []; |
| 253 | for (const [paramName] of Object.entries(tool.parameters)) { |
| 254 | if ( |
| 255 | requiredParams.includes(paramName) && |
| 256 | (toolCall.arguments[paramName] === undefined || |
| 257 | toolCall.arguments[paramName] === null) |
| 258 | ) { |
| 259 | throw new Error( |
| 260 | `Required parameter "${paramName}" missing for tool "${toolCall.name}"`, |
| 261 | ); |
| 262 | } |
| 263 | } |
| 264 | } |