Elffuss BraidHub

kikocis/continue public

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