Elffuss BraidHub

kikocis/continue public

main · 7.7 KiBRawPermalink
1import type { ChatHistoryItem, ToolStatus } from "core/index.js";
2import { stripImages } from "core/util/messageContent.js";
3import { createHistoryItem } from "core/util/messageConversion.js";
4import type { ChatCompletionTool } from "openai/resources.mjs";
5
6import { filterExcludedTools } from "../permissions/index.js";
7import {
8 getServiceSync,
9 MCPServiceState,
10 MCPTool,
11 SERVICE_NAMES,
12 services,
13} from "../services/index.js";
14import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
15import { getAllBuiltinTools, ToolCall } from "../tools/index.js";
16import { logger } from "../util/logger.js";
17
18import {
19 executeStreamedToolCalls,
20 preprocessStreamedToolCalls,
21} from "./streamChatResponse.helpers.js";
22import { StreamCallbacks } from "./streamChatResponse.types.js";
23
24export async function handleToolCalls(
25 toolCalls: ToolCall[],
26 chatHistory: ChatHistoryItem[],
27 content: string,
28 callbacks: StreamCallbacks | undefined,
29 isHeadless: boolean,
30): Promise<boolean> {
31 const chatHistorySvc = services.chatHistory;
32 const useService =
33 typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady();
34 if (toolCalls.length === 0) {
35 if (content) {
36 if (useService) {
37 // Service-driven: write assistant message via service
38 chatHistorySvc.addAssistantMessage(content);
39 } else {
40 // Fallback only when service is unavailable
41 chatHistory.push(
42 createHistoryItem({
43 role: "assistant",
44 content,
45 }),
46 );
47 }
48 }
49 return false;
50 }
51
52 // Create tool call states for the ChatHistoryItem
53 const toolCallStates = toolCalls.map((tc) => ({
54 toolCallId: tc.id,
55 toolCall: {
56 id: tc.id,
57 type: "function" as const,
58 function: {
59 name: tc.name,
60 arguments: JSON.stringify(tc.arguments),
61 },
62 },
63 status: "generated" as ToolStatus,
64 parsedArgs: tc.arguments,
65 }));
66
67 // Create assistant message with tool calls
68 const assistantMessage = {
69 role: "assistant" as const,
70 content: content || "",
71 toolCalls: toolCalls.map((tc) => ({
72 id: tc.id,
73 type: "function" as const,
74 function: {
75 name: tc.name,
76 arguments: JSON.stringify(tc.arguments),
77 },
78 })),
79 };
80
81 if (useService) {
82 // Important: pass ChatCompletion-style toolCalls, not internal ToolCall[]
83 chatHistorySvc.addAssistantMessage(
84 assistantMessage.content || "",
85 assistantMessage.toolCalls,
86 );
87 } else {
88 // Fallback only when service is unavailable
89 chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
90 }
91
92 // First preprocess the tool calls
93 const { preprocessedCalls, errorChatEntries } =
94 await preprocessStreamedToolCalls(toolCalls, callbacks);
95
96 // Add any preprocessing errors to chat history
97 // Convert error entries from OpenAI format to ChatHistoryItem format
98 errorChatEntries.forEach((errorEntry) => {
99 const item = createHistoryItem({
100 role: "tool",
101 content: stripImages(errorEntry.content) || "",
102 toolCallId: errorEntry.tool_call_id,
103 });
104 if (useService) {
105 chatHistorySvc.addHistoryItem(item);
106 } else {
107 // Fallback only when service is unavailable
108 chatHistory.push(item);
109 }
110 });
111
112 // Execute the valid preprocessed tool calls
113 const { chatHistoryEntries: toolResults, hasRejection } =
114 await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
115
116 if (isHeadless && hasRejection) {
117 logger.debug(
118 "Tool call rejected in headless mode - returning current content",
119 );
120 return true; // Signal early return needed
121 }
122
123 // Convert tool results and add them to the chat history with per-result status
124 toolResults.forEach((toolResult) => {
125 const resultContent =
126 typeof toolResult.content === "string" ? toolResult.content : "";
127
128 // Derive per-result status instead of applying batch-wide hasRejection
129 let status: ToolStatus = "done";
130 const lower = resultContent.toLowerCase();
131 if (
132 lower.includes("permission denied by user") ||
133 lower.includes("cancelled due to previous tool rejection") ||
134 lower.includes("canceled due to previous tool rejection")
135 ) {
136 status = "canceled";
137 } else if (
138 lower.startsWith("error executing tool") ||
139 lower.startsWith("error:")
140 ) {
141 status = "errored" as ToolStatus;
142 }
143
144 if (useService) {
145 chatHistorySvc.addToolResult(
146 toolResult.tool_call_id,
147 resultContent,
148 status,
149 );
150 } else {
151 // Fallback only when service is unavailable: update local tool state
152 const lastAssistantIndex = chatHistory.findLastIndex(
153 (item) => item.message.role === "assistant" && item.toolCallStates,
154 );
155 if (
156 lastAssistantIndex >= 0 &&
157 chatHistory[lastAssistantIndex].toolCallStates
158 ) {
159 const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
160 (ts) => ts.toolCallId === toolResult.tool_call_id,
161 );
162 if (toolState) {
163 toolState.status = status;
164 toolState.output = [
165 {
166 content: resultContent,
167 name: `Tool Result`,
168 description: "Tool execution result",
169 },
170 ];
171 }
172 }
173 }
174 });
175 return false;
176}
177
178export async function getAllTools() {
179 // Get all available tool names
180 const allBuiltinTools = getAllBuiltinTools();
181 const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
182
183 let mcpTools: MCPTool[] = [];
184 let mcpToolNames: string[] = [];
185 const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP);
186 if (mcpServiceResult.state === "ready") {
187 mcpTools = mcpServiceResult?.value?.tools ?? [];
188 mcpToolNames = mcpTools.map((t) => t.name);
189 } else {
190 // MCP is lazy
191 // throw new Error("MCP Service not initialized");
192 }
193
194 const allToolNames = [...builtinToolNames, ...mcpToolNames];
195
196 // Check if the ToolPermissionService is ready
197 const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>(
198 SERVICE_NAMES.TOOL_PERMISSIONS,
199 );
200
201 let allowedToolNames: string[];
202 if (
203 permissionsServiceResult.state === "ready" &&
204 permissionsServiceResult.value
205 ) {
206 // Filter out excluded tools based on permissions
207 allowedToolNames = filterExcludedTools(
208 allToolNames,
209 permissionsServiceResult.value.permissions,
210 );
211 } else {
212 // Service not ready - this is a critical error since tools should only be
213 // requested after services are properly initialized
214 logger.error(
215 "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
216 );
217 throw new Error(
218 "ToolPermissionService not initialized. Services must be initialized before requesting tools.",
219 );
220 }
221
222 const allowedToolNamesSet = new Set(allowedToolNames);
223
224 // Filter builtin tools
225 const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
226 allowedToolNamesSet.has(tool.name),
227 );
228
229 const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
230 type: "function" as const,
231 function: {
232 name: tool.name,
233 description: tool.description,
234 parameters: {
235 type: "object",
236 required: tool.parameters.required,
237 properties: tool.parameters.properties,
238 },
239 },
240 }));
241
242 // Add filtered MCP tools
243 const allowedMcpTools = mcpTools.filter((tool) =>
244 allowedToolNamesSet.has(tool.name),
245 );
246
247 allTools.push(
248 ...allowedMcpTools.map((tool) => ({
249 type: "function" as const,
250 function: {
251 name: tool.name,
252 description: tool.description,
253 parameters: tool.inputSchema,
254 },
255 })),
256 );
257
258 return allTools;
259}