Elffuss BraidHub

kikocis/continue public

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