| 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 3 | import type { ChatHistoryItem } from "core/index.js"; |
| 4 | import React from "react"; |
| 5 | |
| 6 | import { compactChatHistory } from "../compaction.js"; |
| 7 | import { updateSessionHistory } from "../session.js"; |
| 8 | import { formatError } from "../util/formatError.js"; |
| 9 | import { logger } from "../util/logger.js"; |
| 10 | import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js"; |
| 11 | |
| 12 | interface AutoCompactionCallbacks { |
| 13 | // For streaming mode |
| 14 | onSystemMessage?: (message: string) => void; |
| 15 | onContent?: (content: string) => void; |
| 16 | |
| 17 | // For TUI mode |
| 18 | setMessages?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 19 | setChatHistory?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 20 | setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>; |
| 21 | |
| 22 | // For headless mode - no callbacks needed, just return values |
| 23 | } |
| 24 | |
| 25 | interface AutoCompactionOptions { |
| 26 | isHeadless?: boolean; |
| 27 | format?: "json"; |
| 28 | callbacks?: AutoCompactionCallbacks; |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Notify user about compaction start |
| 33 | */ |
| 34 | function notifyCompactionStart( |
| 35 | message: string, |
| 36 | isHeadless: boolean, |
| 37 | callbacks?: AutoCompactionCallbacks, |
| 38 | ) { |
| 39 | if (isHeadless) return; |
| 40 | |
| 41 | if (callbacks?.onSystemMessage) { |
| 42 | callbacks.onSystemMessage(message); |
| 43 | } else if (callbacks?.setMessages) { |
| 44 | // TUI mode - handled by caller |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Handle successful compaction state updates |
| 50 | */ |
| 51 | function handleCompactionSuccess( |
| 52 | result: any, |
| 53 | isHeadless: boolean, |
| 54 | callbacks?: AutoCompactionCallbacks, |
| 55 | ) { |
| 56 | if (isHeadless) return; |
| 57 | |
| 58 | const successMessage = "Chat history auto-compacted successfully."; |
| 59 | |
| 60 | if (callbacks?.onSystemMessage) { |
| 61 | callbacks.onSystemMessage(successMessage); |
| 62 | } else if ( |
| 63 | callbacks?.setMessages && |
| 64 | callbacks?.setChatHistory && |
| 65 | callbacks?.setCompactionIndex |
| 66 | ) { |
| 67 | callbacks.setChatHistory(result.compactedHistory); |
| 68 | callbacks.setCompactionIndex(result.compactionIndex); |
| 69 | callbacks.setMessages((prev: ChatHistoryItem[]) => [ |
| 70 | ...prev, |
| 71 | { |
| 72 | message: { |
| 73 | role: "system", |
| 74 | content: successMessage, |
| 75 | }, |
| 76 | contextItems: [], |
| 77 | }, |
| 78 | ]); |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Handle compaction error notification |
| 84 | */ |
| 85 | function handleCompactionError( |
| 86 | error: any, |
| 87 | isHeadless: boolean, |
| 88 | callbacks?: AutoCompactionCallbacks, |
| 89 | ) { |
| 90 | const errorMessage = `Auto-compaction error: ${formatError(error)}`; |
| 91 | logger.error(errorMessage); |
| 92 | |
| 93 | if (isHeadless) return; |
| 94 | |
| 95 | const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; |
| 96 | |
| 97 | if (callbacks?.onSystemMessage) { |
| 98 | callbacks.onSystemMessage(warningMessage); |
| 99 | } else if (callbacks?.setMessages) { |
| 100 | callbacks.setMessages((prev: ChatHistoryItem[]) => [ |
| 101 | ...prev, |
| 102 | { |
| 103 | message: { |
| 104 | role: "system", |
| 105 | content: warningMessage, |
| 106 | }, |
| 107 | contextItems: [], |
| 108 | }, |
| 109 | ]); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Unified auto-compaction handler for all modes (streaming, TUI, headless) |
| 115 | * @param chatHistory Current chat history |
| 116 | * @param model Model configuration |
| 117 | * @param llmApi LLM API instance |
| 118 | * @param options Configuration options for different usage contexts |
| 119 | * @returns Updated chat history and compaction index, or original if no compaction needed |
| 120 | */ |
| 121 | export async function handleAutoCompaction( |
| 122 | chatHistory: ChatHistoryItem[], |
| 123 | model: ModelConfig, |
| 124 | llmApi: BaseLlmApi, |
| 125 | options: AutoCompactionOptions = {}, |
| 126 | ): Promise<{ |
| 127 | chatHistory: ChatHistoryItem[]; |
| 128 | compactionIndex: number | null; |
| 129 | wasCompacted: boolean; |
| 130 | }> { |
| 131 | const { isHeadless = false, callbacks } = options; |
| 132 | |
| 133 | if (!model || !shouldAutoCompact(chatHistory, model)) { |
| 134 | return { chatHistory, compactionIndex: null, wasCompacted: false }; |
| 135 | } |
| 136 | |
| 137 | logger.info( |
| 138 | `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, |
| 139 | ); |
| 140 | |
| 141 | // Notify about compaction start |
| 142 | notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); |
| 143 | |
| 144 | try { |
| 145 | // Compact the history |
| 146 | const result = await compactChatHistory( |
| 147 | chatHistory, |
| 148 | model, |
| 149 | llmApi, |
| 150 | isHeadless |
| 151 | ? undefined |
| 152 | : { |
| 153 | onStreamContent: callbacks?.onContent, |
| 154 | onStreamComplete: () => {}, |
| 155 | }, |
| 156 | ); |
| 157 | |
| 158 | // Save the compacted session |
| 159 | updateSessionHistory(result.compactedHistory); |
| 160 | |
| 161 | // Handle success notification |
| 162 | handleCompactionSuccess(result, isHeadless, callbacks); |
| 163 | |
| 164 | return { |
| 165 | chatHistory: result.compactedHistory, |
| 166 | compactionIndex: result.compactionIndex, |
| 167 | wasCompacted: true, |
| 168 | }; |
| 169 | } catch (error: any) { |
| 170 | // Handle error notification |
| 171 | handleCompactionError(error, isHeadless, callbacks); |
| 172 | |
| 173 | // Continue without compaction on error |
| 174 | return { chatHistory, compactionIndex: null, wasCompacted: false }; |
| 175 | } |
| 176 | } |