The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): failed authority turns carry the error_surface the TUI sends
alt-glitch76fd3f1debfa
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex a41728cce01..d261a42412b 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -33,27 +33,31 @@ RESULT_FIELDS = ('final_response', 'failed', 'interrupted', 'completed', 'partia'cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens','estimated_cost_usd', 'cost_status', 'cost_source', 'service_tier', 'failure_reason','session_id', 'requested_model', 'served_model', '_turn_input_tokens', '_turn_output_tokens',- 'billing_block')-# ``billing_block`` (``agent/billing_links.BillingBlock`` plus ``unverified``) is the one structured field.+ 'failure_retryable', 'failure_resets_at', 'billing_block', 'free_tier')+# The structured fields and their allowed keys: ``billing_block`` (``agent/billing_links.BillingBlock``+# plus ``unverified``) and ``free_tier`` (``agent/turn_recovery._stamp_free_tier``). With+# ``failure_reason``, ``failure_retryable`` and ``failure_resets_at`` they are what+# ``agent.error_surface.build_error_surface_from_result`` reads for the owner's error card.BILLING_FIELDS = ('provider', 'provider_label', 'model', 'billing_url', 'is_nous', 'message', 'unverified')+STRUCTURED_FIELDS = {'billing_block': BILLING_FIELDS, 'free_tier': ('kind', 'message')}def _scalar(value):return value is None or type(value) in (bool, int, float) or (isinstance(value, str) and len(value) <= 4096)-def _billing_block(value):- return isinstance(value, dict) and not set(value) - set(BILLING_FIELDS) and all(map(_scalar, value.values()))+def _structured(key, value):+ return isinstance(value, dict) and not set(value) - set(STRUCTURED_FIELDS[key]) and all(map(_scalar, value.values()))def result_frame(result):"""Worker side: the receipt fields of ``run_conversation``'s result, scalars only, text bounded."""frame = {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 k != 'billing_block' and (v is None or type(v) in (bool, int, float, str))}- block = result.get('billing_block')- if isinstance(block, dict):- frame['billing_block'] = {k: v[:4096] if isinstance(v, str) else v for k, v in block.items()- if k in BILLING_FIELDS and (v is None or type(v) in (bool, int, float, str))}+ if k in RESULT_FIELDS and k not in STRUCTURED_FIELDS and (v is None or type(v) in (bool, int, float, str))}+ for key, fields in STRUCTURED_FIELDS.items():+ if isinstance(block := result.get(key), dict):+ frame[key] = {k: v[:4096] if isinstance(v, str) else v for k, v in block.items()+ if k in fields and (v is None or type(v) in (bool, int, float, str))}return frame@@ -61,13 +65,15 @@ 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 result.get('billing_block') is not None and not _billing_block(result['billing_block'])- or any(not _scalar(value) for key, value in result.items() if key not in ('final_response', 'billing_block'))):+ or any(result.get(key) is not None and not _structured(key, result[key]) for key in STRUCTURED_FIELDS)+ or any(not _scalar(value) for key, value in result.items()+ if key != 'final_response' and key not in STRUCTURED_FIELDS)):raise ValueError('invalid_worker_result')accepted = dict(result)- if accepted.get('billing_block') is None:- # Every failure other than a billing wall carries no block.- accepted.pop('billing_block', None)+ for key in STRUCTURED_FIELDS:+ if accepted.get(key) is None:+ # A failure other than a billing wall or a free-tier refusal carries no block.+ accepted.pop(key, None)turn_in, turn_out = accepted.pop('_turn_input_tokens', None), accepted.pop('_turn_output_tokens', None)if any(value is not None and (type(value) is not int or value < 0) for value in (turn_in, turn_out)):raise ValueError('invalid_worker_result')diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 37da0e27c2d..c4ba2a34ed2 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -71,6 +71,9 @@ _LEDGER_PASSTHROUGH_KEYS = ("estimated_cost_usd", "cost_status", "cost_source", "cache_read_tokens", "cache_write_tokens","reasoning_tokens", "total_tokens", "provider", "turn_exit_reason", "service_tier",)+# Beside ``failure_reason`` and ``error``: what ``agent.error_surface.build_error_surface_from_result`` reads,+# so the authority's ``message.complete`` carries the same error card the TUI path builds.+_FAILURE_DESCRIPTOR_KEYS = ("free_tier", "failure_retryable", "failure_resets_at")def _finite_viewer_turn() -> bool:@@ -1337,6 +1340,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):"partial": result.get("partial", False), "completed": result.get("completed"),"interrupted": result.get("interrupted", False), "interrupt_message": result.get("interrupt_message"),"error": result.get("error"),+ **{key: result[key] for key in _FAILURE_DESCRIPTOR_KEYS if key in result},"compression_exhausted": result.get("compression_exhausted", False),"compression_deferred": result.get("compression_deferred", False),"tools": ctx.tools_holder[0] or [],diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.pyindex 7342e111b19..dc12fb99c3a 100644--- a/gateway/session_settlement_recovery.py+++ b/gateway/session_settlement_recovery.py@@ -61,9 +61,16 @@ def completion_payload(row, settled, response, captured):# Only the agent's reuse site sets this (never inferred from equal text): the# final repeats a reply the viewer already painted, so it settles in place.captured_result = (captured or {}).get('result') or {}- if isinstance(captured_result.get('error_surface'), dict):- # Only gateway-owned refusals set this (``session_cron.execute``); ``text`` is already their copy.- complete['error_surface'] = captured_result['error_surface']+ # A gateway-owned refusal brings its own descriptor (``session_cron.execute``); every other failed+ # turn gets the one the TUI path builds from the same result, so the viewer shows the right card.+ surface = captured_result.get('error_surface')+ if not isinstance(surface, dict) and complete['status'] == 'error':+ from agent.error_surface import build_error_surface_from_result+ surface = build_error_surface_from_result(+ captured_result, provider=str(captured_result.get('provider') or ''),+ model=str(captured_result.get('model') or ''))+ if isinstance(surface, dict):+ complete['error_surface'] = surfaceif response and captured_result.get('response_reused'):complete['response_reused'] = Trueif captured_result.get('local_viewer'):diff --git a/tests/gateway/test_authority_turn_error_surface.py b/tests/gateway/test_authority_turn_error_surface.pynew file mode 100644index 00000000000..5e59d7cbd77--- /dev/null+++ b/tests/gateway/test_authority_turn_error_surface.py@@ -0,0 +1,87 @@+"""A turn that fails on the session authority completes with the same ``error_surface`` the TUI+path sends, so the Desktop renders the failure's own card (free tier at capacity, rate limit)+instead of the generic one."""+import io+from types import SimpleNamespace++import pytest++from gateway.config import Platform++_FREE_TIER_FULL = {'free_tier': {'kind': 'at_capacity', 'message': 'The free tier is full right now.'},+ 'failure_reason': 'rate_limit', 'failure_retryable': True, 'error': 'HTTP 429'}+_RATE_LIMITED = {'failure_reason': 'rate_limit', 'failure_retryable': True, 'failure_resets_at': 1900000000.0,+ 'error': 'HTTP 429: slow down'}+++def _authority_turn(platform, failure):+ """Run one failed turn through the authority's in-process TurnRunner: ``(response, captured)``."""+ from gateway.run_turn_runner import TurnRunner+ from gateway.session import SessionSource+ from gateway.session_results import execution_result+ from gateway.turn_context import TurnContext+ from tests.gateway.test_local_viewer_events_submit import _gateway_runner, _RecordingAgent++ class _FailingAgent(_RecordingAgent):+ def run_conversation(self, message, **kwargs):+ return {'final_response': '', 'messages': [], 'failed': True, 'completed': False,+ 'provider': 'nous', 'model': 'free-model', **failure}++ ctx = TurnContext(+ source=SessionSource(platform=platform, chat_id='sid', user_id='u'),+ message='hi', history=[], session_id='sid', session_key='key', user_config={},+ AIAgent=_FailingAgent, resolve_display_setting=lambda *_a: False,+ _run_still_current=lambda: True, _hooks_ref=SimpleNamespace(loaded_hooks=False))+ captured = {}+ token = execution_result.set(captured)+ try:+ turn = TurnRunner(_gateway_runner(), ctx)+ turn._approval_owner = (SimpleNamespace(sessions={'sid': SimpleNamespace(tool_progress_mode=None)},+ profile_id='p', adopt_agent=lambda *a: None), 'sid', 1)+ delivered = turn.run_sync()+ finally:+ execution_result.reset(token)+ return delivered['final_response'], captured+++def _complete(response, captured):+ from gateway.session_results import prepare_result+ from gateway.session_settlement_recovery import completion_payload+ row = {'admission_id': 'a1', 'request_id': 'r1', 'payload': {'text': 'hi'}}+ outcome, _stored = prepare_result(row, response, 'completed', captured)+ return completion_payload(row, {'outcome': outcome}, response, captured)++[email protected]('platform', [Platform.LOCAL, Platform.TELEGRAM])+def test_free_tier_at_capacity_turn_completes_with_its_own_surface(platform):+ complete = _complete(*_authority_turn(platform, _FREE_TIER_FULL))+ assert complete['status'] == 'error'+ assert complete['error_surface']['code'] == 'free_tier_at_capacity'+ assert complete['error_surface']['message'] == 'The free tier is full right now.'+++def test_rate_limited_turn_completes_with_rate_limit_and_reset_time():+ from tui_gateway.contracts.registry import EVENTS++ complete = _complete(*_authority_turn(Platform.LOCAL, _RATE_LIMITED))+ surface = complete['error_surface']+ assert (surface['code'], surface['retryable'], surface['resets_at']) == ('rate_limit', True, 1900000000.0)+ EVENTS['message.complete'].payload.model_validate(+ {k: v for k, v in complete.items() if k not in ('content', 'admission_id', 'outcome')})+++def test_a_managed_worker_turn_carries_the_free_tier_failure_to_the_owner():+ from agent.managed_worker import accept_result, encode_frame, read_frame, result_frame++ raw = {'final_response': '', 'failed': True, 'completed': False, 'provider': 'nous', 'model': 'free-model',+ 'messages': [], **_FREE_TIER_FULL}+ wire = read_frame(io.BytesIO(encode_frame({'type': 'result', 'result': result_frame(raw)})))+ accepted, usage = accept_result(wire['result'])+ # The owner's projection of a finished worker turn (``session_managed_worker``).+ complete = _complete('', {'result': {**accepted, 'local_viewer': True}, 'usage': usage})+ assert complete['error_surface']['code'] == 'free_tier_at_capacity'+++def test_a_successful_turn_completes_without_a_surface():+ complete = _complete('done', {'result': {'final_response': 'done', 'messages': []}, 'usage': {}})+ assert complete['status'] == 'complete' and 'error_surface' not in complete