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