Skip to content

The agent that grows with you

fix: GatewayRPCError keeps the owner's numeric code and bounded data

Teknium399c88242aba
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.py
index d72c8782ad4..da9623c1aa5 100644
--- a/hermes_cli/gateway_client.py
+++ b/hermes_cli/gateway_client.py
@@ -28,7 +28,49 @@ class GatewayClientError(ValueError):
class GatewayRPCError(GatewayClientError):
- """A received owner refusal, distinct from an ambiguous transport failure."""
+ """A received owner refusal, distinct from an ambiguous transport failure.
+
+ ``str(exc)`` is the bounded reason code; ``code`` is the frame's numeric JSON-RPC code (``None``
+ when absent or not an int) and ``data`` its bounded, scalar-only ``error.data`` mapping."""
+
+ def __init__(self, reason, code=None, data=None):
+ super().__init__(reason)
+ self.code = code
+ self.data = data or {}
+
+
+def _bounded_reason(value):
+ return value if isinstance(value, str) and value.replace("_", "").isalnum() and len(value) <= 80 else None
+
+
+def _bounded_error_data(data):
+ """At most 16 short keys whose values are bool/int/None, short strings or short lists of them;
+ anything else (nested objects, raw remote diagnostics) is dropped, never forwarded."""
+ def scalar(value):
+ return value is None or isinstance(value, (bool, int)) or (isinstance(value, str) and len(value) <= 200)
+ if not isinstance(data, dict):
+ return {}
+ out = {}
+ for key, value in data.items():
+ if len(out) >= 16 or not isinstance(key, str) or len(key) > 64:
+ continue
+ if scalar(value):
+ out[key] = value
+ elif isinstance(value, list) and len(value) <= 16 and all(scalar(item) for item in value):
+ out[key] = list(value)
+ return out
+
+
+def rpc_error(error):
+ """The ``GatewayRPCError`` for one received ``error`` member: only bounded reason codes, never
+ raw remote diagnostics. A free-text message (``unknown method: x``) falls back to the bounded
+ ``data.reason`` the owner sends beside it, then to ``request_failed``."""
+ error = error if isinstance(error, dict) else {}
+ data = _bounded_error_data(error.get("data"))
+ code = error.get("code")
+ reason = _bounded_reason(error.get("message", "request_failed")) or _bounded_reason(data.get("reason"))
+ return GatewayRPCError(reason or "request_failed",
+ code if isinstance(code, int) and not isinstance(code, bool) else None, data)
class GatewayUnavailableError(GatewayClientError):
@@ -65,11 +107,7 @@ class GatewayClient:
future = self.pending.get(frame.get("id"))
if future is not None and not future.done():
if "error" in frame:
- # Only bounded authority reason codes, never raw remote diagnostics.
- reason = frame["error"].get("message", "request_failed")
- if not isinstance(reason, str) or not reason.replace("_", "").isalnum() or len(reason) > 80:
- reason = "request_failed"
- future.set_exception(GatewayRPCError(reason))
+ future.set_exception(rpc_error(frame["error"]))
else:
future.set_result(frame.get("result", {}))
elif "method" in frame:
diff --git a/tests/hermes_cli/test_gateway_client_rpc.py b/tests/hermes_cli/test_gateway_client_rpc.py
new file mode 100644
index 00000000000..25f522b661a
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_client_rpc.py
@@ -0,0 +1,47 @@
+"""The viewer RPC client keeps an owner refusal's structured verdict (code + bounded data)."""
+import asyncio
+import json
+
+import pytest
+
+from hermes_cli.gateway_client import GatewayClient, GatewayRPCError
+
+
+class _Socket:
+ """One scripted owner: answers each request with the frame ``reply(request)`` builds."""
+
+ def __init__(self, reply):
+ self.reply = reply
+ self.inbox = asyncio.Queue()
+
+ async def send(self, raw):
+ frame = self.reply(json.loads(raw))
+ if frame is not None:
+ await self.inbox.put(json.dumps(frame))
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ return await self.inbox.get()
+
+
+async def test_rpc_error_keeps_numeric_code_and_bounded_data():
+ errors = {
+ 'session.mutate': {'code': 4001, 'message': 'invalid_params', 'data': {
+ 'reason': 'invalid_params', 'fields': ['payload.title'],
+ 'trace': {'nested': 'remote diagnostics'}, 'blob': 'x' * 5000}},
+ 'nope': {'code': -32601, 'message': 'unknown method: nope', 'data': {'reason': 'unknown_method'}},
+ }
+ socket = _Socket(lambda req: {'jsonrpc': '2.0', 'id': req['id'], 'error': errors[req['method']]})
+ async with GatewayClient(socket) as client:
+ with pytest.raises(GatewayRPCError) as refused:
+ await client.rpc('session.mutate', session_id='s')
+ assert str(refused.value) == 'invalid_params' and refused.value.code == 4001
+ # Scalar facts survive; nested objects and oversized strings never reach the caller.
+ assert refused.value.data == {'reason': 'invalid_params', 'fields': ['payload.title']}
+ with pytest.raises(GatewayRPCError) as unknown:
+ await client.rpc('nope')
+ # Free-text messages stay bounded: the owner's reason code, not the raw sentence.
+ assert str(unknown.value) == 'unknown_method' and unknown.value.code == -32601