Skip to content

The agent that grows with you

fix(gateway): run on_pre_compress memory hooks on canonical /compress

Teknium4279636b9624
diff --git a/gateway/session_mutation_compress.py b/gateway/session_mutation_compress.py
index 55faef46eef..f7fc50711bf 100644
--- a/gateway/session_mutation_compress.py
+++ b/gateway/session_mutation_compress.py
@@ -55,8 +55,16 @@ async def prepare_compress(authority, live, payload, prepared):
estimate_request_tokens_rough(messages))
return {'status': 'preview', 'lines': report['lines'], 'head_count': report['head_count'],
'tail_count': report['tail_count'], 'message_count': report['total']}
+ # The session's resident agent owns its memory providers; give them the same pre-compress
+ # turn (and the same best-effort contract) the in-process compressor does. No resident agent
+ # (cold session, or a managed worker that runs out of process) means no provider to call.
+ cached_agent = getattr(authority.runner, '_cached_agent_for', None)
+ resident = cached_agent(live.route) if callable(cached_agent) else None
+
def summarize():
with policy_scope(policy, authority=authority):
+ from agent.conversation_compression import _pre_compress_memory_context
+ memory_context = _pre_compress_memory_context(resident, head, False) if resident is not None else ''
compressor = ContextCompressor(model, base_url=runtime.get('base_url') or '',
api_key=runtime.get('api_key') or '', provider=runtime.get('provider') or '',
api_mode=runtime.get('api_mode') or '', quiet_mode=True, abort_on_summary_failure=True,
@@ -64,7 +72,7 @@ async def prepare_compress(authority, live, payload, prepared):
min_tail_user_messages=max(1, _parse_config_int(options.get('min_tail_user_messages', 1), 1)),
custom_providers=config.get('custom_providers'))
compressed = compressor.compress(json.loads(json.dumps(head)), force=True,
- focus_topic=request.focus_topic)
+ focus_topic=request.focus_topic, memory_context=memory_context)
if not any(m.get('_compressed_summary') for m in compressed):
raise RuntimeStoreError('nothing_to_compress')
return rejoin_compressed_head_and_tail(compressed, tail), compressor
diff --git a/tests/gateway/test_session_mutation_compress_preview.py b/tests/gateway/test_session_mutation_compress_preview.py
index 602c82c7f0b..005acc8cc60 100644
--- a/tests/gateway/test_session_mutation_compress_preview.py
+++ b/tests/gateway/test_session_mutation_compress_preview.py
@@ -73,3 +73,51 @@ async def test_preview_mutation_reports_without_summarizing_or_writing(tmp_path,
assert summaries == []
finally:
await owner.close()
+
+
+async def test_canonical_compress_runs_the_live_agents_pre_compress_memory_hook(tmp_path, monkeypatch):
+ """Canonical ``/compress`` gives the session's memory providers the same ``on_pre_compress``
+ turn the in-process compressor does, and their insight reaches the summarizer."""
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from agent.context_compressor import ContextCompressor
+
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ hooked, summarized = [], []
+
+ class Memory:
+ def on_pre_compress(self, messages, **kwargs):
+ hooked.append([m['content'] for m in messages])
+ return 'PROVIDER_INSIGHT'
+
+ def compress(self, messages, **kw):
+ summarized.append(kw.get('memory_context'))
+ return [{'role': 'user', 'content': 'summary', '_compressed_summary': True}]
+
+ monkeypatch.setattr(ContextCompressor, '__init__', lambda self, *a, **k: None)
+ monkeypatch.setattr(ContextCompressor, 'compress', compress)
+ live_agent = SimpleNamespace(_memory_manager=Memory())
+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,
+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: live_agent,
+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)
+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})
+ ref = create_local_session(authority, owner.actor, dict(request_id='hook', source='cli', cwd=str(tmp_path),
+ model='frozen', toolsets=[]))
+ for i in range(4):
+ db.append_message(ref.session_id, 'user', f'question {i}')
+ db.append_message(ref.session_id, 'assistant', f'answer {i}')
+ before = db.get_session(ref.session_id)
+ try:
+ await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': {
+ 'session_id': ref.session_id, 'request_id': 'compress', 'expected_revision': before['runtime_revision'],
+ 'expected_generation': before['runtime_generation'], 'operation': 'compress', 'payload': {}}})
+ assert hooked and hooked[0][0] == 'question 0' and len(hooked[0]) == 8
+ assert summarized and 'PROVIDER_INSIGHT' in summarized[0]
+ finally:
+ await owner.close()