| 1 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 2 | import { |
| 3 | ContextItem, |
| 4 | LLMFullCompletionOptions, |
| 5 | Tool, |
| 6 | ToolCallState, |
| 7 | } from "core"; |
| 8 | import { ToolPolicy } from "@continuedev/terminal-security"; |
| 9 | import { getRuleId } from "core/llm/rules/getSystemMessageWithRules"; |
| 10 | import { ToCoreProtocol } from "core/protocol"; |
| 11 | import { selectActiveTools } from "../selectors/selectActiveTools"; |
| 12 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 13 | import { |
| 14 | abortStream, |
| 15 | addPromptCompletionPair, |
| 16 | errorToolCall, |
| 17 | setActive, |
| 18 | setAppliedRulesAtIndex, |
| 19 | setContextPercentage, |
| 20 | setInactive, |
| 21 | setInlineErrorMessage, |
| 22 | setIsPruned, |
| 23 | setToolGenerated, |
| 24 | streamUpdate, |
| 25 | updateToolCallOutput, |
| 26 | } from "../slices/sessionSlice"; |
| 27 | import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; |
| 28 | import { IIdeMessenger } from "../../context/IdeMessenger"; |
| 29 | import { constructMessages } from "../util/constructMessages"; |
| 30 | |
| 31 | import { modelSupportsNativeTools } from "core/llm/toolSupport"; |
| 32 | import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage"; |
| 33 | import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls"; |
| 34 | import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks"; |
| 35 | import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; |
| 36 | import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; |
| 37 | import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; |
| 38 | import { callToolById } from "./callToolById"; |
| 39 | import { enhanceParsedArgs } from "./enhanceParsedArgs"; |
| 40 | |
| 41 | /** |
| 42 | * Evaluates the tool policy for a tool call, including dynamic policy evaluation |
| 43 | */ |
| 44 | async function evaluateToolPolicy( |
| 45 | toolCallState: ToolCallState, |
| 46 | toolSettings: Record<string, ToolPolicy>, |
| 47 | activeTools: Tool[], |
| 48 | ideMessenger: IIdeMessenger, |
| 49 | ): Promise<{ policy: ToolPolicy; displayValue?: string }> { |
| 50 | const basePolicy = |
| 51 | toolSettings[toolCallState.toolCall.function.name] ?? |
| 52 | activeTools.find( |
| 53 | (tool) => tool.function.name === toolCallState.toolCall.function.name, |
| 54 | )?.defaultToolPolicy ?? |
| 55 | DEFAULT_TOOL_SETTING; |
| 56 | |
| 57 | // Use already parsed arguments |
| 58 | const parsedArgs = toolCallState.parsedArgs || {}; |
| 59 | |
| 60 | let result; |
| 61 | try { |
| 62 | result = await ideMessenger.request("tools/evaluatePolicy", { |
| 63 | toolName: toolCallState.toolCall.function.name, |
| 64 | basePolicy, |
| 65 | args: parsedArgs, |
| 66 | }); |
| 67 | } catch (error) { |
| 68 | // If request fails, return disabled |
| 69 | return { policy: "disabled" }; |
| 70 | } |
| 71 | |
| 72 | // Evaluate the policy dynamically |
| 73 | if (!result || result.status === "error") { |
| 74 | // If evaluation fails, treat as disabled |
| 75 | return { policy: "disabled" }; |
| 76 | } |
| 77 | |
| 78 | const dynamicPolicy = result.content.policy; |
| 79 | const displayValue = result.content.displayValue; |
| 80 | |
| 81 | // Ensure dynamic policy cannot be more lenient than base policy |
| 82 | // Policy hierarchy (most restrictive to least): disabled > allowedWithPermission > allowedWithoutPermission |
| 83 | if (basePolicy === "disabled") { |
| 84 | return { policy: "disabled", displayValue }; // Cannot override disabled |
| 85 | } |
| 86 | if ( |
| 87 | basePolicy === "allowedWithPermission" && |
| 88 | dynamicPolicy === "allowedWithoutPermission" |
| 89 | ) { |
| 90 | return { policy: "allowedWithPermission", displayValue }; // Cannot make more lenient |
| 91 | } |
| 92 | |
| 93 | return { policy: dynamicPolicy, displayValue }; |
| 94 | } |
| 95 | |
| 96 | /** |
| 97 | * Handles the execution of tool calls that may be automatically accepted. |
| 98 | * Sets all tools as generated first, then executes auto-approved tool calls. |
| 99 | */ |
| 100 | async function handleToolCallExecution( |
| 101 | dispatch: AppThunkDispatch, |
| 102 | getState: () => RootState, |
| 103 | activeTools: Tool[], |
| 104 | ideMessenger: IIdeMessenger, |
| 105 | ): Promise<boolean> { |
| 106 | // Return whether all tools were auto-approved |
| 107 | const newState = getState(); |
| 108 | const toolSettings = newState.ui.toolSettings; |
| 109 | const allToolCallStates = selectCurrentToolCalls(newState); |
| 110 | |
| 111 | // Only process tool calls that are in "generating" status (newly created during this streaming session) |
| 112 | const toolCallStates = allToolCallStates.filter( |
| 113 | (toolCallState) => toolCallState.status === "generating", |
| 114 | ); |
| 115 | |
| 116 | // If no generating tool calls, nothing to process |
| 117 | if (toolCallStates.length === 0) { |
| 118 | return false; // No tools to process, need to set inactive |
| 119 | } |
| 120 | |
| 121 | // Check if ALL tool calls are auto-approved using dynamic evaluation |
| 122 | const policyResults = await Promise.all( |
| 123 | toolCallStates.map((toolCallState) => |
| 124 | evaluateToolPolicy( |
| 125 | toolCallState, |
| 126 | toolSettings, |
| 127 | activeTools, |
| 128 | ideMessenger, |
| 129 | ), |
| 130 | ), |
| 131 | ); |
| 132 | |
| 133 | // Handle disabled tool calls and set others as generated |
| 134 | const autoApprovedResults = await Promise.all( |
| 135 | toolCallStates.map(async (toolCallState, index) => { |
| 136 | const { policy, displayValue } = policyResults[index]; |
| 137 | |
| 138 | if (policy === "disabled") { |
| 139 | // Mark as errored instead of generated |
| 140 | dispatch(errorToolCall({ toolCallId: toolCallState.toolCallId })); |
| 141 | |
| 142 | // Use the displayValue from the policy evaluation, or fallback to function name |
| 143 | const command = displayValue || toolCallState.toolCall.function.name; |
| 144 | |
| 145 | // Add error message explaining why it's disabled |
| 146 | dispatch( |
| 147 | updateToolCallOutput({ |
| 148 | toolCallId: toolCallState.toolCallId, |
| 149 | contextItems: [ |
| 150 | { |
| 151 | icon: "problems", |
| 152 | name: "Security Policy Violation", |
| 153 | description: "Command Disabled", |
| 154 | content: `This command has been disabled by security policy:\n\n${command}\n\nThis command cannot be executed as it may pose a security risk.`, |
| 155 | hidden: false, |
| 156 | }, |
| 157 | ], |
| 158 | }), |
| 159 | ); |
| 160 | return false; |
| 161 | } else { |
| 162 | // Set as generated for non-disabled tools |
| 163 | dispatch( |
| 164 | setToolGenerated({ |
| 165 | toolCallId: toolCallState.toolCallId, |
| 166 | tools: newState.config.config.tools, |
| 167 | }), |
| 168 | ); |
| 169 | return policy === "allowedWithoutPermission"; |
| 170 | } |
| 171 | }), |
| 172 | ); |
| 173 | |
| 174 | const allAutoApproved = autoApprovedResults.every(Boolean); |
| 175 | |
| 176 | // Only run if we have auto-approve for all non-disabled tools |
| 177 | if (allAutoApproved && toolCallStates.length > 0) { |
| 178 | const nonDisabledToolCalls = toolCallStates.filter( |
| 179 | (_, index) => policyResults[index].policy !== "disabled", |
| 180 | ); |
| 181 | |
| 182 | const toolCallPromises = nonDisabledToolCalls.map(async (toolCallState) => { |
| 183 | const response = await dispatch( |
| 184 | callToolById({ toolCallId: toolCallState.toolCallId }), |
| 185 | ); |
| 186 | unwrapResult(response); |
| 187 | }); |
| 188 | |
| 189 | await Promise.all(toolCallPromises); |
| 190 | } |
| 191 | |
| 192 | return allAutoApproved; |
| 193 | } |
| 194 | |
| 195 | export const streamNormalInput = createAsyncThunk< |
| 196 | void, |
| 197 | { |
| 198 | legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; |
| 199 | }, |
| 200 | ThunkApiType |
| 201 | >( |
| 202 | "chat/streamNormalInput", |
| 203 | async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { |
| 204 | const state = getState(); |
| 205 | const selectedChatModel = selectSelectedChatModel(state); |
| 206 | |
| 207 | if (!selectedChatModel) { |
| 208 | throw new Error("No chat model selected"); |
| 209 | } |
| 210 | |
| 211 | // Get tools and filter them based on the selected model |
| 212 | const activeTools = selectActiveTools(state); |
| 213 | |
| 214 | // Use the centralized selector to determine if system message tools should be used |
| 215 | const useNativeTools = state.config.config.experimental |
| 216 | ?.onlyUseSystemMessageTools |
| 217 | ? false |
| 218 | : modelSupportsNativeTools(selectedChatModel); |
| 219 | const systemToolsFramework = !useNativeTools |
| 220 | ? new SystemMessageToolCodeblocksFramework() |
| 221 | : undefined; |
| 222 | |
| 223 | // Construct completion options |
| 224 | let completionOptions: LLMFullCompletionOptions = {}; |
| 225 | if (useNativeTools && activeTools.length > 0) { |
| 226 | completionOptions = { |
| 227 | tools: activeTools, |
| 228 | }; |
| 229 | } |
| 230 | |
| 231 | if (state.session.hasReasoningEnabled) { |
| 232 | completionOptions = { |
| 233 | ...completionOptions, |
| 234 | reasoning: true, |
| 235 | reasoningBudgetTokens: |
| 236 | selectedChatModel.completionOptions?.reasoningBudgetTokens ?? 2048, |
| 237 | }; |
| 238 | } |
| 239 | |
| 240 | // Construct messages (excluding system message) |
| 241 | const baseSystemMessage = getBaseSystemMessage( |
| 242 | state.session.mode, |
| 243 | selectedChatModel, |
| 244 | activeTools, |
| 245 | ); |
| 246 | |
| 247 | const systemMessage = systemToolsFramework |
| 248 | ? addSystemMessageToolsToSystemMessage( |
| 249 | systemToolsFramework, |
| 250 | baseSystemMessage, |
| 251 | activeTools, |
| 252 | ) |
| 253 | : baseSystemMessage; |
| 254 | |
| 255 | const withoutMessageIds = state.session.history.map((item) => { |
| 256 | const { id, ...messageWithoutId } = item.message; |
| 257 | return { ...item, message: messageWithoutId }; |
| 258 | }); |
| 259 | |
| 260 | const { messages, appliedRules, appliedRuleIndex } = constructMessages( |
| 261 | withoutMessageIds, |
| 262 | systemMessage, |
| 263 | state.config.config.rules, |
| 264 | state.ui.ruleSettings, |
| 265 | systemToolsFramework, |
| 266 | ); |
| 267 | |
| 268 | // TODO parallel tool calls will cause issues with this |
| 269 | // because there will be multiple tool messages, so which one should have applied rules? |
| 270 | dispatch( |
| 271 | setAppliedRulesAtIndex({ |
| 272 | index: appliedRuleIndex, |
| 273 | appliedRules: appliedRules, |
| 274 | }), |
| 275 | ); |
| 276 | |
| 277 | dispatch(setActive()); |
| 278 | dispatch(setInlineErrorMessage(undefined)); |
| 279 | |
| 280 | const precompiledRes = await extra.ideMessenger.request("llm/compileChat", { |
| 281 | messages, |
| 282 | options: completionOptions, |
| 283 | }); |
| 284 | |
| 285 | if (precompiledRes.status === "error") { |
| 286 | if (precompiledRes.error.includes("Not enough context")) { |
| 287 | dispatch(setInlineErrorMessage("out-of-context")); |
| 288 | dispatch(setInactive()); |
| 289 | return; |
| 290 | } else { |
| 291 | throw new Error(precompiledRes.error); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | const { compiledChatMessages, didPrune, contextPercentage } = |
| 296 | precompiledRes.content; |
| 297 | |
| 298 | dispatch(setIsPruned(didPrune)); |
| 299 | dispatch(setContextPercentage(contextPercentage)); |
| 300 | |
| 301 | // Send request and stream response |
| 302 | const streamAborter = state.session.streamAborter; |
| 303 | let gen = extra.ideMessenger.llmStreamChat( |
| 304 | { |
| 305 | completionOptions, |
| 306 | title: selectedChatModel.title, |
| 307 | messages: compiledChatMessages, |
| 308 | legacySlashCommandData, |
| 309 | messageOptions: { precompiled: true }, |
| 310 | }, |
| 311 | streamAborter.signal, |
| 312 | ); |
| 313 | if (systemToolsFramework && activeTools.length > 0) { |
| 314 | gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework); |
| 315 | } |
| 316 | |
| 317 | let next = await gen.next(); |
| 318 | while (!next.done) { |
| 319 | if (!getState().session.isStreaming) { |
| 320 | dispatch(abortStream()); |
| 321 | break; |
| 322 | } |
| 323 | |
| 324 | dispatch(streamUpdate(next.value)); |
| 325 | next = await gen.next(); |
| 326 | } |
| 327 | |
| 328 | // Attach prompt log and end thinking for reasoning models |
| 329 | if (next.done && next.value) { |
| 330 | dispatch(addPromptCompletionPair([next.value])); |
| 331 | |
| 332 | try { |
| 333 | extra.ideMessenger.post("devdata/log", { |
| 334 | name: "chatInteraction", |
| 335 | data: { |
| 336 | prompt: next.value.prompt, |
| 337 | completion: next.value.completion, |
| 338 | modelProvider: selectedChatModel.underlyingProviderName, |
| 339 | modelName: selectedChatModel.title, |
| 340 | modelTitle: selectedChatModel.title, |
| 341 | sessionId: state.session.id, |
| 342 | ...(!!activeTools.length && { |
| 343 | tools: activeTools.map((tool) => tool.function.name), |
| 344 | }), |
| 345 | ...(appliedRules.length > 0 && { |
| 346 | rules: appliedRules.map((rule) => ({ |
| 347 | id: getRuleId(rule), |
| 348 | rule: rule.rule, |
| 349 | slug: rule.slug, |
| 350 | })), |
| 351 | }), |
| 352 | }, |
| 353 | }); |
| 354 | } catch (e) { |
| 355 | console.error("Failed to send dev data interaction log", e); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // Check if we have any tool calls that were just generated |
| 360 | const newState = getState(); |
| 361 | const toolSettings = newState.ui.toolSettings; |
| 362 | const allToolCallStates = selectCurrentToolCalls(newState); |
| 363 | |
| 364 | await Promise.all( |
| 365 | allToolCallStates.map((tcState) => |
| 366 | enhanceParsedArgs( |
| 367 | extra.ideMessenger, |
| 368 | dispatch, |
| 369 | tcState?.toolCall.function.name, |
| 370 | tcState.toolCallId, |
| 371 | tcState.parsedArgs, |
| 372 | ), |
| 373 | ), |
| 374 | ); |
| 375 | |
| 376 | // Handle tool call execution if there are any generating tool calls |
| 377 | const allAutoApproved = await handleToolCallExecution( |
| 378 | dispatch, |
| 379 | getState, |
| 380 | activeTools, |
| 381 | extra.ideMessenger, |
| 382 | ); |
| 383 | |
| 384 | // Only set inactive if not all tools were auto-approved |
| 385 | // This prevents UI flashing for auto-approved tools |
| 386 | if (!allAutoApproved) { |
| 387 | dispatch(setInactive()); |
| 388 | } |
| 389 | }, |
| 390 | ); |