Elffuss BraidHub

kikocis/continue public

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