refactor: apply Single Responsibility Principle to Program.cs and ReplLoop.cs
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.
This commit is contained in:
61
ContextCompactionService.cs
Normal file
61
ContextCompactionService.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user