Elffuss BraidHub

kikocis/continue public

494a780fdb25 · 13.5 KiBRawPermalink
1import { ModelConfig } from "@continuedev/config-yaml";
2import { BaseLlmApi } from "@continuedev/openai-adapters";
3import * as dotenv from "dotenv";
4import type {
5 ChatCompletionMessageParam,
6 ChatCompletionMessageToolCall,
7 ChatCompletionTool,
8} from "openai/resources.mjs";
9
10import { filterExcludedTools } from "./permissions/index.js";
11import {
12 getServiceSync,
13 MCPServiceState,
14 MCPTool,
15 SERVICE_NAMES,
16} from "./services/index.js";
17import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
18import {
19 executeStreamedToolCalls,
20 preprocessStreamedToolCalls,
21 processChunkContent,
22 processToolCallDelta,
23 recordStreamTelemetry,
24 trackFirstTokenTime,
25} from "./streamChatResponse.helpers.js";
26import {
27 getDefaultCompletionOptions,
28 StreamCallbacks,
29} from "./streamChatResponse.types.js";
30import { telemetryService } from "./telemetry/telemetryService.js";
31import { getAllBuiltinTools, ToolCall } from "./tools/index.js";
32import {
33 chatCompletionStreamWithBackoff,
34 withExponentialBackoff,
35} from "./util/exponentialBackoff.js";
36import { logger } from "./util/logger.js";
37
38dotenv.config();
39
40function updateFinalResponse(
41 content: string,
42 shouldContinue: boolean,
43 isHeadless: boolean,
44 currentFinalResponse: string,
45): string {
46 if (!shouldContinue) {
47 return content;
48 } else if (isHeadless && content) {
49 return content;
50 }
51 return currentFinalResponse;
52}
53
54function handleContentDisplay(
55 content: string,
56 callbacks: StreamCallbacks | undefined,
57 isHeadless: boolean,
58): void {
59 // Add newline after content if needed
60 if (!callbacks?.onContent && !isHeadless && content) {
61 logger.info("");
62 }
63
64 // Notify content complete
65 if (content && callbacks?.onContentComplete) {
66 callbacks.onContentComplete(content);
67 }
68}
69
70async function handleToolCalls(
71 toolCalls: ToolCall[],
72 chatHistory: ChatCompletionMessageParam[],
73 content: string,
74 callbacks: StreamCallbacks | undefined,
75 isHeadless: boolean,
76): Promise<boolean> {
77 if (toolCalls.length === 0) {
78 if (content) {
79 chatHistory.push({ role: "assistant", content });
80 }
81 return false;
82 }
83
84 const toolCallsForHistory: ChatCompletionMessageToolCall[] = toolCalls.map(
85 (tc) => ({
86 id: tc.id,
87 type: "function",
88 function: {
89 name: tc.name,
90 arguments: JSON.stringify(tc.arguments),
91 },
92 }),
93 );
94
95 chatHistory.push({
96 role: "assistant",
97 content: content || null,
98 tool_calls: toolCallsForHistory,
99 });
100
101 // First preprocess the tool calls
102 const { preprocessedCalls, errorChatEntries } =
103 await preprocessStreamedToolCalls(toolCalls, callbacks);
104
105 // Add any preprocessing errors to chat history
106 chatHistory.push(...errorChatEntries);
107
108 // Execute the valid preprocessed tool calls
109 const { chatHistoryEntries: toolResults, hasRejection } =
110 await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
111
112 if (isHeadless && hasRejection) {
113 logger.debug(
114 "Tool call rejected in headless mode - returning current content",
115 );
116 return true; // Signal early return needed
117 }
118
119 chatHistory.push(...toolResults);
120 return false;
121}
122
123export async function getAllTools() {
124 // Get all available tool names
125 const allBuiltinTools = getAllBuiltinTools();
126 const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
127
128 let mcpTools: MCPTool[] = [];
129 let mcpToolNames: string[] = [];
130 const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP);
131 if (mcpServiceResult.state === "ready") {
132 mcpTools = mcpServiceResult?.value?.tools ?? [];
133 mcpToolNames = mcpTools.map((t) => t.name);
134 } else {
135 // MCP is lazy
136 // throw new Error("MCP Service not initialized");
137 }
138
139 const allToolNames = [...builtinToolNames, ...mcpToolNames];
140
141 // Check if the ToolPermissionService is ready
142 const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>(
143 SERVICE_NAMES.TOOL_PERMISSIONS,
144 );
145
146 let allowedToolNames: string[];
147 if (
148 permissionsServiceResult.state === "ready" &&
149 permissionsServiceResult.value
150 ) {
151 // Filter out excluded tools based on permissions
152 allowedToolNames = filterExcludedTools(
153 allToolNames,
154 permissionsServiceResult.value.permissions,
155 );
156 } else {
157 // Service not ready - this is a critical error since tools should only be
158 // requested after services are properly initialized
159 logger.error(
160 "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
161 );
162 throw new Error(
163 "ToolPermissionService not initialized. Services must be initialized before requesting tools.",
164 );
165 }
166
167 const allowedToolNamesSet = new Set(allowedToolNames);
168
169 // Filter builtin tools
170 const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
171 allowedToolNamesSet.has(tool.name),
172 );
173
174 const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
175 type: "function" as const,
176 function: {
177 name: tool.name,
178 description: tool.description,
179 parameters: {
180 type: "object",
181 properties: Object.fromEntries(
182 Object.entries(tool.parameters).map(([key, param]) => [
183 key,
184 {
185 type: param.type,
186 description: param.description,
187 items: param.items,
188 },
189 ]),
190 ),
191 required: Object.entries(tool.parameters)
192 .filter(([_, param]) => param.required)
193 .map(([key, _]) => key),
194 },
195 },
196 }));
197
198 // Add filtered MCP tools
199 const allowedMcpTools = mcpTools.filter((tool) =>
200 allowedToolNamesSet.has(tool.name),
201 );
202
203 allTools.push(
204 ...allowedMcpTools.map((tool) => ({
205 type: "function" as const,
206 function: {
207 name: tool.name,
208 description: tool.description,
209 parameters: tool.inputSchema,
210 },
211 })),
212 );
213
214 return allTools;
215}
216
217// Helper function to process a single chunk
218interface ProcessChunkOptions {
219 chunk: any;
220 aiResponse: string;
221 toolCallsMap: Map<string, ToolCall>;
222 indexToIdMap: Map<number, string>;
223 callbacks?: StreamCallbacks;
224 isHeadless?: boolean;
225}
226
227function processChunk(options: ProcessChunkOptions): {
228 aiResponse: string;
229 shouldContinue: boolean;
230} {
231 const {
232 chunk,
233 aiResponse,
234 toolCallsMap,
235 indexToIdMap,
236 callbacks,
237 isHeadless,
238 } = options;
239 // Safety check: ensure chunk has the expected structure
240 if (!chunk.choices || !chunk.choices[0]) {
241 logger.warn("Malformed chunk received - missing choices", { chunk });
242 return { aiResponse, shouldContinue: true };
243 }
244
245 const choice = chunk.choices[0];
246 if (!choice.delta) {
247 logger.warn("Malformed chunk received - missing delta", { chunk });
248 return { aiResponse, shouldContinue: true };
249 }
250
251 let updatedResponse = aiResponse;
252
253 // Handle content streaming
254 if (choice.delta.content) {
255 updatedResponse = processChunkContent(
256 choice.delta.content,
257 aiResponse,
258 callbacks,
259 isHeadless,
260 );
261 }
262
263 // Handle tool calls
264 if (choice.delta.tool_calls) {
265 for (const toolCallDelta of choice.delta.tool_calls) {
266 processToolCallDelta(toolCallDelta, toolCallsMap, indexToIdMap);
267 }
268 }
269
270 return { aiResponse: updatedResponse, shouldContinue: true };
271}
272
273interface ProcessStreamingResponseOptions {
274 chatHistory: ChatCompletionMessageParam[];
275 model: ModelConfig;
276 llmApi: BaseLlmApi;
277 abortController: AbortController;
278 callbacks?: StreamCallbacks;
279 isHeadless?: boolean;
280 tools?: ChatCompletionTool[];
281}
282
283// Process a single streaming response and return whether we need to continue
284export async function processStreamingResponse(
285 options: ProcessStreamingResponseOptions,
286): Promise<{
287 content: string;
288 finalContent: string; // Added field for final content only
289 toolCalls: ToolCall[];
290 shouldContinue: boolean;
291}> {
292 const {
293 chatHistory,
294 model,
295 llmApi,
296 abortController,
297 callbacks,
298 isHeadless,
299 tools,
300 } = options;
301 const requestStartTime = Date.now();
302
303 const streamFactory = async () => {
304 logger.debug("Creating chat completion stream", {
305 model,
306 messageCount: chatHistory.length,
307 toolCount: tools?.length || 0,
308 });
309 return await chatCompletionStreamWithBackoff(
310 llmApi,
311 {
312 model: model.model,
313 messages: chatHistory,
314 stream: true,
315 tools,
316 ...getDefaultCompletionOptions(model.defaultCompletionOptions),
317 },
318 abortController.signal,
319 );
320 };
321
322 let aiResponse = "";
323 let finalContent = "";
324 const toolCallsMap = new Map<string, ToolCall>();
325 const indexToIdMap = new Map<number, string>(); // Track index to ID mapping
326 let firstTokenTime: number | null = null;
327 let inputTokens = 0;
328 let outputTokens = 0;
329
330 try {
331 const streamWithBackoff = withExponentialBackoff(
332 streamFactory,
333 abortController.signal,
334 );
335
336 let chunkCount = 0;
337 for await (const chunk of streamWithBackoff) {
338 chunkCount++;
339
340 logger.debug("Received chunk", { chunkCount, chunk });
341
342 // Track token usage if available
343 if (chunk.usage) {
344 inputTokens = chunk.usage.prompt_tokens || 0;
345 outputTokens = chunk.usage.completion_tokens || 0;
346 }
347
348 // Check if we should abort
349 if (abortController?.signal.aborted) {
350 logger.debug("Stream aborted");
351 break;
352 }
353
354 // Track first token time
355 firstTokenTime = trackFirstTokenTime(
356 firstTokenTime,
357 chunk,
358 requestStartTime,
359 model,
360 tools,
361 );
362
363 const result = processChunk({
364 chunk,
365 aiResponse,
366 toolCallsMap,
367 indexToIdMap,
368 callbacks,
369 isHeadless,
370 });
371 aiResponse = result.aiResponse;
372 if (!result.shouldContinue) break;
373 }
374
375 const responseEndTime = Date.now();
376 const cost = recordStreamTelemetry({
377 requestStartTime,
378 responseEndTime,
379 inputTokens,
380 outputTokens,
381 model,
382 tools,
383 });
384 const totalDuration = responseEndTime - requestStartTime;
385
386 logger.debug("Stream complete", {
387 chunkCount,
388 responseLength: aiResponse.length,
389 toolCallsCount: toolCallsMap.size,
390 inputTokens,
391 outputTokens,
392 cost,
393 duration: totalDuration,
394 });
395 } catch (error: any) {
396 const errorDuration = Date.now() - requestStartTime;
397
398 // Log failed API request
399 telemetryService.logApiRequest({
400 model: model.model,
401 durationMs: errorDuration,
402 success: false,
403 error: error.message || String(error),
404 });
405
406 if (error.name === "AbortError" || abortController?.signal.aborted) {
407 logger.debug("Stream aborted by user");
408 return {
409 content: aiResponse,
410 finalContent: aiResponse,
411 toolCalls: [],
412 shouldContinue: false,
413 };
414 }
415 throw error;
416 }
417
418 const toolCalls = Array.from(toolCallsMap.values());
419
420 // Validate tool calls have complete arguments
421 const validToolCalls = toolCalls.filter((tc) => {
422 if (!tc.arguments || !tc.name) {
423 logger.error("Incomplete tool call", {
424 id: tc.id,
425 name: tc.name,
426 hasArguments: !!tc.arguments,
427 argumentsStr: tc.argumentsStr,
428 });
429 return false;
430 }
431 return true;
432 });
433
434 // Always preserve the content - it should be displayed regardless of tool calls
435 finalContent = aiResponse;
436
437 return {
438 content: aiResponse,
439 finalContent: finalContent,
440 toolCalls: validToolCalls,
441 shouldContinue: validToolCalls.length > 0,
442 };
443}
444
445// Main function that handles the conversation loop
446export async function streamChatResponse(
447 chatHistory: ChatCompletionMessageParam[],
448 model: ModelConfig,
449 llmApi: BaseLlmApi,
450 abortController: AbortController,
451 callbacks?: StreamCallbacks,
452) {
453 logger.debug("streamChatResponse called", {
454 model,
455 historyLength: chatHistory.length,
456 hasCallbacks: !!callbacks,
457 });
458
459 const serviceResult = getServiceSync<ToolPermissionServiceState>(
460 SERVICE_NAMES.TOOL_PERMISSIONS,
461 );
462 const isHeadless = serviceResult.value?.isHeadless ?? false;
463
464 let fullResponse = "";
465 let finalResponse = "";
466
467 while (true) {
468 logger.debug("Starting conversation iteration");
469
470 // Recompute tools on each iteration to handle mode changes during streaming
471 const tools = await getAllTools();
472
473 logger.debug("Tools prepared", {
474 toolCount: tools.length,
475 toolNames: tools.map((t) => t.function.name),
476 });
477
478 // Get response from LLM
479 const { content, toolCalls, shouldContinue } =
480 await processStreamingResponse({
481 chatHistory,
482 model,
483 llmApi,
484 abortController,
485 callbacks,
486 isHeadless,
487 tools,
488 });
489
490 fullResponse += content;
491
492 // Update final response based on mode
493 finalResponse = updateFinalResponse(
494 content,
495 shouldContinue,
496 isHeadless,
497 finalResponse,
498 );
499
500 // Handle content display
501 handleContentDisplay(content, callbacks, isHeadless);
502
503 // Handle tool calls and check for early return
504 const shouldReturn = await handleToolCalls(
505 toolCalls,
506 chatHistory,
507 content,
508 callbacks,
509 isHeadless,
510 );
511
512 if (shouldReturn) {
513 return finalResponse || content || fullResponse;
514 }
515
516 // Check if we should continue
517 if (!shouldContinue) {
518 break;
519 }
520 }
521
522 logger.debug("streamChatResponse complete", {
523 totalResponseLength: fullResponse.length,
524 totalMessages: chatHistory.length,
525 });
526
527 // For headless mode, we return only the final response
528 // Otherwise, return the full response
529 return isHeadless ? finalResponse : fullResponse;
530}