Elffuss BraidHub

kikocis/continue public

88b8936f200c · 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);
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 = `Error processing tool call: ${
331 error instanceof Error ? error.message : String(error)
332 }`;
333
334 logger.error("Invalid tool call", {
335 name: toolCall.name,
336 error: errorMessage,
337 });
338
339 const duration = Date.now() - startTime;
340 telemetryService.logToolResult({
341 toolName: toolCall.name,
342 success: false,
343 durationMs: duration,
344 error: errorMessage,
345 });
346
347 // Add error to chat history
348 errorChatEntries.push({
349 role: "tool",
350 tool_call_id: toolCall.id,
351 content: errorMessage,
352 });
353
354 // Notify about the error
355 callbacks?.onToolError?.(errorMessage, toolCall.name);
356 }
357 }
358
359 return { preprocessedCalls, errorChatEntries };
360}
361
362/**
363 * Executes preprocessed tool calls, handling permissions and results
364 * @param preprocessedCalls - The preprocessed tool calls ready for execution
365 * @param callbacks - Optional callbacks for notifying of events
366 * @returns - Chat history entries with tool results
367 */
368export async function executeStreamedToolCalls(
369 preprocessedCalls: PreprocessedToolCall[],
370 callbacks?: StreamCallbacks,
371 isHeadless?: boolean,
372): Promise<{
373 hasRejection: boolean;
374 chatHistoryEntries: ChatCompletionToolMessageParam[];
375}> {
376 const chatHistoryEntries: ChatCompletionToolMessageParam[] = [];
377 let hasRejection = false;
378
379 // Execute each preprocessed tool call
380 for (const toolCall of preprocessedCalls) {
381 if (hasRejection) {
382 const cancelledMessage = `Cancelled due to previous tool rejection`;
383 chatHistoryEntries.push({
384 role: "tool",
385 tool_call_id: toolCall.id,
386 content: cancelledMessage,
387 });
388
389 callbacks?.onToolResult?.(cancelledMessage, toolCall.name);
390 continue;
391 }
392
393 // Handle remaining tool calls in this batch to maintain chat history consistency
394 try {
395 logger.debug("Checking tool permissions", {
396 name: toolCall.name,
397 arguments: toolCall.arguments,
398 });
399
400 // Notify tool start - before permission check
401 // This ensures the UI shows the tool call even if it's rejected
402 callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
403
404 // Check tool permissions using helper
405 const approved = await checkToolPermissionApproval(
406 toolCall,
407 callbacks,
408 isHeadless,
409 );
410
411 if (!approved) {
412 handlePermissionDenied(toolCall, chatHistoryEntries, callbacks);
413 hasRejection = true;
414 continue;
415 }
416
417 logger.debug("Executing tool", {
418 name: toolCall.name,
419 arguments: toolCall.arguments,
420 });
421
422 const toolResult = await executeToolCall(toolCall);
423
424 chatHistoryEntries.push({
425 role: "tool",
426 tool_call_id: toolCall.id,
427 content: toolResult,
428 });
429
430 callbacks?.onToolResult?.(toolResult, toolCall.name);
431 } catch (error) {
432 const errorMessage = `Error executing tool ${toolCall.name}: ${
433 error instanceof Error ? error.message : String(error)
434 }`;
435
436 logger.error("Tool execution failed", {
437 name: toolCall.name,
438 error: errorMessage,
439 });
440
441 chatHistoryEntries.push({
442 role: "tool",
443 tool_call_id: toolCall.id,
444 content: errorMessage,
445 });
446
447 callbacks?.onToolError?.(errorMessage, toolCall.name);
448 }
449 }
450
451 return {
452 hasRejection,
453 chatHistoryEntries,
454 };
455}