Skip to content

The agent that grows with you

fix(gateway): a managed session's receipt keeps the turn's tokens, cost and model

Tekniumac6a5d44dcfd
diff --git a/agent/managed_worker.py b/agent/managed_worker.py
index 73a2064e467..fdbd4cfd07c 100644
--- a/agent/managed_worker.py
+++ b/agent/managed_worker.py
@@ -25,6 +25,35 @@ logger = logging.getLogger(__name__)
MAX_FRAME = 4 * 1024 * 1024
BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'route', 'user_id', 'chat_id',
'turn_author', 'safe_mode', 'ignore_user_config'}
+# The bounded run_conversation fields a turn receipt keeps (outcome, exit reason, tokens, cost,
+# model): what the in-process projection commits and ``-z --usage-file`` reads.
+RESULT_FIELDS = ('final_response', 'failed', 'interrupted', 'completed', 'partial', 'error', 'turn_exit_reason',
+ 'api_calls', 'model', 'provider', 'prompt_tokens', 'completion_tokens', 'total_tokens',
+ 'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens',
+ 'estimated_cost_usd', 'cost_status', 'cost_source', 'service_tier')
+
+
+def result_frame(result):
+ """Worker side: the receipt fields of ``run_conversation``'s result, scalars only, text bounded."""
+ return {k: (v[:4096] if isinstance(v, str) and k != 'final_response' else v) for k, v in result.items()
+ if k in RESULT_FIELDS and (v is None or type(v) in (bool, int, float, str))}
+
+
+def accept_result(result):
+ """Owner side of the worker's result frame: ``(result, usage)`` in the in-process turn's shape
+ (gateway projection: prompt/completion tokens as input/output), or ValueError."""
+ if (not isinstance(result, dict) or set(result) - set(RESULT_FIELDS) or not isinstance(result.get('final_response'), str)
+ or any(not (value is None or type(value) in (bool, int, float) or (isinstance(value, str) and len(value) <= 4096))
+ for key, value in result.items() if key != 'final_response')):
+ raise ValueError('invalid_worker_result')
+ accepted = dict(result)
+ incoming, outgoing = accepted.pop('prompt_tokens', None), accepted.pop('completion_tokens', None)
+ if incoming is None and outgoing is None:
+ return accepted, {}
+ usage = {'input_tokens': incoming or 0, 'output_tokens': outgoing or 0}
+ usage['total_tokens'] = usage['input_tokens'] + usage['output_tokens']
+ accepted.update(input_tokens=usage['input_tokens'], output_tokens=usage['output_tokens'])
+ return accepted, usage
def read_frame(stream):
@@ -301,8 +330,7 @@ def execute(frame, channel):
store.flush_token_counts()
if result.get('final_response') is None and (result.get('interrupted') or result.get('failed')):
result['final_response'] = ''
- channel.send('result', result={k: result[k] for k in
- ('final_response', 'failed', 'interrupted') if k in result})
+ channel.send('result', result=result_frame(result))
if not controls.finish.wait(30):
raise ValueError('managed_finish_timeout')
store.finish()
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 11221500752..75b7dcb86b6 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -10,7 +10,7 @@ from pathlib import Path
import subprocess
import sys
-from agent.managed_worker import encode_frame, read_frame
+from agent.managed_worker import accept_result, encode_frame, read_frame
from gateway.session_worker_reservation import reserve_admission_worker
from hermes_state_runtime import RuntimeStoreError
@@ -292,7 +292,7 @@ async def execute_managed(authority, ref, row, policy):
# A Stop acknowledged during the env/spawn awaits found no worker and was latched for this
# generation; consume it in the same step that makes the worker reachable to interrupt_managed.
authority.adopt_agent(ref.session_id, row['generation'], worker)
- accepted = None
+ accepted = usage = None
scope = None
try:
# The interpreter behind the handle introduces itself first; the owner verifies that
@@ -325,11 +325,10 @@ async def execute_managed(authority, ref, row, policy):
if publish_worker_tool_event(authority, ref.session_id, row['generation'], frame):
continue
if kind == 'result' and set(frame) == {'type', 'result'} and accepted is None:
- result = frame['result']
- if (not isinstance(result, dict) or set(result) - {'final_response', 'failed', 'interrupted'}
- or not isinstance(result.get('final_response'), str)):
- raise RuntimeStoreError('invalid_worker_result')
- accepted = result
+ try:
+ accepted, usage = accept_result(frame['result'])
+ except ValueError as exc:
+ raise RuntimeStoreError('invalid_worker_result') from exc
authority.sessions[ref.session_id].controls.snapshot(ref.session_id, None)
await asyncio.to_thread(worker.send, {'type': 'finish'})
continue
@@ -339,7 +338,7 @@ async def execute_managed(authority, ref, row, policy):
raise RuntimeStoreError('managed_worker_lost')
# Like in-process execution, settlement belongs to the drain's stream lock.
# The worker must acknowledge its durable finish before that boundary.
- authority.pending_results[row['admission_id']] = {'result': accepted, 'usage': {}}
+ authority.pending_results[row['admission_id']] = {'result': accepted, 'usage': usage}
return accepted['final_response']
raise RuntimeStoreError('invalid_worker_frame')
except (Exception, asyncio.CancelledError) as exc:
diff --git a/tests/gateway/test_managed_worker_launch.py b/tests/gateway/test_managed_worker_launch.py
index e70b3ded532..10f4414e35a 100644
--- a/tests/gateway/test_managed_worker_launch.py
+++ b/tests/gateway/test_managed_worker_launch.py
@@ -217,6 +217,11 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path
restored = await rpc(ws, 'session.resume', session_id=sid)
history = restored['result']['messages']
assert 'MANAGED_TOOL_DONE' in json.dumps(history), restored
+ # The committed receipt keeps the worker's spend (what `-z --usage-file` reads).
+ [(admission,)] = query('SELECT admission_id FROM session_admissions WHERE request_id=?', ('managed-input',))
+ receipt = (await rpc(ws, 'prompt.receipt', session_id=sid, admission_id=admission, include_result=True))['result']
+ assert receipt['usage']['total_tokens'] == 15 * len(peer.requests), receipt
+ assert receipt['result']['model'] == 'managed-model' and receipt['result']['api_calls'] == len(peer.requests), receipt
replay = await rpc(ws, 'session.events.since', session_id=sid,
replay_epoch=restored['result']['replay_epoch'], last_sequence=0)
tools = [e for e in replay['result']['events'] if e['type'] in {'tool.start', 'tool.complete'}]
diff --git a/tests/gateway/test_managed_worker_result_usage.py b/tests/gateway/test_managed_worker_result_usage.py
new file mode 100644
index 00000000000..8f2c172216f
--- /dev/null
+++ b/tests/gateway/test_managed_worker_result_usage.py
@@ -0,0 +1,39 @@
+"""A managed turn's receipt keeps its spend: the worker's result frame carries the bounded
+accounting fields of ``run_conversation`` and the owner commits them with ``usage``, so
+``-z --usage-file`` on a managed session reports tokens, cost, model and exit reason."""
+import io
+
+from agent.managed_worker import accept_result, encode_frame, read_frame, result_frame
+from hermes_cli.oneshot import _USAGE_KEYS
+
+
+def _run_conversation_result():
+ """The keys agent/turn_finalizer.py returns (values from one two-call turn)."""
+ return {'final_response': 'done', 'last_reasoning': None, 'messages': [{'role': 'user', 'content': 'go'}],
+ 'api_calls': 2, 'completed': True, 'turn_exit_reason': 'text_response(finish_reason=stop)',
+ 'failed': False, 'partial': False, 'interrupted': False, 'response_transformed': False,
+ 'pre_transform_response': None, 'response_previewed': False, 'response_reused': False,
+ 'model': 'm', 'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1',
+ 'input_tokens': 18, 'output_tokens': 10, 'cache_read_tokens': 2, 'cache_write_tokens': 0,
+ 'reasoning_tokens': 0, 'prompt_tokens': 20, 'completion_tokens': 10, 'total_tokens': 30,
+ 'last_prompt_tokens': 10, 'estimated_cost_usd': 0.0125, 'cost_status': 'estimated',
+ 'cost_source': 'catalog', 'service_tier': None, 'session_id': 'worker-session',
+ 'error': 'x' * 10000}
+
+
+def test_worker_result_frame_carries_the_usage_ledger():
+ wire = read_frame(io.BytesIO(encode_frame({'type': 'result', 'result': result_frame(_run_conversation_result())})))
+ result, usage = accept_result(wire['result'])
+ # Same projection the in-process gateway turn commits (prompt/completion as input/output).
+ assert usage == {'input_tokens': 20, 'output_tokens': 10, 'total_tokens': 30}
+ # Every ledger key the usage file reads, except the session id the viewer stamps itself.
+ assert {k for k in _USAGE_KEYS if k != 'session_id'} <= set(result), set(_USAGE_KEYS) - set(result)
+ assert result['estimated_cost_usd'] == 0.0125 and result['turn_exit_reason'].startswith('text_response')
+ assert len(result['error']) == 4096 and 'messages' not in result and 'base_url' not in result
+ # Unknown or non-scalar fields are refused at the owner boundary.
+ for bad in ({'final_response': 'x', 'messages': []}, {'final_response': 'x', 'model': ['m']}, {'failed': True}):
+ try:
+ accept_result(bad)
+ except ValueError:
+ continue
+ raise AssertionError(bad)