Elffuss BraidHub

kikocis/continue public

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