module LittleGhost::Agent::ContextManagement

Keep long conversations within the model’s available context window. The capability summarizes older turns while preserving trusted instructions and recent messages.

class CustomerSupportAgent < LittleGhost::Agent
  manage_context compression_threshold: 0.75,
    preserve_recent_messages: 12
end

As a support thread reaches the threshold, the next model request contains a generated summary and targets retaining its 12 most recent conversation messages. System and developer messages remain intact, and tool-use/result pairs are never split merely to hit the requested count.

A message whose metadata sets PINNED_METADATA_KEY is never summarized away. true pins it for good; an agent operation id pins it only during that invocation. Pinned messages, with the other half of any tool-use/result pair, stay verbatim ahead of the summary and still count toward the window. Each invocation’s request is pinned this way unless +preserve_invocation_request: false+ is declared.

The summary’s metadata lists, under SUMMARIZED_METADATA_KEY, the scalar metadata of every message it replaced, including those replaced by earlier summaries, so applications can tell compacted messages from new ones.

Context management is inactive until manage_context is declared. The configured window is a fallback: provider metadata takes precedence when it advertises a positive context-window size. Compaction uses the current model with the request’s settings, cancellation token, and deadline.

Request size is estimated at four characters per token. Once the provider reports input usage, including cache reads and writes, a request that extends the measured one is sized from that report plus an estimate for the added messages, whichever is larger. Dense content such as identifiers, numbers, and escaped JSON then still compacts before the provider rejects it.

Proactive compaction failures leave the original request unchanged and emit diagnostic instrumentation. A provider context-overflow error triggers one compaction replacement through the model-error callback; cancellation, deadlines, and cleanup failures still escape as control flow.