| 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | import { LLMFullCompletionOptions, Tool } from "core"; |
| 3 | import { getRuleId } from "core/llm/rules/getSystemMessageWithRules"; |
| 4 | import { ToCoreProtocol } from "core/protocol"; |
| 5 | import { selectActiveTools } from "../selectors/selectActiveTools"; |
| 6 | import { selectUseSystemMessageTools } from "../selectors/selectUseSystemMessageTools"; |
| 7 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 8 | import { |
| 9 | abortStream, |
| 10 | addPromptCompletionPair, |
| 11 | setActive, |
| 12 | setAppliedRulesAtIndex, |
| 13 | setContextPercentage, |
| 14 | setInactive, |
| 15 | setInlineErrorMessage, |
| 16 | setIsPruned, |
| 17 | setToolGenerated, |
| 18 | streamUpdate, |
| 19 | } from "../slices/sessionSlice"; |
| 20 | import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; |
| 21 | import { constructMessages } from "../util/constructMessages"; |
| 22 | |
| 23 | import { modelSupportsNativeTools } from "core/llm/toolSupport"; |
| 24 | import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage"; |
| 25 | import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls"; |
| 26 | import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks"; |
| 27 | import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; |
| 28 | import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; |
| 29 | import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; |
| 30 | import { callToolById } from "./callToolById"; |
| 31 | import { enhanceParsedArgs } from "./enhanceParsedArgs"; |
| 32 | /** |
| 33 | * Handles the execution of tool calls that may be automatically accepted. |
| 34 | * Sets all tools as generated first, then executes auto-approved tool calls. |
| 35 | */ |
| 36 | async function handleToolCallExecution( |
| 37 | dispatch: AppThunkDispatch, |
| 38 | getState: () => RootState, |
| 39 | activeTools: Tool[], |
| 40 | ): Promise<void> { |
| 41 | const newState = getState(); |
| 42 | const toolSettings = newState.ui.toolSettings; |
| 43 | const allToolCallStates = selectCurrentToolCalls(newState); |
| 44 | |
| 45 | // Only process tool calls that are in "generating" status (newly created during this streaming session) |
| 46 | const toolCallStates = allToolCallStates.filter( |
| 47 | (toolCallState) => toolCallState.status === "generating", |
| 48 | ); |
| 49 | |
| 50 | // If no generating tool calls, nothing to process |
| 51 | if (toolCallStates.length === 0) { |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | // Check if ALL tool calls are auto-approved - if not, wait for user approval |
| 56 | const allAutoApproved = toolCallStates.every((toolCallState) => { |
| 57 | const toolPolicy = |
| 58 | toolSettings[toolCallState.toolCall.function.name] ?? |
| 59 | activeTools.find( |
| 60 | (tool) => tool.function.name === toolCallState.toolCall.function.name, |
| 61 | )?.defaultToolPolicy ?? |
| 62 | DEFAULT_TOOL_SETTING; |
| 63 | return toolPolicy == "allowedWithoutPermission"; |
| 64 | }); |
| 65 | |
| 66 | // Set all tools as generated first |
| 67 | toolCallStates.forEach((toolCallState) => { |
| 68 | dispatch( |
| 69 | setToolGenerated({ |
| 70 | toolCallId: toolCallState.toolCallId, |
| 71 | tools: newState.config.config.tools, |
| 72 | }), |
| 73 | ); |
| 74 | }); |
| 75 | |
| 76 | // Only run if we have auto-approve for all |
| 77 | if (allAutoApproved && toolCallStates.length > 0) { |
| 78 | const toolCallPromises = toolCallStates.map(async (toolCallState) => { |
| 79 | const response = await dispatch( |
| 80 | callToolById({ toolCallId: toolCallState.toolCallId }), |
| 81 | ); |
| 82 | unwrapResult(response); |
| 83 | }); |
| 84 | |
| 85 | await Promise.all(toolCallPromises); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | export const streamNormalInput = createAsyncThunk< |
| 90 | void, |
| 91 | { |
| 92 | legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; |
| 93 | }, |
| 94 | ThunkApiType |
| 95 | >( |
| 96 | "chat/streamNormalInput", |
| 97 | async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { |
| 98 | const state = getState(); |
| 99 | const selectedChatModel = selectSelectedChatModel(state); |
| 100 | |
| 101 | if (!selectedChatModel) { |
| 102 | throw new Error("No chat model selected"); |
| 103 | } |
| 104 | |
| 105 | // Get tools and filter them based on the selected model |
| 106 | const activeTools = selectActiveTools(state); |
| 107 | |
| 108 | const supportsNativeTools = modelSupportsNativeTools(selectedChatModel); |
| 109 | |
| 110 | // Use the centralized selector to determine if system message tools should be used |
| 111 | const useSystemTools = selectUseSystemMessageTools(state); |
| 112 | const useNativeTools = !useSystemTools && supportsNativeTools; |
| 113 | const systemToolsFramework = useSystemTools |
| 114 | ? new SystemMessageToolCodeblocksFramework() |
| 115 | : undefined; |
| 116 | |
| 117 | // Construct completion options |
| 118 | let completionOptions: LLMFullCompletionOptions = {}; |
| 119 | if (useNativeTools && activeTools.length > 0) { |
| 120 | completionOptions = { |
| 121 | tools: activeTools, |
| 122 | }; |
| 123 | } |
| 124 | |
| 125 | if (state.session.hasReasoningEnabled) { |
| 126 | completionOptions = { |
| 127 | ...completionOptions, |
| 128 | reasoning: true, |
| 129 | reasoningBudgetTokens: |
| 130 | selectedChatModel.completionOptions?.reasoningBudgetTokens ?? 2048, |
| 131 | }; |
| 132 | } |
| 133 | |
| 134 | // Construct messages (excluding system message) |
| 135 | const baseSystemMessage = getBaseSystemMessage( |
| 136 | state.session.mode, |
| 137 | selectedChatModel, |
| 138 | activeTools, |
| 139 | ); |
| 140 | |
| 141 | const systemMessage = systemToolsFramework |
| 142 | ? addSystemMessageToolsToSystemMessage( |
| 143 | systemToolsFramework, |
| 144 | baseSystemMessage, |
| 145 | activeTools, |
| 146 | ) |
| 147 | : baseSystemMessage; |
| 148 | |
| 149 | const withoutMessageIds = state.session.history.map((item) => { |
| 150 | const { id, ...messageWithoutId } = item.message; |
| 151 | return { ...item, message: messageWithoutId }; |
| 152 | }); |
| 153 | |
| 154 | const { messages, appliedRules, appliedRuleIndex } = constructMessages( |
| 155 | withoutMessageIds, |
| 156 | systemMessage, |
| 157 | state.config.config.rules, |
| 158 | state.ui.ruleSettings, |
| 159 | systemToolsFramework, |
| 160 | ); |
| 161 | |
| 162 | // TODO parallel tool calls will cause issues with this |
| 163 | // because there will be multiple tool messages, so which one should have applied rules? |
| 164 | dispatch( |
| 165 | setAppliedRulesAtIndex({ |
| 166 | index: appliedRuleIndex, |
| 167 | appliedRules: appliedRules, |
| 168 | }), |
| 169 | ); |
| 170 | |
| 171 | dispatch(setActive()); |
| 172 | dispatch(setInlineErrorMessage(undefined)); |
| 173 | |
| 174 | const precompiledRes = await extra.ideMessenger.request("llm/compileChat", { |
| 175 | messages, |
| 176 | options: completionOptions, |
| 177 | }); |
| 178 | |
| 179 | if (precompiledRes.status === "error") { |
| 180 | if (precompiledRes.error.includes("Not enough context")) { |
| 181 | dispatch(setInlineErrorMessage("out-of-context")); |
| 182 | dispatch(setInactive()); |
| 183 | return; |
| 184 | } else { |
| 185 | throw new Error(precompiledRes.error); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | const { compiledChatMessages, didPrune, contextPercentage } = |
| 190 | precompiledRes.content; |
| 191 | |
| 192 | dispatch(setIsPruned(didPrune)); |
| 193 | dispatch(setContextPercentage(contextPercentage)); |
| 194 | |
| 195 | // Send request and stream response |
| 196 | const streamAborter = state.session.streamAborter; |
| 197 | let gen = extra.ideMessenger.llmStreamChat( |
| 198 | { |
| 199 | completionOptions, |
| 200 | title: selectedChatModel.title, |
| 201 | messages: compiledChatMessages, |
| 202 | legacySlashCommandData, |
| 203 | messageOptions: { precompiled: true }, |
| 204 | }, |
| 205 | streamAborter.signal, |
| 206 | ); |
| 207 | if (systemToolsFramework && activeTools.length > 0) { |
| 208 | gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework); |
| 209 | } |
| 210 | |
| 211 | let next = await gen.next(); |
| 212 | while (!next.done) { |
| 213 | if (!getState().session.isStreaming) { |
| 214 | dispatch(abortStream()); |
| 215 | break; |
| 216 | } |
| 217 | |
| 218 | dispatch(streamUpdate(next.value)); |
| 219 | next = await gen.next(); |
| 220 | } |
| 221 | |
| 222 | // Attach prompt log and end thinking for reasoning models |
| 223 | if (next.done && next.value) { |
| 224 | dispatch(addPromptCompletionPair([next.value])); |
| 225 | |
| 226 | try { |
| 227 | extra.ideMessenger.post("devdata/log", { |
| 228 | name: "chatInteraction", |
| 229 | data: { |
| 230 | prompt: next.value.prompt, |
| 231 | completion: next.value.completion, |
| 232 | modelProvider: selectedChatModel.underlyingProviderName, |
| 233 | modelName: selectedChatModel.title, |
| 234 | modelTitle: selectedChatModel.title, |
| 235 | sessionId: state.session.id, |
| 236 | ...(!!activeTools.length && { |
| 237 | tools: activeTools.map((tool) => tool.function.name), |
| 238 | }), |
| 239 | ...(appliedRules.length > 0 && { |
| 240 | rules: appliedRules.map((rule) => ({ |
| 241 | id: getRuleId(rule), |
| 242 | rule: rule.rule, |
| 243 | slug: rule.slug, |
| 244 | })), |
| 245 | }), |
| 246 | }, |
| 247 | }); |
| 248 | } catch (e) { |
| 249 | console.error("Failed to send dev data interaction log", e); |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // Check if we have any tool calls that were just generated |
| 254 | const newState = getState(); |
| 255 | const toolSettings = newState.ui.toolSettings; |
| 256 | const allToolCallStates = selectCurrentToolCalls(newState); |
| 257 | |
| 258 | await Promise.all( |
| 259 | allToolCallStates.map((tcState) => |
| 260 | enhanceParsedArgs( |
| 261 | extra.ideMessenger, |
| 262 | dispatch, |
| 263 | tcState?.toolCall.function.name, |
| 264 | tcState.toolCallId, |
| 265 | tcState.parsedArgs, |
| 266 | ), |
| 267 | ), |
| 268 | ); |
| 269 | |
| 270 | const generatingToolCalls = allToolCallStates.filter( |
| 271 | (toolCallState) => toolCallState.status === "generating", |
| 272 | ); |
| 273 | |
| 274 | // Check if ALL generating tool calls are auto-approved |
| 275 | const allAutoApproved = |
| 276 | generatingToolCalls.length > 0 && |
| 277 | generatingToolCalls.every((toolCallState) => { |
| 278 | const toolPolicy = |
| 279 | toolSettings[toolCallState.toolCall.function.name] ?? |
| 280 | activeTools.find( |
| 281 | (tool) => |
| 282 | tool.function.name === toolCallState.toolCall.function.name, |
| 283 | )?.defaultToolPolicy ?? |
| 284 | DEFAULT_TOOL_SETTING; |
| 285 | return toolPolicy == "allowedWithoutPermission"; |
| 286 | }); |
| 287 | |
| 288 | // Only set inactive if: |
| 289 | // 1. There are no tool calls, OR |
| 290 | // 2. There are tool calls but they require manual approval |
| 291 | // This prevents UI flashing for auto-approved tools while still showing approval UI for others |
| 292 | if (generatingToolCalls.length === 0 || !allAutoApproved) { |
| 293 | dispatch(setInactive()); |
| 294 | } |
| 295 | |
| 296 | await handleToolCallExecution(dispatch, getState, activeTools); |
| 297 | }, |
| 298 | ); |