Elffuss BraidHub

kikocis/continue public

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