Search by

adachsoft / ai-agent-context-tool-window-compaction

Arkadiusz Adach

Tool-window compaction strategy for AdachSoft AiAgent conversation context (archive old tool-calls into placeholders while protecting recent messages)

Package info

gitlab.com/a.adach/ai-agent-context-tool-window-compaction

Issues

pkg:composer/adachsoft/ai-agent-context-tool-window-compaction

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

v0.1.0 2026-11-27 00:46 UTC

This package is auto-updated.

Last update: 2026-11-26 23:47:12 UTC


README

Tool-window compaction strategy for adachsoft/ai-agent.

Overview

This package provides ToolWindowCompactionConversationContextStrategy – a conversation context strategy that:

  • Uses a hysteresis-based window: below a trigger size it only applies inner compaction, above it starts archiving old tool interactions.
  • Preserves a fresh window of recent messages while archiving older tool-calling blocks into compact placeholders.
  • Guarantees tool-calling integrity by dynamically adjusting the window boundary (never splits a call/result pair).
  • Delegates the merged archive + fresh window to the configured inner strategy when byte epochs are disabled; with epochs enabled, uses package-local epoch-aware trimming compatible with the default inner strategy.

Constructors of the strategy and internal collaborators are a hard BC break. Create the strategy only through ToolWindowCompactionConversationContextStrategyFactory.

Requirements

  • PHP 8.3 or later
  • Composer

Installation

Install the package with Composer:

composer require adachsoft/ai-agent-context-tool-window-compaction

Usage

use AdachSoft\AiAgentContextToolWindowCompaction\Enum\ArchivePlaceholderModeEnum;
use AdachSoft\AiAgentContextToolWindowCompaction\Factory\ToolWindowCompactionConversationContextStrategyFactory;
use AdachSoft\AiAgentContextToolWindowCompaction\PublicApi\Summary\ToolSummarizerInterfaceCollection;
use AdachSoft\AiAgentContextToolWindowCompaction\ToolWindowCompactionStrategyParams;

$strategy = (new ToolWindowCompactionConversationContextStrategyFactory())->create(
    summarizers: new ToolSummarizerInterfaceCollection([$toolSummarizer]),
    storage: $toolSummaryStorage,
);

$context = $strategy->transform(
    $conversationId,
    $fullConversationCollection,
    [
        ToolWindowCompactionStrategyParams::COMPACTION_TRIGGER_MESSAGE_COUNT => 80,
        ToolWindowCompactionStrategyParams::COMPACTION_TARGET_FRESH_MESSAGE_COUNT => 40,
        ToolWindowCompactionStrategyParams::COMPACTION_TRIGGER_BYTES => 524288,
        ToolWindowCompactionStrategyParams::COMPACTION_TARGET_FRESH_BYTES => 196608,
        ToolWindowCompactionStrategyParams::COMPACTION_EPOCH_BYTES => 65536,
        ToolWindowCompactionStrategyParams::COMPACTION_NEAR_BYTES => 20000,
        ToolWindowCompactionStrategyParams::MAX_TOOL_RESULT_BYTES => 16384,
        ToolWindowCompactionStrategyParams::TOOL_RESULT_MAX_BYTES => ['ssh' => 8192],
        ToolWindowCompactionStrategyParams::EXCLUDED_TOOLS => ['critical-tool'],
        ToolWindowCompactionStrategyParams::PROTECTED_RECENT_TOOL_CALLS => 3,
        ToolWindowCompactionStrategyParams::ARCHIVE_PLACEHOLDER_MODE => ArchivePlaceholderModeEnum::TOOL_NAMES_WITH_COUNTS->value,
        ToolWindowCompactionStrategyParams::ARCHIVE_PLACEHOLDER_TEMPLATE => '[archived tools] %s',
        ToolWindowCompactionStrategyParams::INPUT_TRIM_BYTES => 100,
        ToolWindowCompactionStrategyParams::OUTPUT_TRIM_BYTES => 100,
        ToolWindowCompactionStrategyParams::SUMMARY_MAX_BYTES => 4096,
    ]
);

Pipeline

Above the trigger the strategy always:

  1. Resolves the latest tool invocations on the full history.
  2. Archives older compactable tool blocks — one placeholder per block. A block is an assistant message with tool calls plus the tool messages carrying its results. The placeholder inherits the block's first message ID and createdAt. A block containing any excluded (e.g. task) or latest-protected call/result is kept whole, so a call is never separated from its result.
  3. Merges compacted archive messages with the fresh window.
  4. Passes the merged collection to inner compaction and returns its result. Without byte epochs, the configured inner strategy receives the full collection as before. With compaction_epoch_bytes, a package-local epoch-aware step applies inner-compatible payload trimming across the entire merged collection; there is no untrimmed raw tail. An older invocation is trimmed only when its newer same-identity call is before the epoch boundary or the serialized messages between its result and that call total fewer than compaction_near_bytes.

The inner ToolCompactionConversationContextStrategy chooses trim candidates internally and does not accept protected call IDs. When byte epochs are enabled, EpochAwareInnerCompactionStrategy therefore selects eligible replaced calls in this package and applies the inner strategy's [omitted] placeholders, _tool_compaction metadata and hashes. The vendor package is unchanged. Existing inner-compaction metadata is left intact so repeated transforms are monotonic.

Because blocks are never merged, placeholders created earlier stay byte-identical when later blocks move into the archive. This keeps the prompt prefix stable for provider prompt caching (OpenAI, Anthropic, Gemini) and keeps summary cache keys stable, so a block is summarized at most once per storage. The trade-off is one placeholder message per archived block instead of one per run of blocks.

Below the archival trigger, inner compaction receives the full history when byte epochs are disabled. With compaction_epoch_bytes set, the epoch-aware step evaluates every message, including messages after the latest boundary: replaced calls before that boundary are trimmed, while farther calls are deferred until a boundary or near threshold permits trimming. The first user message remains non-scalable and is never archived.

Compaction Notes and Metadata

The package uses the shared conversation model (adachsoft/ai-conversation-model). Compaction information that only the application needs is stored in metadata and is not sent to the model:

  • Archive placeholders keep their text (the deterministic placeholder or the AI summary) in the message content, which the model sees. Details such as source_message_count, source_tool_call_ids, source_size_bytes and summary_source are stored in the message metadata under _tool_window_compaction.
  • When the payload of an older tool result is trimmed, every omitted field is replaced in the result content with [omitted by context compaction: N bytes - not a usable value, do not reuse], so the model still knows which values are missing. The general notice [tool_compaction] Tool result compacted for tool=…, callId=…. Large fields omitted. and the flag output_compacted are stored in the tool result metadata under _tool_window_compaction.

The shared conversation model stores tool output in tool results rather than on tool messages. Accordingly, the general [tool_compaction] notice is stored in tool result metadata and is not sent to the model. Per-field [omitted …] markers remain in result content. Summary cache keys are computed from the canonical message array.

Configuration Parameters

See ToolWindowCompactionStrategyParams for all supported keys and defaults. The most important ones are:

  • compaction_trigger_message_count – message-count threshold at which archival starts.
  • compaction_target_fresh_message_count – maximum message-count target for the fresh window.
  • compaction_trigger_bytes – optional serialized-byte threshold; archival starts when either the message-count or byte threshold is reached. Defaults to null.
  • compaction_target_fresh_bytes – optional maximum serialized-byte target for the fresh window. Defaults to null and, when set with compaction_trigger_bytes, must be smaller than the trigger.
  • compaction_epoch_bytes – optional positive serialized-byte interval for inner compaction. Defaults to null, preserving the current behavior. When enabled, replaced calls are trimmed when the newer invocation is before the latest crossed boundary; otherwise they stay complete until a later boundary.
  • compaction_near_bytes – optional positive serialized-byte threshold for trimming replaced calls close to their newer invocation, even when that newer call is after the epoch boundary. The distance is the sum of serialized messages strictly between the older result and newer call. Defaults to null (equivalent to zero), so only the epoch-boundary rule applies.
  • max_tool_result_bytes – optional global maximum serialized size for each tool result. Defaults to null (no limit).
  • tool_result_max_bytes – optional map of tool names to result-size limits; a per-tool value overrides the global limit.
  • archive_placeholder_mode – one of:
    • count_only – placeholder shows only the number of archived tool messages,
    • tool_names_unique – placeholder shows a deduplicated list of tool names,
    • tool_names_with_counts – placeholder shows tool names with occurrence counts.
  • archive_placeholder_template – sprintf template used to render the placeholder body (depends on the selected mode).
  • archive_placeholder_role – role of the placeholder message (defaults to assistant).
  • excluded_tools – list of tool names that must never be archived. It defaults to ['task'], preserving task descriptions returned by task.read. Set it explicitly to [] only when task results may be compacted. An explicit empty list is not merged with the default.
  • tool_identifier_fields – optional per-tool identifiers used by the epoch-aware selector and forwarded to the configured inner strategy when epochs are disabled.
  • protected_recent_tool_calls – number of newest tool calls whose call and result messages are protected from inner payload compaction; defaults to 3. The fresh window expands when necessary to keep these messages together. Set it to 0 to restore the previous behavior.
  • input_trim_bytes / output_trim_bytes – thresholds used for inner-compatible payload trimming and forwarded to the configured inner strategy when epochs are disabled.
  • summary_max_bytes – maximum byte length of generated summary text (defaults to 4096). 0 disables AI summary content. Invalid values resolve to 4096. This limit does not truncate the source messages sent to a summarizer.

Byte thresholds count the sum of the canonical JSON sizes of the messages (ConversationArrayNormalizer from adachsoft/ai-conversation-model, encoded with json_encode). This is a deterministic byte size, not a token estimate or a provider payload size. Tool-result limits count the text size of each result's content separately; a result whose content is a single JSON text part is treated as a structured payload. For oversized result arrays, the longest nested text values are truncated first; array keys and non-text values (such as exit_code) are retained. Text uses a deterministic head/tail split (one third head, two thirds tail) with a marker such as [... truncated 1234 bytes; re-run with a narrower command/range to see more ...]. If the preserved array keys and non-text values alone exceed the configured limit, the result can remain larger than that limit rather than losing structure. Truncation is UTF-8-safe and applies before archival, including to the latest tool invocation. When a tool-call/result pair must remain intact, the window boundary may expand to keep both messages together.

Keeping full task payloads increases memory use. Provider caches are less effective for highly variable tool content. This package does not search historical conversations.

Optional Tool Summaries

Create the strategy through ToolWindowCompactionConversationContextStrategyFactory and pass an ordered ToolSummarizerInterfaceCollection plus a ToolSummaryStorageInterface implementation to create() to enable summaries for archived tool interactions. Without a supporting summarizer, the strategy uses its configured archive placeholder. Default storage is in-memory only; there is no persistent cache.

Each ToolSummarizerInterface implements supports(), summarize(), and cacheNamespace(). Its ToolSummaryRequestDto contains the conversation ID, the source ChatMessageDtoCollection (shared model from adachsoft/ai-conversation-model), and unique sorted tool names. ToolSummaryResultDto contains the generated summary content. The storage interface uses find() and save() to cache results.

use AdachSoft\AiAgentContextToolWindowCompaction\Exception\ToolSummaryFailedException;
use AdachSoft\AiAgentContextToolWindowCompaction\PublicApi\Summary\ToolSummarizerInterface;
use AdachSoft\AiAgentContextToolWindowCompaction\PublicApi\Summary\ToolSummaryRequestDto;
use AdachSoft\AiAgentContextToolWindowCompaction\PublicApi\Summary\ToolSummaryResultDto;

final class FileReadSummarizer implements ToolSummarizerInterface
{
    public function supports(ToolSummaryRequestDto $request): bool
    {
        return $request->toolNames === ['file_read_single'];
    }

    public function summarize(ToolSummaryRequestDto $request): ToolSummaryResultDto
    {
        return new ToolSummaryResultDto('Archived file_read_single results.');
    }

    public function cacheNamespace(): string
    {
        return 'file-read-summary-v1';
    }
}

Every archived block (including a single call/result pair) is offered to the summarizers; eligibility is decided only by supports(), e.g. by checking toolNames or the size of the source messages. The first supporting adapter wins. A summarizer or storage failure does not prevent compaction: the strategy falls back to the deterministic archive placeholder (summary_source = none). Adapter errors are wrapped as ToolSummaryFailedException internally and never leak secrets. The summary_max_bytes limit applies to the final summary text only; the original tool messages remain available to the summarizer.

Testing

cd packages/ai-agent-context-tool-window-compaction
../../../vendor/bin/phpunit

Functional replay (tests/Functional/TaskAmnesiaReplayTest.php) starts every cycle from the same checked-in fixture and asserts that default exclusions keep the full task description while an explicit empty excluded_tools list allows compaction.

tests/Functional/CompactionStatsTest.php maps SPI messages through tests/Support/ConversationStatsMapper.php into adachsoft/ai-agent-stats. Compactable tools such as phpunit_runner reduce totalMessagesSize, trimmedSizeBytes, trimmedMessageCount and trimRatio, while default task usage/input/output sizes stay equal between raw and context stats.

Note: All tests must pass with zero deprecations/notices per project rules.