| 1 | // @ts-ignore |
| 2 | import { |
| 3 | getServiceSync, |
| 4 | MCPServiceState, |
| 5 | SERVICE_NAMES, |
| 6 | serviceContainer, |
| 7 | } from "../services/index.js"; |
| 8 | import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; |
| 9 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 10 | import { logger } from "../util/logger.js"; |
| 11 | |
| 12 | import { editTool } from "./edit.js"; |
| 13 | import { exitTool } from "./exit.js"; |
| 14 | import { fetchTool } from "./fetch.js"; |
| 15 | import { listFilesTool } from "./listFiles.js"; |
| 16 | import { multiEditTool } from "./multiEdit.js"; |
| 17 | import { readFileTool } from "./readFile.js"; |
| 18 | import { runTerminalCommandTool } from "./runTerminalCommand.js"; |
| 19 | import { searchCodeTool } from "./searchCode.js"; |
| 20 | import { |
| 21 | type Tool, |
| 22 | type ToolCall, |
| 23 | type ToolParameters, |
| 24 | PreprocessedToolCall, |
| 25 | } from "./types.js"; |
| 26 | import { writeChecklistTool } from "./writeChecklist.js"; |
| 27 | import { writeFileTool } from "./writeFile.js"; |
| 28 | |
| 29 | export type { Tool, ToolCall, ToolParameters }; |
| 30 | |
| 31 | // Base tools that are always available |
| 32 | const BASE_BUILTIN_TOOLS: Tool[] = [ |
| 33 | readFileTool, |
| 34 | editTool, |
| 35 | multiEditTool, |
| 36 | writeFileTool, |
| 37 | // searchAndReplaceInFileTool, |
| 38 | listFilesTool, |
| 39 | searchCodeTool, |
| 40 | runTerminalCommandTool, |
| 41 | fetchTool, |
| 42 | writeChecklistTool, |
| 43 | ]; |
| 44 | |
| 45 | // Export BUILTIN_TOOLS as the base set of tools |
| 46 | // Dynamic tools (like exit tool in headless mode) are added separately |
| 47 | export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; |
| 48 | |
| 49 | // Get dynamic tools based on current state |
| 50 | function getDynamicTools(): Tool[] { |
| 51 | const dynamicTools: Tool[] = []; |
| 52 | |
| 53 | // Add headless-specific tools if in headless mode |
| 54 | try { |
| 55 | const serviceResult = getServiceSync<ToolPermissionServiceState>( |
| 56 | SERVICE_NAMES.TOOL_PERMISSIONS, |
| 57 | ); |
| 58 | const isHeadless = serviceResult.value?.isHeadless ?? false; |
| 59 | if (isHeadless) { |
| 60 | dynamicTools.push(exitTool); |
| 61 | } |
| 62 | } catch { |
| 63 | // Service not ready yet, no dynamic tools |
| 64 | } |
| 65 | |
| 66 | return dynamicTools; |
| 67 | } |
| 68 | |
| 69 | // Get all builtin tools including dynamic ones |
| 70 | export function getAllBuiltinTools(): Tool[] { |
| 71 | return [...BUILTIN_TOOLS, ...getDynamicTools()]; |
| 72 | } |
| 73 | |
| 74 | export function getToolDisplayName(toolName: string): string { |
| 75 | const allTools = getAllBuiltinTools(); |
| 76 | const tool = allTools.find((t) => t.name === toolName); |
| 77 | return tool?.displayName || toolName; |
| 78 | } |
| 79 | |
| 80 | export function extractToolCalls( |
| 81 | response: string, |
| 82 | ): Array<{ name: string; arguments: Record<string, any> }> { |
| 83 | const toolCallRegex = /<tool>([\s\S]*?)<\/tool>/g; |
| 84 | const matches = [...response.matchAll(toolCallRegex)]; |
| 85 | |
| 86 | const toolCalls = []; |
| 87 | |
| 88 | for (const match of matches) { |
| 89 | try { |
| 90 | const toolCallJson = JSON.parse(match[1]); |
| 91 | if (toolCallJson.name && toolCallJson.arguments) { |
| 92 | toolCalls.push({ |
| 93 | name: toolCallJson.name, |
| 94 | arguments: toolCallJson.arguments, |
| 95 | }); |
| 96 | } |
| 97 | } catch { |
| 98 | logger.error("Failed to parse tool call:", { toolCall: match[1] }); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | return toolCalls; |
| 103 | } |
| 104 | |
| 105 | function convertInputSchemaToParameters(inputSchema: any): ToolParameters { |
| 106 | const parameters: Record< |
| 107 | string, |
| 108 | { type: string; description: string; required: boolean } |
| 109 | > = {}; |
| 110 | for (const [key, value] of Object.entries(inputSchema.properties)) { |
| 111 | const val = value as any; |
| 112 | parameters[key] = { |
| 113 | type: val.type, |
| 114 | description: val.description || "", |
| 115 | required: inputSchema.required?.includes(key) || false, |
| 116 | }; |
| 117 | } |
| 118 | return parameters; |
| 119 | } |
| 120 | |
| 121 | export async function getAvailableTools() { |
| 122 | // Load MCP tools |
| 123 | const mcpState = await serviceContainer.get<MCPServiceState>( |
| 124 | SERVICE_NAMES.MCP, |
| 125 | ); |
| 126 | const tools = mcpState.tools ?? []; |
| 127 | const mcpTools: Tool[] = |
| 128 | tools.map((t) => ({ |
| 129 | name: t.name, |
| 130 | displayName: t.name.replace("mcp__", "").replace("ide__", ""), |
| 131 | description: t.description ?? "", |
| 132 | parameters: convertInputSchemaToParameters(t.inputSchema), |
| 133 | readonly: undefined, // MCP tools don't have readonly property |
| 134 | isBuiltIn: false, |
| 135 | run: async (args: any) => { |
| 136 | const result = await mcpState.mcpService?.runTool(t.name, args); |
| 137 | return JSON.stringify(result?.content) ?? ""; |
| 138 | }, |
| 139 | })) || []; |
| 140 | |
| 141 | const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools]; |
| 142 | return allTools; |
| 143 | } |
| 144 | |
| 145 | export async function executeToolCall( |
| 146 | toolCall: PreprocessedToolCall, |
| 147 | ): Promise<string> { |
| 148 | const startTime = Date.now(); |
| 149 | |
| 150 | try { |
| 151 | logger.debug("Executing tool", { |
| 152 | toolName: toolCall.name, |
| 153 | arguments: toolCall.arguments, |
| 154 | }); |
| 155 | |
| 156 | // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args |
| 157 | // Preprocessed arg names may be different |
| 158 | const result = await toolCall.tool.run( |
| 159 | toolCall.preprocessResult?.args ?? toolCall.arguments, |
| 160 | ); |
| 161 | const duration = Date.now() - startTime; |
| 162 | |
| 163 | telemetryService.logToolResult({ |
| 164 | toolName: toolCall.name, |
| 165 | success: true, |
| 166 | durationMs: duration, |
| 167 | toolParameters: JSON.stringify(toolCall.arguments), |
| 168 | }); |
| 169 | |
| 170 | logger.debug("Tool execution completed", { |
| 171 | toolName: toolCall.name, |
| 172 | resultLength: result?.length || 0, |
| 173 | }); |
| 174 | |
| 175 | return result; |
| 176 | } catch (error) { |
| 177 | const duration = Date.now() - startTime; |
| 178 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 179 | |
| 180 | telemetryService.logToolResult({ |
| 181 | toolName: toolCall.name, |
| 182 | success: false, |
| 183 | durationMs: duration, |
| 184 | error: errorMessage, |
| 185 | toolParameters: JSON.stringify(toolCall.arguments), |
| 186 | }); |
| 187 | |
| 188 | return `Error executing tool "${toolCall.name}": ${errorMessage}`; |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { |
| 193 | for (const [paramName, paramDef] of Object.entries(tool.parameters)) { |
| 194 | if ( |
| 195 | paramDef.required && |
| 196 | (toolCall.arguments[paramName] === undefined || |
| 197 | toolCall.arguments[paramName] === null) |
| 198 | ) { |
| 199 | throw new Error( |
| 200 | `Required parameter "${paramName}" missing for tool "${toolCall.name}"`, |
| 201 | ); |
| 202 | } |
| 203 | } |
| 204 | } |