Elffuss BraidHub

kikocis/continue public

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