( chatHistory: ChatHistoryItem[], model: ModelConfig, llmApi: BaseLlmApi, isHeadless: boolean, format?: "json", )
| 220 | |
| 221 | // Helper function to handle auto-compaction for headless mode |
| 222 | async function handleAutoCompaction( |
| 223 | chatHistory: ChatHistoryItem[], |
| 224 | model: ModelConfig, |
| 225 | llmApi: BaseLlmApi, |
| 226 | isHeadless: boolean, |
| 227 | format?: "json", |
| 228 | ): Promise<number | null> { |
| 229 | const { handleAutoCompaction: coreAutoCompaction } = await import( |
| 230 | "../stream/streamChatResponse.autoCompaction.js" |
| 231 | ); |
| 232 | |
| 233 | // Custom callbacks for headless mode console output |
| 234 | const callbacks = { |
| 235 | onSystemMessage: (message: string) => { |
| 236 | if ( |
| 237 | message.includes("Auto-compacting") || |
| 238 | message.includes("Approaching") |
| 239 | ) { |
| 240 | if (!isHeadless) { |
| 241 | console.info(chalk.yellow(`\n${message}`)); |
| 242 | } else if (format === "json") { |
| 243 | safeStdout( |
| 244 | JSON.stringify({ |
| 245 | status: "info", |
| 246 | message: "Auto-compacting triggered", |
| 247 | contextUsage: |
| 248 | calculateContextUsagePercentage( |
| 249 | countChatHistoryTokens( |
| 250 | services.chatHistory.getHistory(), |
| 251 | model, |
| 252 | ), |
| 253 | model, |
| 254 | ) + "%", |
| 255 | }) + "\n", |
| 256 | ); |
| 257 | } |
| 258 | } else if (message.includes("✓")) { |
| 259 | if (!isHeadless) { |
| 260 | console.info(chalk.green(message)); |
| 261 | } else if (format === "json") { |
| 262 | // Omit history length here; service updates occur after compaction completes |
| 263 | safeStdout( |
| 264 | JSON.stringify({ |
| 265 | status: "success", |
| 266 | message: "Auto-compacted successfully", |
| 267 | }) + "\n", |
| 268 | ); |
| 269 | } |
| 270 | } else if (message.includes("Warning:")) { |
| 271 | if (!isHeadless) { |
| 272 | console.error(chalk.red(message)); |
| 273 | console.info(chalk.yellow("Continuing without compaction...")); |
| 274 | } else if (format === "json") { |
| 275 | safeStdout( |
| 276 | JSON.stringify({ |
| 277 | status: "warning", |
| 278 | message: "Auto-compaction failed, continuing without compaction", |
| 279 | }) + "\n", |
no test coverage detected