Elffuss BraidHub

kikocis/continue public

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