Elffuss BraidHub

kikocis/continue public

9334ee37bf04 · 4.7 KiBRawPermalink
1import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2import { ContextItem } from "core";
3import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn";
4import posthog from "posthog-js";
5import { callClientTool } from "../../util/clientTools/callClientTool";
6import { selectSelectedChatModel } from "../slices/configSlice";
7import {
8 acceptToolCall,
9 errorToolCall,
10 setInactive,
11 setToolCallCalling,
12 updateToolCallOutput,
13} from "../slices/sessionSlice";
14import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
15import { ThunkApiType } from "../store";
16import { findToolCallById, logToolUsage } from "../util";
17import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
18
19export const callToolById = createAsyncThunk<
20 void,
21 { toolCallId: string },
22 ThunkApiType
23>("chat/callTool", async ({ toolCallId }, { dispatch, extra, getState }) => {
24 const state = getState();
25 const toolCallState = findToolCallById(state.session.history, toolCallId);
26 if (!toolCallState) {
27 console.warn(`Tool call with ID ${toolCallId} not found`);
28 return;
29 }
30
31 if (toolCallState.status !== "generated") {
32 return;
33 }
34
35 // Track tool call acceptance and start timing
36 const startTime = Date.now();
37
38 // Check if this is an auto-approved tool
39 const toolSettings = state.ui.toolSettings;
40 const toolPolicy =
41 toolSettings[toolCallState.toolCall.function.name] ??
42 toolCallState.tool?.defaultToolPolicy ??
43 DEFAULT_TOOL_SETTING;
44 const isAutoApproved = toolPolicy === "allowedWithoutPermission";
45
46 const selectedChatModel = selectSelectedChatModel(state);
47
48 posthog.capture("gui_tool_call_decision", {
49 model: selectedChatModel,
50 decision: isAutoApproved ? "auto_accept" : "accept",
51 toolName: toolCallState.toolCall.function.name,
52 toolCallId: toolCallId,
53 });
54
55 if (!selectedChatModel) {
56 throw new Error("No model selected");
57 }
58
59 dispatch(
60 setToolCallCalling({
61 toolCallId,
62 }),
63 );
64
65 let output: ContextItem[] | undefined = undefined;
66 let errorMessage: string | undefined = undefined;
67 let streamResponse: boolean;
68
69 // IMPORTANT:
70 // Errors that occur while calling tool call implementations
71 // Are caught and passed in output as context items
72 // Errors that occur outside specifically calling the tool
73 // Should not be caught here - should be handled as normal stream errors
74 if (
75 CLIENT_TOOLS_IMPLS.find(
76 (toolName) => toolName === toolCallState.toolCall.function.name,
77 )
78 ) {
79 // Tool is called on client side
80 const {
81 output: clientToolOutput,
82 respondImmediately,
83 errorMessage: clientToolError,
84 } = await callClientTool(toolCallState, {
85 dispatch,
86 ideMessenger: extra.ideMessenger,
87 getState,
88 });
89 output = clientToolOutput;
90 errorMessage = clientToolError;
91 streamResponse = respondImmediately;
92 } else {
93 // Tool is called on core side
94 const result = await extra.ideMessenger.request("tools/call", {
95 toolCall: toolCallState.toolCall,
96 });
97 if (result.status === "error") {
98 throw new Error(result.error);
99 } else {
100 output = result.content.contextItems;
101 errorMessage = result.content.errorMessage;
102 }
103 streamResponse = true;
104 }
105
106 if (errorMessage) {
107 dispatch(
108 updateToolCallOutput({
109 toolCallId,
110 contextItems: [
111 {
112 icon: "problems",
113 name: "Tool Call Error",
114 description: "Tool Call Failed",
115 content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`,
116 hidden: false,
117 },
118 ],
119 }),
120 );
121 } else if (output?.length) {
122 dispatch(
123 updateToolCallOutput({
124 toolCallId,
125 contextItems: output,
126 }),
127 );
128 }
129
130 // Capture telemetry for tool call execution outcome with duration
131 const duration_ms = Date.now() - startTime;
132 posthog.capture("gui_tool_call_outcome", {
133 model: selectedChatModel,
134 succeeded: errorMessage === undefined,
135 toolName: toolCallState.toolCall.function.name,
136 errorMessage: errorMessage,
137 duration_ms: duration_ms,
138 });
139
140 if (streamResponse) {
141 if (errorMessage) {
142 logToolUsage(toolCallState, false, false, extra.ideMessenger, output);
143 dispatch(
144 errorToolCall({
145 toolCallId,
146 }),
147 );
148 } else {
149 logToolUsage(toolCallState, true, true, extra.ideMessenger, output);
150 dispatch(
151 acceptToolCall({
152 toolCallId,
153 }),
154 );
155 }
156
157 // Send to the LLM to continue the conversation
158 const wrapped = await dispatch(
159 streamResponseAfterToolCall({
160 toolCallId,
161 }),
162 );
163 unwrapResult(wrapped);
164 } else {
165 dispatch(setInactive());
166 }
167});