Elffuss BraidHub

kikocis/continue public

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