Elffuss BraidHub

kikocis/continue public

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