extracted responsibilities from Program.cs (208→46 lines) and ReplLoop.cs (274→174 lines) into focused service classes: HeaderRenderer, SessionManager, ApplicationStartup, ResponseStreamer, SpinnerService, UsageDisplayer, and ContextCompactionService. Each class now has a single, well-defined responsibility, improving testability and maintainability.
62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using Microsoft.Extensions.AI;
|
|
using Spectre.Console;
|
|
using AnchorCli.OpenRouter;
|
|
|
|
namespace AnchorCli;
|
|
|
|
/// <summary>
|
|
/// Handles context compaction when the conversation approaches token limits.
|
|
/// </summary>
|
|
internal sealed class ContextCompactionService
|
|
{
|
|
private readonly ContextCompactor _compactor;
|
|
private readonly List<ChatMessage> _history;
|
|
private readonly TokenTracker _tokenTracker;
|
|
|
|
public ContextCompactionService(
|
|
ContextCompactor compactor,
|
|
List<ChatMessage> history,
|
|
TokenTracker tokenTracker)
|
|
{
|
|
_compactor = compactor;
|
|
_history = history;
|
|
_tokenTracker = tokenTracker;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Checks if compaction is needed and performs it if so.
|
|
/// Returns true if compaction was performed.
|
|
/// </summary>
|
|
public async Task<bool> TryCompactAsync()
|
|
{
|
|
if (!_tokenTracker.ShouldCompact())
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var pct = _tokenTracker.ContextUsagePercent;
|
|
AnsiConsole.MarkupLine(
|
|
$"[yellow]⚠ Context at {pct:F0}% — compacting conversation history...[/]");
|
|
|
|
bool compacted = await AnsiConsole.Status()
|
|
.Spinner(Spinner.Known.BouncingBar)
|
|
.SpinnerStyle(Style.Parse("yellow"))
|
|
.StartAsync("Compacting context...", async ctx =>
|
|
await _compactor.TryCompactAsync(_history, default));
|
|
|
|
if (compacted)
|
|
{
|
|
AnsiConsole.MarkupLine(
|
|
$"[green]✓ Context compacted ({_history.Count} messages remaining)[/]");
|
|
}
|
|
else
|
|
{
|
|
AnsiConsole.MarkupLine(
|
|
"[dim grey] (compaction skipped — not enough history to compress)[/]");
|
|
}
|
|
|
|
AnsiConsole.WriteLine();
|
|
return compacted;
|
|
}
|
|
}
|