Skip to content

The agent that grows with you

fix(state): retain complete current-turn output in compact receipts

David Dudok de Witef0becea778e
diff --git a/gateway/platforms/api_server_turn_boundary.py b/gateway/platforms/api_server_turn_boundary.py
index 0731abb52f9..c8e90cf1ff0 100644
--- a/gateway/platforms/api_server_turn_boundary.py
+++ b/gateway/platforms/api_server_turn_boundary.py
@@ -49,6 +49,8 @@ def response_turn_start_index(
agent_messages = result.get("messages") if isinstance(result, dict) else None
if not isinstance(agent_messages, list) or not agent_messages:
return 0
+ if result.get('_messages_are_turn_suffix'):
+ return 0
user_idx = reanchor_current_turn_user_idx(agent_messages, user_message)
if user_idx >= 0:
return user_idx + 1
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 035b705a819..71323058c72 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -167,7 +167,7 @@ def settle_session_input(db, *, epoch: int, admission_id: str, generation: int,
result: dict | None = None) -> dict:
if outcome not in ('completed', 'interrupted', 'rejected', 'failed'):
raise RuntimeStoreError('invalid_params')
- encoded = _json(result) if result is not None else None
+ from hermes_state_terminal import compact_result
def write(conn):
_epoch(conn, epoch)
row = _admission(conn, admission_id)
@@ -177,8 +177,9 @@ def settle_session_input(db, *, epoch: int, admission_id: str, generation: int,
or session['runtime_generation'] != generation):
raise RuntimeStoreError('stale_generation')
_retire_admission_workers(conn, row, epoch)
- if encoded is not None:
+ if result is not None:
from hermes_state_terminal import RESULT_PREFIX
+ encoded = _json(compact_result(result, user_message=json.loads(row['payload_json']).get('text')))
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '
'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
(RESULT_PREFIX + admission_id, encoded))
diff --git a/hermes_state_terminal.py b/hermes_state_terminal.py
index 10c791bb359..c5b83caf1d8 100644
--- a/hermes_state_terminal.py
+++ b/hermes_state_terminal.py
@@ -15,6 +15,34 @@ IDENTITY_PREFIX = 'gateway.terminal_identity.v1.'
WORKER_PREFIX = 'gateway.terminal_worker.v1.'
+def compact_result(result, *, user_message=None):
+ """Retain replay/accounting and current-turn API output, never cumulative history."""
+ result = dict(result)
+ value = result.get('result')
+ if not isinstance(value, dict):
+ return result
+ value = dict(value)
+ messages = value.get('messages')
+ if isinstance(messages, list):
+ # Agent results include all previous turns. APIs only project this turn's
+ # assistant/tool suffix; previous_response_id stores its own history. Compression
+ # is the exception: its replacement snapshot is the only immutable record of the
+ # rewritten prefix for this turn. A later live transcript may include a successor.
+ if not value.get('_compressed') and not value.get('_messages_are_turn_suffix'):
+ from agent.turn_context import reanchor_current_turn_user_idx
+ anchor = value.get('current_turn_user_idx')
+ if not (type(anchor) is int and 0 <= anchor < len(messages)
+ and isinstance(messages[anchor], dict) and messages[anchor].get('role') == 'user'):
+ anchor = reanchor_current_turn_user_idx(messages, user_message)
+ value['messages'] = messages[anchor + 1:]
+ # Recovery/verification nudges are later user-role rows within this same turn.
+ # Consumers must not infer a new boundary from them after the real anchor is gone.
+ value['_messages_are_turn_suffix'] = True
+ value.pop('current_turn_user_idx', None)
+ result['result'] = value
+ return result
+
+
def identity_key(principal_id, session_id, request_id):
return IDENTITY_PREFIX + admission_fingerprint(canonical_target=session_id,
payload={'principal': principal_id, 'request': request_id})
diff --git a/tests/gateway/test_api_compressed_receipt_history.py b/tests/gateway/test_api_compressed_receipt_history.py
new file mode 100644
index 00000000000..8f3a961d3de
--- /dev/null
+++ b/tests/gateway/test_api_compressed_receipt_history.py
@@ -0,0 +1,51 @@
+"""Responses chaining preserves a turn's compressed replacement, while ordinary receipts stay compact."""
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+
+async def test_compressed_receipt_chains_its_snapshot_then_retires_history(api, owner):
+ from gateway.session_api_turn import api_execution
+ from gateway.session_results import admission_result, execution_result
+ seen = []
+ compressed = [
+ {'role': 'assistant', 'content': 'compressed-summary-sentinel', '_compressed_summary': True},
+ {'role': 'user', 'content': 'compress now'},
+ {'role': 'assistant', 'content': 'compressed answer'},
+ ]
+
+ async def handle(event):
+ history = api_execution.get()['history']
+ seen.append(history)
+ if event.text == 'compress now':
+ result = {'final_response': 'compressed answer', '_compressed': True, 'messages': compressed}
+ else:
+ result = {'final_response': 'next answer', 'messages': [*history,
+ {'role': 'user', 'content': event.text}, {'role': 'assistant', 'content': 'next answer'}]}
+ execution_result.get()['result'] = result
+ return result['final_response']
+
+ owner.runner._handle_message = handle
+ app = web.Application()
+ app.router.add_post('/v1/responses', api._handle_responses)
+ async with TestClient(TestServer(app)) as client:
+ first = await client.post('/v1/responses', json={'input': 'compress now',
+ 'conversation_history': [{'role': 'user', 'content': 'old-uncompressed-history'}]},
+ headers={'Idempotency-Key': 'compress-key'})
+ assert first.status == 200
+ first_result = await first.json()
+ second = await client.post('/v1/responses', json={'input': 'next', 'previous_response_id': first_result['id']},
+ headers={'Idempotency-Key': 'next-key'})
+ assert second.status == 200
+ assert seen[1] == compressed
+ assert 'old-uncompressed-history' not in str(seen[1])
+ rows = owner.db._read_all('SELECT admission_id,target_session_id FROM session_admissions ORDER BY seq')
+ assert admission_result(owner.db, rows[0]['admission_id'])['result']['messages'] == compressed
+ assert admission_result(owner.db, rows[1]['admission_id'])['result']['messages'] == [
+ {'role': 'assistant', 'content': 'next answer'}]
+ assert owner.db.delete_session(rows[0]['target_session_id'])
+ for row in rows:
+ saved = admission_result(owner.db, row['admission_id'])
+ assert saved['result']['messages'] == []
+ assert 'compressed-summary-sentinel' not in str(saved)
diff --git a/tests/gateway/test_api_synthetic_nudge_receipt.py b/tests/gateway/test_api_synthetic_nudge_receipt.py
new file mode 100644
index 00000000000..219efd839d3
--- /dev/null
+++ b/tests/gateway/test_api_synthetic_nudge_receipt.py
@@ -0,0 +1,54 @@
+"""An internal user-role recovery nudge must not erase earlier output in the same API turn."""
+import json
+
+import pytest
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+
[email protected]('stream', [False, True])
[email protected]('marked', [False, True])
+async def test_tool_output_before_synthetic_user_nudge_survives_settlement(api, owner, stream, marked):
+ from gateway.session_api_turn import publish_api_tool_event
+ from gateway.session_results import execution_result
+ prior = [{'role': 'user', 'content': 'read a'}, {'role': 'assistant', 'content': 'previous answer'}]
+ transcript = []
+
+ async def handle(event):
+ sid = event.source.chat_id
+ generation = owner.sessions[sid].event_stream.execution['execution_generation']
+ publish_api_tool_event(owner, sid, generation, 'tool.start', 'read-1', 'read_file', {'path': 'a'})
+ publish_api_tool_event(owner, sid, generation, 'tool.complete', 'read-1', 'read_file', {'path': 'a'}, 'read')
+ transcript.extend([*prior,
+ {'role': 'user', 'content': event.text},
+ {'role': 'assistant', 'content': '', 'tool_calls': [
+ {'id': 'read-1', 'type': 'function',
+ 'function': {'name': 'read_file', 'arguments': '{"path":"a"}'}}]},
+ {'role': 'tool', 'tool_call_id': 'read-1', 'content': 'read'},
+ {'role': 'user', 'content': 'Please finish your response.' if marked else event.text,
+ **({'_empty_recovery_synthetic': True} if marked else {})},
+ {'role': 'assistant', 'content': 'answer'},
+ ])
+ execution_result.get()['result'] = {'final_response': 'answer', 'messages': transcript,
+ **({} if marked else {'current_turn_user_idx': len(prior)})}
+ return 'answer'
+
+ owner.runner._handle_message = handle
+ app = web.Application()
+ app.router.add_post('/v1/responses', api._handle_responses)
+ async with TestClient(TestServer(app)) as client:
+ response = await client.post('/v1/responses', json={'input': 'read a', 'stream': stream,
+ 'conversation_history': prior},
+ headers={'Idempotency-Key': 'synthetic-nudge'})
+ assert response.status == 200
+ if stream:
+ frames = [json.loads(line[6:]) for line in (await response.text()).splitlines()
+ if line.startswith('data: ')]
+ result = frames[-1]['response']
+ else:
+ result = await response.json()
+ stored = api._current_response_store().get(result['id'])
+ assert stored['conversation_history'] == transcript
+ assert [(item['type'], item.get('call_id')) for item in result['output']] == [
+ ('function_call', 'read-1'), ('function_call_output', 'read-1'), ('message', None)]
diff --git a/tests/gateway/test_turn_result_retention.py b/tests/gateway/test_turn_result_retention.py
new file mode 100644
index 00000000000..fdbd7755d00
--- /dev/null
+++ b/tests/gateway/test_turn_result_retention.py
@@ -0,0 +1,55 @@
+"""Receipt retries preserve transcript boundaries, successor ownership and media identity."""
+
+
+
+from pathlib import Path
+
+
+
+from types import SimpleNamespace
+
+
+
+import pytest
+
+
+
+from gateway.session_authority import LiveSession
+
+
+
+from gateway.session_contract import Principal, SessionRef, Submission
+
+
+
+from gateway.session_results import admission_result, finish_result
+
+
+
+from hermes_state_runtime import (RuntimeStoreError, admit_session_input, begin_runtime_epoch,
+ claim_session_input, get_session_admission, recover_session_inputs)
+
+
+
+def test_results_retain_only_turn_output_and_retirement_keeps_accounting(owner):
+ owner.db.create_session('s', source='api_server')
+ messages = []
+ admissions = []
+ for index in range(3):
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id='api', session_id='s',
+ request_id=str(index), payload={'text': str(index)})
+ row = claim_session_input(owner.db, epoch=owner.epoch, session_id='s')
+ messages += [{'role': 'user', 'content': 'history-sentinel'},
+ {'role': 'assistant', 'content': f'answer-{index}'}]
+ finish_result(owner.db, epoch=owner.epoch, row=row, response=f'answer-{index}', outcome='completed',
+ result={'result': {'messages': list(messages), 'final_response': f'answer-{index}', 'completed': True},
+ 'usage': {'input_tokens': 11, 'cost': .5}})
+ saved = admission_result(owner.db, row['admission_id'])
+ assert saved['result']['messages'] == [messages[-1]]
+ admissions.append(row['admission_id'])
+ owner.db.delete_session('s')
+ for aid in admissions:
+ saved = admission_result(owner.db, aid)
+ assert saved['result']['messages'] == []
+ assert saved['usage'] == {'input_tokens': 11, 'cost': .5}
+ assert saved['result']['completed'] is True