Elffuss BraidHub

kikocis/continue public

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