Elffuss BraidHub

kikocis/continue public

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