Elffuss BraidHub

kikocis/continue public

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