adachsoft / ai-agent-context-tool-compaction
Conversation context strategy for adachsoft/ai-agent that compacts old tool call payloads to reduce token usage.
Package info
gitlab.com/a.adach/ai-agent-context-tool-compaction
pkg:composer/adachsoft/ai-agent-context-tool-compaction
Requires
- php: ^8.3
- adachsoft/ai-agent: ^0.13
Requires (Dev)
- adachsoft/php-code-style: ^0.7.2
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.2
- phpunit/phpunit: ^12.4
- rector/rector: ^2.6
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Conversation context strategy for adachsoft/ai-agent that compacts old tool call payloads (arguments and results) in the conversation history to reduce LLM token usage.
Requirements
- PHP: >= 8.3
- Runtime dependency:
adachsoft/ai-agent(^0.13; SPI:ConversationContextStrategyInterface) - Conversation model: the shared DTOs from
adachsoft/ai-conversation-model, provided byadachsoft/ai-agent - Namespace:
AdachSoft\\AiAgentContextToolCompaction\\
The strategy uses the shared conversation model provided by adachsoft/ai-agent
and never interacts with the agent's internal domain model.
Installation
Install via Composer:
composer require adachsoft/ai-agent-context-tool-compaction
This package requires adachsoft/ai-agent (declared as a runtime dependency in
composer.json).
Quick Start
1. Register the strategy in AiAgentBuilder
use AdachSoft\AiAgent\PublicApi\Builder\AiAgentBuilder;
use AdachSoft\AiAgentContextToolCompaction\Factory\ToolCompactionConversationContextStrategyFactory;
$strategy = (new ToolCompactionConversationContextStrategyFactory())->create();
$builder = (new AiAgentBuilder())
// ... your ports and config ...
->withSpiConversationContextStrategy($strategy);
2. Enable the strategy in AgentConfigDto
The strategy is selected by its id on AgentConfigDto and configured via
conversationContextStrategyParams.
use AdachSoft\AiAgent\PublicApi\Dto\AgentConfigDto;
use AdachSoft\AiAgentContextToolCompaction\ToolCompactionStrategyParams;
$config = new AgentConfigDto(
// ... other required arguments ...
);
// Pseudocode: set these fields according to your AgentConfigDto API
$config->conversationContextStrategyId = ToolCompactionStrategyParams::STRATEGY_ID; // "tool_compaction"
$config->conversationContextStrategyParams = [
'inputTrimBytes' => 100,
'outputTrimBytes' => 100,
'excludedTools' => [],
'toolIdentifierFields' => [
'read_file_content' => ['path', 'position', 'length'],
],
];
Note: the exact way of setting
conversationContextStrategyIdandconversationContextStrategyParamsdepends on the version ofAgentConfigDto. The example above uses pseudo-code – adapt it to your public API.
3. Minimal configuration fixing the log bug
To ensure that consecutive read_file_content tool calls with the same
path but different position/length are treated as different
logical operations, configure:
$config->conversationContextStrategyParams = [
'toolIdentifierFields' => [
'read_file_content' => ['path', 'position', 'length'],
],
];
Without this configuration the strategy falls back to grouping only by
toolName, which may compact older results for different segments of the same
file.
Public Factories and Latest Invocation Resolver
Create the strategy through its factory
Create the strategy through the public factory and register it through the SPI interface:
use AdachSoft\AiAgentContextToolCompaction\Factory\ToolCompactionConversationContextStrategyFactory;
$strategy = (new ToolCompactionConversationContextStrategyFactory())->create();
Resolve latest invocation IDs
LatestToolInvocationResolver is available through its public factory. It accepts
a chronological list<ChatMessageDto> from the shared conversation model and the
same toolIdentifierFields configuration used by the compaction strategy. It
returns an array<string, true> keyed by tool call ID. The resolver does not
modify the messages or perform I/O.
use AdachSoft\AiConversationModel\Message\ChatMessageDto;
use AdachSoft\AiAgentContextToolCompaction\Factory\LatestToolInvocationResolverFactory;
$resolver = (new LatestToolInvocationResolverFactory())->create();
/** @var list<ChatMessageDto> $messages */
$messages = iterator_to_array($conversation, false);
$protectedToolCallIds = $resolver->resolve($messages, [
'read_file_content' => ['path', 'position', 'length'],
]);
if (isset($protectedToolCallIds['call-123'])) {
// Keep this tool invocation's payload complete.
}
Call the resolver before a destructive operation that removes or rewrites older messages when the protected invocation IDs are needed. The result contains only IDs; the resolver never changes the supplied history.
Reuse identity and payload rules
ToolInvocationIdentityResolver builds the same group key used by
LatestToolInvocationResolver and the conversation strategy. Its factory
provides the default implementation:
use AdachSoft\AiAgentContextToolCompaction\Factory\ToolInvocationIdentityResolverFactory;
$identityResolver = (new ToolInvocationIdentityResolverFactory())->create();
$identityKey = $identityResolver->buildIdentityKey(
toolName: 'read_file_content',
arguments: $arguments,
toolIdentifierFields: [
'read_file_content' => ['path', 'position', 'length'],
],
);
The key follows the strategy's configured field order, treats missing values as
null, and groups tools without configured identifier fields by tool name
alone.
ToolPayloadTrimmer reuses the strategy's input and output size and placeholder
rules. Its thresholds are the integer values configured through
ToolCompactionStrategyParams::INPUT_TRIM_BYTES and
ToolCompactionStrategyParams::OUTPUT_TRIM_BYTES:
use AdachSoft\AiAgentContextToolCompaction\Factory\ToolPayloadTrimmerFactory;
use AdachSoft\AiAgentContextToolCompaction\ToolCompactionStrategyParams;
$toolIdentifierFields = [
'read_file_content' => ['path', 'position', 'length'],
];
$strategyParams = [
ToolCompactionStrategyParams::INPUT_TRIM_BYTES => 100,
ToolCompactionStrategyParams::OUTPUT_TRIM_BYTES => 100,
];
$trimmer = (new ToolPayloadTrimmerFactory())->create();
$trimmedArguments = $trimmer->trimInput(
arguments: $arguments,
inputTrimBytes: $strategyParams[ToolCompactionStrategyParams::INPUT_TRIM_BYTES],
identifierFields: $toolIdentifierFields['read_file_content'],
);
$trimmedResult = $trimmer->trimOutput(
result: $result,
outputTrimBytes: $strategyParams[ToolCompactionStrategyParams::OUTPUT_TRIM_BYTES],
);
The trimmer returns plain arrays and preserves input identifier fields. An
oversized value is replaced with
[omitted by context compaction: <N> bytes - not a usable value, do not reuse].
The returned array never contains _tool_compaction; when the conversation
strategy compacts a tool call or result, it stores omission details under
metadata['tool_compaction'] on the corresponding DTO.
Migration from direct strategy construction
Replace direct construction:
$strategy = new ToolCompactionConversationContextStrategy();
with factory creation:
$strategy = (new ToolCompactionConversationContextStrategyFactory())->create();
ToolCompactionConversationContextStrategy and classes under Internal are
implementation details, not stable public API. Consumers should depend on
ConversationContextStrategyInterface and use the public factories.
Configuration
Parameters are passed as array<string, mixed> through
AgentConfigDto::$conversationContextStrategyParams and resolved by
ParamsResolver. Invalid types are handled fail-open – the strategy uses
safe defaults and never throws.
Supported keys (all optional):
inputTrimBytes(int, default:100)- Maximum payload size in bytes for individual tool argument fields before they are compacted.
outputTrimBytes(int, default:100)- Maximum payload size in bytes for individual tool result fields before they are compacted.
excludedTools(string[], default:[])- List of
toolNamevalues for which no compaction is performed at all (both input and output remain untouched).
- List of
toolIdentifierFields(array<string, string[]>, default:[])- Map of
toolNameto the list of top-level argument keys that together act as a logical identifier. - These fields:
- participate in deduplication key creation,
- are never trimmed, even if they exceed the configured thresholds.
- Map of
Identifier fallback rule
If a tool is not present in toolIdentifierFields, it is treated as if it
had no identifier arguments. In this case, the deduplication key is based
only on the toolName (see the algorithm section below). This may cause older
calls of the same tool with different arguments to be compacted together.
Make sure to configure toolIdentifierFields for tools where arguments define
"what" is being processed (e.g. path, position, length for
read_file_content).
Algorithm Overview
The strategy implements the algorithm described in .tasks/task002-plan-v1.md:
- Input: full conversation history as a
ChatMessageDtoCollectionfrom the shared conversation model. - Output: new
ChatMessageDtoCollectionwith the same messages in the same order, but with selected tool payloads compacted. - The strategy is a pure function over SPI DTOs:
- it never mutates incoming DTO instances,
- it never throws exceptions (fail-open behaviour).
Data model (shared conversation model)
The strategy uses the shared DTOs from adachsoft/ai-conversation-model:
ChatMessageDtoCollectioncontains chronologicalChatMessageDtomessages.ChatMessageDtocarries aChatMessageIdVo,ChatRoleEnum, aContentPartCollection, tool-call and tool-result collections, and metadata.ToolCallDtocarriesToolCallIdVoandToolNameVovalues plusarray<string, mixed>arguments. The arguments remain an array and are compacted using the existing payload rules.ToolResultDtocarriestoolCallId,toolName, aContentPartCollection, and metadata. Tool results are represented as text JSON in oneTextContentPartDto; media and other multi-part content remain supported.
A tool role message has no message content; its result is carried only in
toolResults. Compaction details are stored in tool DTO metadata, not as a
message-content note.
Deduplication key (IdentifierGroupKey)
For each tool call, the strategy computes a group key:
- If
toolIdentifierFields[toolName]is configured and non-empty:- it builds a deterministic string from
(fieldName => value)pairs for the configured fields, - missing values are represented as
null, - field order is preserved as in the configuration (no sorting).
- it builds a deterministic string from
- If there is no configuration for the tool:
- the identifier key is a constant
"__tool_only__".
- the identifier key is a constant
The final IdentifierGroupKey is:
{toolName}|{identifierKey}
Protect the latest occurrence (input + output)
Business rule: for each IdentifierGroupKey, the latest occurrence of a
logical tool call (input and output) must remain fully intact.
To achieve this, the strategy:
Builds an index of all tool calls:
$toolCallIndex[toolCallId] = [ 'toolName' => string, 'arguments' => array<string, mixed>, 'groupKey' => string, ];Iterates over messages from newest to oldest and keeps:
seenGroups: set<string>– which group keys were already seen from the end of the conversation,protectedToolCallIds: set<string>– ids of tool calls that belong to the most recent occurrence of a group.
During this reverse scan:
- When processing tool results:
- the first (
latest) result for eachgroupKeyis left untouched and itsidis added toprotectedToolCallIds; - subsequent (older) results in the same group are compacted.
- the first (
- When processing tool calls:
- any call whose
idis inprotectedToolCallIdsis always left untouched; - otherwise, the first (
latest) call for eachgroupKeyis preserved and itsidis added toprotectedToolCallIds; - subsequent (older) calls in the same group are compacted.
- any call whose
Compaction behaviour
Compaction is delegated to PayloadCompactor, which operates on plain arrays
and uses PayloadSizer for size calculations.
PayloadSizer
string→strlen($value)null/bool/int/float→strlen((string) $value)array→strlen(json_encode($value))(withoutJSON_THROW_ON_ERROR)- unsupported types (objects, resources, etc.) → size
0(fail-open, no trimming)
compactInput(arguments, thresholdBytes, identifierFields)
- Iterates over top-level keys in
arguments. - If key is in
identifierFields→ the field is never trimmed. - Otherwise, if
size(value) > thresholdBytes(andsize > 0):- replaces the value with
"[omitted by context compaction: <N> bytes - not a usable value, do not reuse]", - reports the omitted field separately as
$key => ['bytes' => $calculatedSize, 'sha256' => ...].
- replaces the value with
compactInputWithMetadata()returns the sanitized payload and omitted-field details separately;compactInput()returns only the payload. A legacy_tool_compactionkey in the input is removed and is never compacted.
compactOutput(result, thresholdBytes)
- Works analogously to
compactInput()but without identifier fields – all keys are eligible for trimming. compactOutputWithMetadata()returns the sanitized payload and omitted-field details separately;compactOutput()returns only the payload. A legacy_tool_compactionkey in the input is removed and is never compacted.
Tool result JSON text
For an older tool result, the strategy compacts content only when it contains
exactly one TextContentPartDto with valid JSON whose top-level value is an
array or object. The JSON is decoded, compacted with the configured output
threshold, and encoded back with JSON_UNESCAPED_UNICODE and
JSON_UNESCAPED_SLASHES. Non-JSON text, scalar JSON, multiple content parts,
and media are left unchanged.
A role='tool' message remains without message content; the strategy never
adds a [tool_compaction] note there. Omission details are stored under
metadata['tool_compaction'] on the corresponding ToolResultDto.
Fail-open and safety
- Invalid parameter types → safe defaults (100/100/[]/[]).
- JSON encoding failures → field left unchanged (no trimming).
- The strategy never throws; if anything unexpected happens, the payload is left as-is.
Behaviour Examples
The following examples mirror the behaviour described in the original design specification.
Example A – read_file_content with identifiers (path, position, length)
Configuration:
[
'inputTrimBytes' => 100,
'outputTrimBytes' => 100,
'toolIdentifierFields' => [
'read_file_content' => ['path', 'position', 'length'],
],
]
Timeline (chronological):
- Assistant calls
read_file_contentwith{path: "A.php", position: 0, length: 6000}(call_1). - Tool returns a very large
contentforcall_1. - Assistant calls
read_file_contentagain with the same arguments (call_2). - Tool returns another large
contentforcall_2.
Result after transform:
call_2(latest group member) remains fully intact (input and output).call_1(older in the same group):- the JSON text in the result content has its
contentfield replaced with"[omitted by context compaction: 200 bytes - not a usable value, do not reuse]", - omitted-field details are stored under
metadata['tool_compaction']on the tool result DTO, - the
role='tool'message remains without messagecontent.
- the JSON text in the result content has its
Example B – same path, different position/length (no cross-group dedup)
With the configuration from Example A, two calls:
call_A:{path: "A.php", position: 0, length: 6000}call_B:{path: "A.php", position: 6000, length: 4000}
produce different identifier keys and thus different groups. Each (group, latest) pair is handled independently – no deduplication across (position, length).
Example C – write_file_content with large input, small output
Configuration:
[
'inputTrimBytes' => 100,
'outputTrimBytes' => 100,
'toolIdentifierFields' => [
'write_file_content' => ['path'],
],
]
Timeline:
- Assistant:
write_file_content(call_1) with{path: "A.php", content: "<VERY_LONG>"}. - Tool: one-part JSON text
{"status":"ok"}forcall_1. - Assistant:
write_file_content(call_2) with{path: "A.php", content: "<VERY_LONG_V2>"}. - Tool: one-part JSON text
{"status":"ok"}forcall_2.
Result:
call_2remains full (input and output).call_1(older in the same group):arguments.pathis preserved (identifier),arguments.contentis replaced with"[omitted by context compaction: <N> bytes - not a usable value, do not reuse]".- Omitted-field details are stored under
metadata['tool_compaction']on the tool call DTO, not in the arguments array. - The result JSON text is small enough → unchanged.
Example D – no toolIdentifierFields configuration
If a tool (e.g. list_files) is not present in toolIdentifierFields, then:
- all its calls share the same identifier key
"__tool_only__", - all occurrences of this tool across the conversation belong to a single deduplication group.
This means that older calls may be compacted even if their arguments differ.
For such tools you should explicitly configure toolIdentifierFields.
License
MIT. See LICENSE file and composer.json.