Manages the agent's working memory within a single run: the conversation history, compacted summaries, pinned observations, and session state. Also provides a pub/sub context bus for cross-module communication.
- Threshold-based — compaction triggers when
token_count / max_tokens >= threshold_low(default 0.75). - Semantic summarization — when
enable_semantic_compression=True, summarizes old observations using LLM-style text compression. - Pinned values — memory keys in
context['memory_keys']are preserved across compactions. - Incremental — each compaction appends to
compacted_summarywith "Then, ..." prefix. - Compression ratio tracked —
context['compression_ratio']andcontext['compaction_count']are updated.
- Pub/sub — modules publish events; subscribers receive them synchronously.
- Decoupled — modules don't need direct references to each other.
- Serialization — packages context for cross-agent transfer or persistence.
- Selective inclusion — only serializes non-sensitive keys.
- Session lifecycle — tracks session ID, start time, user, run history.
- Persistence — serialized to JSON in the run directory.
[context dict]
└── observations: list[str] ← appended each iteration
should_compact(token_count, max_tokens)?
└── YES if token_count/max_tokens >= 0.75
compact(context)
├── split observations: old[:-recent_observations], recent[-recent_observations:]
├── summarize(old) → summary string
├── context['observations'] = recent
├── context['compacted_summary'] += '\nThen, ' + summary
└── context['compaction_count'] += 1
compaction_countis monotonically increasing.recent_observationsmost recent items are always preserved.memory_keysare copied verbatim across compactions.- Token estimation is approximate (3.5-4.0 chars/token); actual token count may differ.
Note: The
context_packsub-module provides context packing and semantic compression utilities. Seecontext_packfor details.