( chatHistory: ChatHistoryItem[], model: ModelConfig, llmApi: BaseLlmApi, abortController: AbortController, callbacks?: StreamCallbacks, isCompacting = false, )
| 421 | // Main function that handles the conversation loop |
| 422 | // eslint-disable-next-line max-params |
| 423 | export async function streamChatResponse( |
| 424 | chatHistory: ChatHistoryItem[], |
| 425 | model: ModelConfig, |
| 426 | llmApi: BaseLlmApi, |
| 427 | abortController: AbortController, |
| 428 | callbacks?: StreamCallbacks, |
| 429 | isCompacting = false, |
| 430 | ) { |
| 431 | logger.debug("streamChatResponse called", { |
| 432 | model, |
| 433 | historyLength: chatHistory.length, |
| 434 | hasCallbacks: !!callbacks, |
| 435 | }); |
| 436 | |
| 437 | const isHeadless = services.toolPermissions.isHeadless(); |
| 438 | |
| 439 | let fullResponse = ""; |
| 440 | let finalResponse = ""; |
| 441 | let compactionOccurredThisTurn = false; // Track if compaction happened during this conversation turn |
| 442 | |
| 443 | while (true) { |
| 444 | // If ChatHistoryService is available, refresh local chatHistory view |
| 445 | chatHistory = refreshChatHistoryFromService(chatHistory, isCompacting); |
| 446 | logger.debug("Starting conversation iteration"); |
| 447 | |
| 448 | // Get system message once per iteration (can change based on tool permissions mode) |
| 449 | const systemMessage = await services.systemMessage.getSystemMessage( |
| 450 | services.toolPermissions.getState().currentMode, |
| 451 | ); |
| 452 | |
| 453 | // Recompute tools on each iteration to handle mode changes during streaming |
| 454 | const rawTools = await getRequestTools(isHeadless); |
| 455 | const tools = applyChatCompletionToolOverrides( |
| 456 | rawTools, |
| 457 | model.chatOptions?.toolOverrides, |
| 458 | ); |
| 459 | |
| 460 | // Pre-API auto-compaction checkpoint (now includes tools) |
| 461 | const preCompactionResult = await handlePreApiCompaction(chatHistory, { |
| 462 | model, |
| 463 | llmApi, |
| 464 | isCompacting, |
| 465 | isHeadless, |
| 466 | callbacks, |
| 467 | systemMessage, |
| 468 | tools, |
| 469 | }); |
| 470 | chatHistory = preCompactionResult.chatHistory; |
| 471 | if (preCompactionResult.wasCompacted) { |
| 472 | compactionOccurredThisTurn = true; |
| 473 | } |
| 474 | |
| 475 | logger.debug("Tools prepared", { |
| 476 | toolCount: tools.length, |
| 477 | toolNames: tools.map((t) => t.function.name), |
| 478 | }); |
| 479 | |
| 480 | // Get response from LLM |
no test coverage detected