Elffuss BraidHub

kikocis/continue public

59947ce7bb53 · 12.6 KiBRawPermalink
1// Helper functions extracted from streamChatResponse.ts to reduce file size
2
3import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs";
4
5import { checkToolPermission } from "../permissions/permissionChecker.js";
6import { toolPermissionManager } from "../permissions/permissionManager.js";
7import { ToolCallRequest } from "../permissions/types.js";
8import { telemetryService } from "../telemetry/telemetryService.js";
9import { calculateTokenCost } from "../telemetry/utils.js";
10import {
11 executeToolCall,
12 getAllBuiltinTools,
13 getAvailableTools,
14 Tool,
15 validateToolCallArgsPresent,
16} from "../tools/index.js";
17import { PreprocessedToolCall, ToolCall } from "../tools/types.js";
18import { logger } from "../util/logger.js";
19
20import { StreamCallbacks } from "./streamChatResponse.types.js";
21
22// Helper function to handle permission denied
23export function handlePermissionDenied(
24 toolCall: PreprocessedToolCall,
25 chatHistoryEntries: ChatCompletionToolMessageParam[],
26 callbacks?: StreamCallbacks,
27): void {
28 const deniedMessage = `Permission denied by user`;
29 logger.info("Tool call denied", {
30 name: toolCall.name,
31 arguments: toolCall.arguments,
32 });
33
34 chatHistoryEntries.push({
35 role: "tool",
36 tool_call_id: toolCall.id,
37 content: deniedMessage,
38 });
39
40 callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled");
41 logger.debug("Tool call rejected - stopping stream");
42}
43
44// Helper function to handle headless mode permission
45export function handleHeadlessPermission(
46 toolCall: PreprocessedToolCall,
47): never {
48 const allBuiltinTools = getAllBuiltinTools();
49 const tool = allBuiltinTools.find((t) => t.name === toolCall.name);
50 const toolName = tool?.displayName || toolCall.name;
51
52 console.error(
53 `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`,
54 );
55 console.error(`If you want to allow this tool, use --allow ${toolName}.`);
56 console.error(
57 `If you don't want the tool to be included, use --exclude ${toolName}.`,
58 );
59
60 process.exit(1);
61}
62
63// Helper function to request user permission
64export async function requestUserPermission(
65 toolCall: PreprocessedToolCall,
66 callbacks?: StreamCallbacks,
67): Promise<boolean> {
68 if (!callbacks?.onToolPermissionRequest) {
69 return false;
70 }
71
72 const toolCallRequest: ToolCallRequest = {
73 name: toolCall.name,
74 arguments: toolCall.preprocessResult?.args ?? toolCall.arguments,
75 preview: toolCall.preprocessResult?.preview,
76 };
77
78 // Set up listener for permissionRequested event
79 const handlePermissionRequested = (event: {
80 requestId: string;
81 toolCall: ToolCallRequest;
82 }) => {
83 if (event.toolCall.name === toolCall.name) {
84 toolPermissionManager.off(
85 "permissionRequested",
86 handlePermissionRequested,
87 );
88 // Notify UI about permission request
89 callbacks.onToolPermissionRequest!(
90 event.toolCall.name,
91 event.toolCall.arguments,
92 event.requestId,
93 event.toolCall.preview,
94 );
95 }
96 };
97
98 toolPermissionManager.on("permissionRequested", handlePermissionRequested);
99
100 // Request permission using the proper API
101 const permissionResult =
102 await toolPermissionManager.requestPermission(toolCallRequest);
103
104 // Clean up listener in case the condition above was never met
105 // This is a safety net to ensure no listeners are left behind
106 toolPermissionManager.off("permissionRequested", handlePermissionRequested);
107
108 return permissionResult.approved;
109}
110
111// Helper function to check if tool permission is needed
112export async function checkToolPermissionApproval(
113 toolCall: PreprocessedToolCall,
114 callbacks?: StreamCallbacks,
115 isHeadless?: boolean,
116): Promise<boolean> {
117 const permissionCheck = checkToolPermission(toolCall);
118
119 if (permissionCheck.permission === "allow") {
120 return true;
121 } else if (permissionCheck.permission === "ask") {
122 if (isHeadless) {
123 handleHeadlessPermission(toolCall);
124 }
125 return await requestUserPermission(toolCall, callbacks);
126 } else if (permissionCheck.permission === "exclude") {
127 // This shouldn't happen as excluded tools are filtered out earlier
128 return false;
129 }
130
131 return false;
132}
133
134// Helper function to track first token time
135export function trackFirstTokenTime(
136 firstTokenTime: number | null,
137 chunk: any,
138 requestStartTime: number,
139 model: any,
140 tools?: any[],
141): number | null {
142 if (
143 firstTokenTime === null &&
144 chunk.choices?.[0]?.delta &&
145 (chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls)
146 ) {
147 const tokenTime = Date.now();
148 telemetryService.recordResponseTime(
149 tokenTime - requestStartTime,
150 model.model,
151 "time_to_first_token",
152 (tools?.length || 0) > 0,
153 );
154 return tokenTime;
155 }
156 return firstTokenTime;
157}
158
159// Helper function to process content from a chunk
160export function processChunkContent(
161 content: string,
162 aiResponse: string,
163 callbacks?: StreamCallbacks,
164 isHeadless?: boolean,
165): string {
166 const updatedResponse = aiResponse + content;
167
168 if (callbacks?.onContent) {
169 callbacks.onContent(content);
170 } else if (!isHeadless) {
171 process.stdout.write(content);
172 }
173
174 return updatedResponse;
175}
176
177// Helper function to handle tool call delta
178export function processToolCallDelta(
179 toolCallDelta: any,
180 toolCallsMap: Map<string, ToolCall>,
181 indexToIdMap: Map<number, string>,
182): void {
183 let toolCallId: string | undefined;
184
185 // If we have an ID, use it and map the index
186 if (toolCallDelta.id) {
187 toolCallId = toolCallDelta.id;
188 if (toolCallDelta.index !== undefined && toolCallId) {
189 indexToIdMap.set(toolCallDelta.index, toolCallId);
190 }
191 } else if (toolCallDelta.index !== undefined) {
192 // No ID, but we have an index - look up the ID from our map
193 toolCallId = indexToIdMap.get(toolCallDelta.index);
194 }
195
196 if (!toolCallId) {
197 logger.warn("Tool call delta without ID or valid index mapping", {
198 toolCallDelta,
199 });
200 return;
201 }
202
203 // Create tool call entry if it doesn't exist
204 if (!toolCallsMap.has(toolCallId)) {
205 toolCallsMap.set(toolCallId, {
206 id: toolCallId,
207 name: "",
208 arguments: null,
209 argumentsStr: "",
210 startNotified: false,
211 });
212 }
213
214 const toolCall = toolCallsMap.get(toolCallId);
215 if (!toolCall) {
216 logger.warn("Tool call not found in map", { toolCallId });
217 return;
218 }
219
220 // Update name
221 if (toolCallDelta.function?.name) {
222 toolCall.name = toolCallDelta.function.name;
223 }
224
225 // Accumulate arguments
226 if (toolCallDelta.function?.arguments) {
227 toolCall.argumentsStr += toolCallDelta.function.arguments;
228
229 // Try to parse when we might have complete JSON
230 try {
231 toolCall.arguments = JSON.parse(toolCall.argumentsStr);
232 toolCall.startNotified = true;
233 } catch {
234 // JSON not complete yet, continue
235 }
236 }
237}
238
239// Helper function to record telemetry
240export function recordStreamTelemetry(options: {
241 requestStartTime: number;
242 responseEndTime: number;
243 inputTokens: number;
244 outputTokens: number;
245 model: any;
246 tools?: any[];
247}): number {
248 const {
249 requestStartTime,
250 responseEndTime,
251 inputTokens,
252 outputTokens,
253 model,
254 tools,
255 } = options;
256 const totalDuration = responseEndTime - requestStartTime;
257 const cost = calculateTokenCost(inputTokens, outputTokens, model.model);
258
259 telemetryService.recordTokenUsage(inputTokens, "input", model.model);
260 telemetryService.recordTokenUsage(outputTokens, "output", model.model);
261 telemetryService.recordCost(cost, model.model);
262
263 telemetryService.recordResponseTime(
264 totalDuration,
265 model.model,
266 "total_response_time",
267 (tools?.length || 0) > 0,
268 );
269
270 telemetryService.logApiRequest({
271 model: model.model,
272 durationMs: totalDuration,
273 success: true,
274 inputTokens,
275 outputTokens,
276 costUsd: cost,
277 });
278
279 return cost;
280}
281
282/**
283 * Processes tool calls by validating and preprocessing them
284 * @param toolCalls - The raw tool calls from the LLM
285 * @param callbacks - Optional callbacks for notifying of events
286 * @returns - Preprocessed tool calls that are ready for execution
287 */
288export async function preprocessStreamedToolCalls(
289 toolCalls: ToolCall[],
290 callbacks?: StreamCallbacks,
291): Promise<{
292 preprocessedCalls: PreprocessedToolCall[];
293 errorChatEntries: ChatCompletionToolMessageParam[];
294}> {
295 const preprocessedCalls: PreprocessedToolCall[] = [];
296 const errorChatEntries: ChatCompletionToolMessageParam[] = [];
297
298 // Get all available tools
299 const availableTools: Tool[] = await getAvailableTools();
300
301 // Process each tool call
302 for (const toolCall of toolCalls) {
303 const startTime = Date.now();
304 try {
305 const tool = availableTools.find((t) => t.name === toolCall.name);
306 if (!tool) {
307 throw new Error(`Tool ${toolCall.name} not found`);
308 }
309
310 validateToolCallArgsPresent(toolCall, tool);
311
312 const preprocessedCall: PreprocessedToolCall = {
313 ...toolCall,
314 tool,
315 };
316
317 if (tool.preprocess) {
318 logger.debug("Preprocessing tool call args", {
319 name: toolCall.name,
320 arguments: toolCall.arguments,
321 });
322 const preprocessed = await tool.preprocess(toolCall.arguments);
323 preprocessedCall.preprocessResult = preprocessed;
324 }
325
326 preprocessedCalls.push(preprocessedCall);
327 } catch (error) {
328 // Notify the UI about the tool start, even though it failed
329 callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
330
331 const errorMessage =
332 error instanceof Error ? error.message : String(error);
333
334 logger.error("Invalid tool call", {
335 name: toolCall.name,
336 error: errorMessage,
337 });
338
339 const duration = Date.now() - startTime;
340 telemetryService.logToolResult({
341 toolName: toolCall.name,
342 success: false,
343 durationMs: duration,
344 error: errorMessage,
345 });
346
347 // Add error to chat history
348 errorChatEntries.push({
349 role: "tool",
350 tool_call_id: toolCall.id,
351 content: errorMessage,
352 });
353
354 // Notify about the error
355 callbacks?.onToolError?.(errorMessage, toolCall.name);
356 }
357 }
358
359 return { preprocessedCalls, errorChatEntries };
360}
361
362/**
363 * Executes preprocessed tool calls, handling permissions and results
364 * @param preprocessedCalls - The preprocessed tool calls ready for execution
365 * @param callbacks - Optional callbacks for notifying of events
366 * @returns - Chat history entries with tool results
367 */
368export async function executeStreamedToolCalls(
369 preprocessedCalls: PreprocessedToolCall[],
370 callbacks?: StreamCallbacks,
371 isHeadless?: boolean,
372): Promise<{
373 hasRejection: boolean;
374 chatHistoryEntries: ChatCompletionToolMessageParam[];
375}> {
376 const chatHistoryEntries: ChatCompletionToolMessageParam[] = [];
377 let hasRejection = false;
378
379 // Execute each preprocessed tool call
380 for (const toolCall of preprocessedCalls) {
381 if (hasRejection) {
382 const cancelledMessage = `Cancelled due to previous tool rejection`;
383 chatHistoryEntries.push({
384 role: "tool",
385 tool_call_id: toolCall.id,
386 content: cancelledMessage,
387 });
388
389 callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled");
390 continue;
391 }
392
393 // Handle remaining tool calls in this batch to maintain chat history consistency
394 try {
395 logger.debug("Checking tool permissions", {
396 name: toolCall.name,
397 arguments: toolCall.arguments,
398 });
399
400 // Notify tool start - before permission check
401 // This ensures the UI shows the tool call even if it's rejected
402 callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
403
404 // Check tool permissions using helper
405 const approved = await checkToolPermissionApproval(
406 toolCall,
407 callbacks,
408 isHeadless,
409 );
410
411 if (!approved) {
412 handlePermissionDenied(toolCall, chatHistoryEntries, callbacks);
413 hasRejection = true;
414 continue;
415 }
416
417 logger.debug("Executing tool", {
418 name: toolCall.name,
419 arguments: toolCall.arguments,
420 });
421
422 const toolResult = await executeToolCall(toolCall);
423
424 chatHistoryEntries.push({
425 role: "tool",
426 tool_call_id: toolCall.id,
427 content: toolResult,
428 });
429
430 callbacks?.onToolResult?.(toolResult, toolCall.name, "done");
431 } catch (error) {
432 const errorMessage = `Error executing tool ${toolCall.name}: ${
433 error instanceof Error ? error.message : String(error)
434 }`;
435
436 logger.error("Tool execution failed", {
437 name: toolCall.name,
438 error: errorMessage,
439 });
440
441 chatHistoryEntries.push({
442 role: "tool",
443 tool_call_id: toolCall.id,
444 content: errorMessage,
445 });
446
447 callbacks?.onToolError?.(errorMessage, toolCall.name);
448 }
449 }
450
451 return {
452 hasRejection,
453 chatHistoryEntries,
454 };
455}