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