Elffuss BraidHub

kikocis/continue public

c04584525d2e · 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 { ThunkApiType } from "../store";
15import { findToolCallById, logToolUsage } from "../util";
16import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
17import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
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 posthog.capture("gui_tool_call_decision", {
47 decision: isAutoApproved ? "auto_accept" : "accept",
48 toolName: toolCallState.toolCall.function.name,
49 toolCallId: toolCallId,
50 });
51
52 const selectedChatModel = selectSelectedChatModel(state);
53
54 if (!selectedChatModel) {
55 throw new Error("No model selected");
56 }
57
58 dispatch(
59 setToolCallCalling({
60 toolCallId,
61 }),
62 );
63
64 let output: ContextItem[] | undefined = undefined;
65 let errorMessage: string | undefined = undefined;
66 let streamResponse: boolean;
67
68 // IMPORTANT:
69 // Errors that occur while calling tool call implementations
70 // Are caught and passed in output as context items
71 // Errors that occur outside specifically calling the tool
72 // Should not be caught here - should be handled as normal stream errors
73 if (
74 CLIENT_TOOLS_IMPLS.find(
75 (toolName) => toolName === toolCallState.toolCall.function.name,
76 )
77 ) {
78 // Tool is called on client side
79 const {
80 output: clientToolOutput,
81 respondImmediately,
82 errorMessage: clientToolError,
83 } = await callClientTool(toolCallState, {
84 dispatch,
85 ideMessenger: extra.ideMessenger,
86 getState,
87 });
88 output = clientToolOutput;
89 errorMessage = clientToolError;
90 streamResponse = respondImmediately;
91 } else {
92 // Tool is called on core side
93 const result = await extra.ideMessenger.request("tools/call", {
94 toolCall: toolCallState.toolCall,
95 });
96 if (result.status === "error") {
97 throw new Error(result.error);
98 } else {
99 output = result.content.contextItems;
100 errorMessage = result.content.errorMessage;
101 }
102 streamResponse = true;
103 }
104
105 if (errorMessage) {
106 dispatch(
107 updateToolCallOutput({
108 toolCallId,
109 contextItems: [
110 {
111 icon: "problems",
112 name: "Tool Call Error",
113 description: "Tool Call Failed",
114 content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`,
115 hidden: false,
116 },
117 ],
118 }),
119 );
120 } else if (output?.length) {
121 dispatch(
122 updateToolCallOutput({
123 toolCallId,
124 contextItems: output,
125 }),
126 );
127 }
128
129 // Capture telemetry for tool call execution outcome with duration
130 const duration_ms = Date.now() - startTime;
131 posthog.capture("gui_tool_call_outcome", {
132 succeeded: errorMessage === undefined,
133 toolName: toolCallState.toolCall.function.name,
134 errorMessage: errorMessage,
135 duration_ms: duration_ms,
136 });
137
138 if (streamResponse) {
139 if (errorMessage) {
140 logToolUsage(toolCallState, false, false, extra.ideMessenger, output);
141 dispatch(
142 errorToolCall({
143 toolCallId,
144 }),
145 );
146 } else {
147 logToolUsage(toolCallState, true, true, extra.ideMessenger, output);
148 dispatch(
149 acceptToolCall({
150 toolCallId,
151 }),
152 );
153 }
154
155 // Send to the LLM to continue the conversation
156 const wrapped = await dispatch(
157 streamResponseAfterToolCall({
158 toolCallId,
159 }),
160 );
161 unwrapResult(wrapped);
162 } else {
163 dispatch(setInactive());
164 }
165});