| 1 | import { ToolPolicy } from "@continuedev/terminal-security"; |
| 2 | import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; |
| 3 | import { |
| 4 | LLMFullCompletionOptions, |
| 5 | ModelDescription, |
| 6 | Tool, |
| 7 | ToolCallState, |
| 8 | } from "core"; |
| 9 | import { getRuleId } from "core/llm/rules/getSystemMessageWithRules"; |
| 10 | import { ToCoreProtocol } from "core/protocol"; |
| 11 | import { IIdeMessenger } from "../../context/IdeMessenger"; |
| 12 | import { selectActiveTools } from "../selectors/selectActiveTools"; |
| 13 | import { selectSelectedChatModel } from "../slices/configSlice"; |
| 14 | import { |
| 15 | abortStream, |
| 16 | addPromptCompletionPair, |
| 17 | errorToolCall, |
| 18 | setActive, |
| 19 | setAppliedRulesAtIndex, |
| 20 | setContextPercentage, |
| 21 | setInactive, |
| 22 | setInlineErrorMessage, |
| 23 | setIsPruned, |
| 24 | setToolGenerated, |
| 25 | streamUpdate, |
| 26 | updateToolCallOutput, |
| 27 | } from "../slices/sessionSlice"; |
| 28 | import { AppThunkDispatch, RootState, ThunkApiType } from "../store"; |
| 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 | /** |
| 196 | * Builds completion options with reasoning configuration based on session state and model capabilities. |
| 197 | * |
| 198 | * @param baseOptions - Base completion options to extend |
| 199 | * @param hasReasoningEnabled - Whether reasoning is enabled in the session |
| 200 | * @param model - The selected model with provider and completion options |
| 201 | * @returns Completion options with reasoning configuration |
| 202 | */ |
| 203 | function buildReasoningCompletionOptions( |
| 204 | baseOptions: LLMFullCompletionOptions, |
| 205 | hasReasoningEnabled: boolean | undefined, |
| 206 | model: ModelDescription, |
| 207 | ): LLMFullCompletionOptions { |
| 208 | if (hasReasoningEnabled === undefined) { |
| 209 | return baseOptions; |
| 210 | } |
| 211 | |
| 212 | const reasoningOptions: LLMFullCompletionOptions = { |
| 213 | ...baseOptions, |
| 214 | reasoning: !!hasReasoningEnabled, |
| 215 | }; |
| 216 | |
| 217 | // Add reasoning budget tokens if reasoning is enabled and provider supports it |
| 218 | if (hasReasoningEnabled && model.underlyingProviderName !== "ollama") { |
| 219 | // Ollama doesn't support limiting reasoning tokens at this point |
| 220 | reasoningOptions.reasoningBudgetTokens = |
| 221 | model.completionOptions?.reasoningBudgetTokens ?? 2048; |
| 222 | } |
| 223 | |
| 224 | return reasoningOptions; |
| 225 | } |
| 226 | |
| 227 | export const streamNormalInput = createAsyncThunk< |
| 228 | void, |
| 229 | { |
| 230 | legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"]; |
| 231 | }, |
| 232 | ThunkApiType |
| 233 | >( |
| 234 | "chat/streamNormalInput", |
| 235 | async ({ legacySlashCommandData }, { dispatch, extra, getState }) => { |
| 236 | const state = getState(); |
| 237 | const selectedChatModel = selectSelectedChatModel(state); |
| 238 | |
| 239 | if (!selectedChatModel) { |
| 240 | throw new Error("No chat model selected"); |
| 241 | } |
| 242 | |
| 243 | // Get tools and filter them based on the selected model |
| 244 | const activeTools = selectActiveTools(state); |
| 245 | |
| 246 | // Use the centralized selector to determine if system message tools should be used |
| 247 | const useNativeTools = state.config.config.experimental |
| 248 | ?.onlyUseSystemMessageTools |
| 249 | ? false |
| 250 | : modelSupportsNativeTools(selectedChatModel); |
| 251 | const systemToolsFramework = !useNativeTools |
| 252 | ? new SystemMessageToolCodeblocksFramework() |
| 253 | : undefined; |
| 254 | |
| 255 | // Construct completion options |
| 256 | let completionOptions: LLMFullCompletionOptions = {}; |
| 257 | if (useNativeTools && activeTools.length > 0) { |
| 258 | completionOptions = { |
| 259 | tools: activeTools, |
| 260 | }; |
| 261 | } |
| 262 | |
| 263 | completionOptions = buildReasoningCompletionOptions( |
| 264 | completionOptions, |
| 265 | state.session.hasReasoningEnabled, |
| 266 | selectedChatModel, |
| 267 | ); |
| 268 | |
| 269 | // Construct messages (excluding system message) |
| 270 | const baseSystemMessage = getBaseSystemMessage( |
| 271 | state.session.mode, |
| 272 | selectedChatModel, |
| 273 | activeTools, |
| 274 | ); |
| 275 | |
| 276 | const systemMessage = systemToolsFramework |
| 277 | ? addSystemMessageToolsToSystemMessage( |
| 278 | systemToolsFramework, |
| 279 | baseSystemMessage, |
| 280 | activeTools, |
| 281 | ) |
| 282 | : baseSystemMessage; |
| 283 | |
| 284 | const withoutMessageIds = state.session.history.map((item) => { |
| 285 | const { id, ...messageWithoutId } = item.message; |
| 286 | return { ...item, message: messageWithoutId }; |
| 287 | }); |
| 288 | |
| 289 | const { messages, appliedRules, appliedRuleIndex } = constructMessages( |
| 290 | withoutMessageIds, |
| 291 | systemMessage, |
| 292 | state.config.config.rules, |
| 293 | state.ui.ruleSettings, |
| 294 | systemToolsFramework, |
| 295 | ); |
| 296 | |
| 297 | // TODO parallel tool calls will cause issues with this |
| 298 | // because there will be multiple tool messages, so which one should have applied rules? |
| 299 | dispatch( |
| 300 | setAppliedRulesAtIndex({ |
| 301 | index: appliedRuleIndex, |
| 302 | appliedRules: appliedRules, |
| 303 | }), |
| 304 | ); |
| 305 | |
| 306 | dispatch(setActive()); |
| 307 | dispatch(setInlineErrorMessage(undefined)); |
| 308 | |
| 309 | const precompiledRes = await extra.ideMessenger.request("llm/compileChat", { |
| 310 | messages, |
| 311 | options: completionOptions, |
| 312 | }); |
| 313 | |
| 314 | if (precompiledRes.status === "error") { |
| 315 | if (precompiledRes.error.includes("Not enough context")) { |
| 316 | dispatch(setInlineErrorMessage("out-of-context")); |
| 317 | dispatch(setInactive()); |
| 318 | return; |
| 319 | } else { |
| 320 | throw new Error(precompiledRes.error); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | const { compiledChatMessages, didPrune, contextPercentage } = |
| 325 | precompiledRes.content; |
| 326 | |
| 327 | dispatch(setIsPruned(didPrune)); |
| 328 | dispatch(setContextPercentage(contextPercentage)); |
| 329 | |
| 330 | // Send request and stream response |
| 331 | const streamAborter = state.session.streamAborter; |
| 332 | let gen = extra.ideMessenger.llmStreamChat( |
| 333 | { |
| 334 | completionOptions, |
| 335 | title: selectedChatModel.title, |
| 336 | messages: compiledChatMessages, |
| 337 | legacySlashCommandData, |
| 338 | messageOptions: { precompiled: true }, |
| 339 | }, |
| 340 | streamAborter.signal, |
| 341 | ); |
| 342 | if (systemToolsFramework && activeTools.length > 0) { |
| 343 | gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework); |
| 344 | } |
| 345 | |
| 346 | let next = await gen.next(); |
| 347 | while (!next.done) { |
| 348 | if (!getState().session.isStreaming) { |
| 349 | dispatch(abortStream()); |
| 350 | break; |
| 351 | } |
| 352 | |
| 353 | dispatch(streamUpdate(next.value)); |
| 354 | next = await gen.next(); |
| 355 | } |
| 356 | |
| 357 | // Attach prompt log and end thinking for reasoning models |
| 358 | if (next.done && next.value) { |
| 359 | dispatch(addPromptCompletionPair([next.value])); |
| 360 | |
| 361 | try { |
| 362 | extra.ideMessenger.post("devdata/log", { |
| 363 | name: "chatInteraction", |
| 364 | data: { |
| 365 | prompt: next.value.prompt, |
| 366 | completion: next.value.completion, |
| 367 | modelProvider: selectedChatModel.underlyingProviderName, |
| 368 | modelName: selectedChatModel.title, |
| 369 | modelTitle: selectedChatModel.title, |
| 370 | sessionId: state.session.id, |
| 371 | ...(!!activeTools.length && { |
| 372 | tools: activeTools.map((tool) => tool.function.name), |
| 373 | }), |
| 374 | ...(appliedRules.length > 0 && { |
| 375 | rules: appliedRules.map((rule) => ({ |
| 376 | id: getRuleId(rule), |
| 377 | rule: rule.rule, |
| 378 | slug: rule.slug, |
| 379 | })), |
| 380 | }), |
| 381 | }, |
| 382 | }); |
| 383 | } catch (e) { |
| 384 | console.error("Failed to send dev data interaction log", e); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // Check if we have any tool calls that were just generated |
| 389 | const newState = getState(); |
| 390 | const toolSettings = newState.ui.toolSettings; |
| 391 | const allToolCallStates = selectCurrentToolCalls(newState); |
| 392 | |
| 393 | await Promise.all( |
| 394 | allToolCallStates.map((tcState) => |
| 395 | enhanceParsedArgs( |
| 396 | extra.ideMessenger, |
| 397 | dispatch, |
| 398 | tcState?.toolCall.function.name, |
| 399 | tcState.toolCallId, |
| 400 | tcState.parsedArgs, |
| 401 | ), |
| 402 | ), |
| 403 | ); |
| 404 | |
| 405 | // Handle tool call execution if there are any generating tool calls |
| 406 | const allAutoApproved = await handleToolCallExecution( |
| 407 | dispatch, |
| 408 | getState, |
| 409 | activeTools, |
| 410 | extra.ideMessenger, |
| 411 | ); |
| 412 | |
| 413 | // Only set inactive if not all tools were auto-approved |
| 414 | // This prevents UI flashing for auto-approved tools |
| 415 | if (!allAutoApproved) { |
| 416 | dispatch(setInactive()); |
| 417 | } |
| 418 | }, |
| 419 | ); |