Elffuss BraidHub

kikocis/continue public

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