Elffuss BraidHub

kikocis/continue public

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