The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a canonical compress counts on the session (`🗜️ N` survives the agent swap)
Teknium650b96e892a7
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.pyindex 1682c3bd6a1..2fc115dcaf0 100644--- a/gateway/local_viewer_events.py+++ b/gateway/local_viewer_events.py@@ -38,6 +38,10 @@ def wire(turn, agent) -> dict:# Kawaii spinner text ("" clears it) and hearts; neither changes what the provider is sent.agent.thinking_callback = lambda text: publish("thinking.delta", {"text": str(text or "")})agent.reaction_callback = lambda kind: publish("reaction", {"kind": str(kind or "")})+ owner = getattr(turn, "_approval_owner", None)+ if owner is not None:+ from gateway.session_usage import seed_compression_count+ seed_compression_count(owner[0].sessions.get(owner[1]), agent)if show_reasoning(turn):# Only on request: a reasoning sink makes the agent ask the provider for reasoning.agent.reasoning_callback = lambda text: publish("reasoning.delta", {"text": str(text or "")})diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 7025b6c74d1..e9eb086994a 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -178,6 +178,12 @@ async def _mutate_session(authority, actor, ref, params, *, commit_lock=None):current = authority.db.get_session(ref.session_id)owns_projection = current is not None and (current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))+ if operation == 'compress' and applied and owns_projection and live is not None:+ # Before the boundary evicts the agent whose compressor holds the running count.+ from gateway.session_usage import note_compression+ note_compression(authority, ref, live)+ elif operation == 'reset' and applied and live is not None:+ live.compression_count = 0 # a fresh conversation, as main's /new builds a fresh agentif operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:_project_committed(authority, ref, operation, result)if live is not None:diff --git a/gateway/session_usage.py b/gateway/session_usage.pyindex 9a425a9c962..cb146b0cb10 100644--- a/gateway/session_usage.py+++ b/gateway/session_usage.py@@ -83,6 +83,30 @@ def usage_stats(agent) -> dict:return stats+def carried_compression_count(live, agent=None) -> int:+ """Compactions of this conversation: main's agent counted them on its compressor for the+ session's life. A canonical compress evicts the gateway's agent (a session boundary), so the+ count rides the live session and seeds the successor (``seed_compression_count``)."""+ own = getattr(getattr(agent, "context_compressor", None), "compression_count", 0)+ carried = getattr(live, "compression_count", 0)+ return max(carried if isinstance(carried, int) else 0, own if isinstance(own, int) else 0)+++def note_compression(authority, ref, live) -> None:+ """A committed (never an exact-retried) compress: one more compaction than the evicted agent saw."""+ agent = None+ with contextlib.suppress(AttributeError, KeyError): # a runner without an agent cache has none+ agent = authority.agent(ref)+ live.compression_count = carried_compression_count(live, agent) + 1+++def seed_compression_count(live, agent) -> None:+ compressor = getattr(agent, "context_compressor", None)+ if live is not None and compressor is not None:+ with contextlib.suppress(Exception):+ compressor.compression_count = carried_compression_count(live, agent)++def publish_usage(turn, agent) -> None:"""One ``session.usage`` frame on the viewer's stream; never breaks the turn."""if agent is None:@@ -97,4 +121,7 @@ async def stats(connection, ref, params):if set(params) - {"session_id", "profile"}:raise RuntimeStoreError("invalid_params")await connection.authority.resolve(connection.actor, ref)- return usage_stats(connection.authority.agent(ref))+ agent = connection.authority.agent(ref)+ result = usage_stats(agent)+ result["compression_count"] = carried_compression_count(connection.authority.sessions.get(ref.session_id), agent)+ return resultdiff --git a/tests/gateway/test_session_mutation_compress.py b/tests/gateway/test_session_mutation_compress.pyindex ac280d62e32..d15ecb72207 100644--- a/tests/gateway/test_session_mutation_compress.py+++ b/tests/gateway/test_session_mutation_compress.py@@ -110,6 +110,9 @@ def run_compress_case(tmp_path, mode, in_place):assert (result['target_session_id'] == physical) is effective_in_placecompressed = await call('session.resume', session_id=sid)assert 'SUMMARY_RETAINED_FACTS' in json.dumps(compressed['messages'])+ # Main's agent counts the compaction (status bar `🗜️ N`, /usage): the evicted agent's+ # successor carries it, before its first turn and after it.+ assert (await call('session.stats', session_id=sid))['compression_count'] == 1retained = 1 if mode == 'safe' else cfg['compression']['min_tail_user_messages']with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:tail_users = [row[0] for row in db.execute(@@ -121,12 +124,14 @@ def run_compress_case(tmp_path, mode, in_place):retried = await call('prompt.submit', session_id=sid, input_id=text, text=text)assert retried['admission_id'] == receipt['admission_id']await turn('AFTER_COMPRESSION')+ assert (await call('session.stats', session_id=sid))['compression_count'] == 1assert 'SUMMARY_RETAINED_FACTS' in json.dumps(peer.requests[-1]['messages'])for i in range(history_count - retained, history_count):assert f'HISTORY_{i}' in json.dumps(peer.requests[-1]['messages'])count = len(peer.requests)assert await call('session.mutate', **params) == resultassert len(peer.requests) == count+ assert (await call('session.stats', session_id=sid))['compression_count'] == 1 # retry: no recount# Later mutations must target the current transcript, not a closed ancestor.after = await call('session.resume', session_id=sid)branch = await call('session.mutate', session_id=sid, request_id='branch-after-compress',