fix(peer): a peer's real 'hermes' profile keeps @hermes DMs, runs, status and stop
Review finding "Messages reach the wrong bot": _base_url rewrote every
<peer>/hermes target to /p/default, so a peer that still serves a real
pre-reservation 'hermes' profile (get_profile_dir keeps those resolving,
and the server keeps such a profile ahead of the alias) had its DMs, runs,
status and stop requests delivered to its default profile instead.
The client now addresses /p/hermes first and uses /p/default only when
the peer itself answers that it has no such profile: the 404 its
/p/<profile>/ prefix middleware returns before any handler runs
({"error": "Unknown or unconfigured profile"}). A handler 404, a 5xx or a
transport failure is no verdict and never reroutes. Peers without the
server-side alias (older hosts) still reach their default profile.
This commit is contained in:
@@ -24,6 +24,11 @@ BOT_CHAT_TITLE = "Bot Chat"
|
||||
_PEER_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
|
||||
_PROFILE_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")
|
||||
|
||||
# The @handle Bot Mode shows for a host's default profile, and the body of the 404 a peer's
|
||||
# /p/<profile>/ prefix middleware returns for a profile it does not serve (gateway/platforms/api_server.py).
|
||||
DEFAULT_PROFILE_HANDLE = "hermes"
|
||||
_UNKNOWN_PROFILE_ERROR = "Unknown or unconfigured profile"
|
||||
|
||||
# One synchronous agent turn can legitimately take minutes.
|
||||
DM_TIMEOUT_S = 600
|
||||
LIST_TIMEOUT_S = 30
|
||||
@@ -91,15 +96,40 @@ def _request(
|
||||
def _base_url(peer: dict, profile: str | None) -> str:
|
||||
url = str(peer.get("url") or "").rstrip("/")
|
||||
if profile:
|
||||
# Multiplex mirror: same handlers, scoped to the named profile. The mirror is keyed by
|
||||
# profile name, and Bot Mode shows a peer's default profile as @hermes (#118076); an
|
||||
# older peer has no alias for it on its side.
|
||||
if profile.lower() == "hermes":
|
||||
profile = "default"
|
||||
# Multiplex mirror: same handlers, scoped to the named profile.
|
||||
return f"{url}/p/{urllib.parse.quote(profile, safe='')}"
|
||||
return url
|
||||
|
||||
|
||||
def _peer_lacks_profile(exc: Exception) -> bool:
|
||||
"""True only for the peer's own "no such profile" verdict: the 404 its /p/<profile>/ prefix
|
||||
middleware returns before any handler runs. A handler's 404 (unknown run or session) carries
|
||||
``{"error": {"message": ...}}`` and a transport failure is no verdict at all."""
|
||||
if not isinstance(exc, urllib.error.HTTPError) or exc.code != 404:
|
||||
return False
|
||||
try:
|
||||
body = json.loads(exc.read().decode("utf-8", "replace"))
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
return isinstance(body, dict) and body.get("error") == _UNKNOWN_PROFILE_ERROR
|
||||
|
||||
|
||||
def _resolve_base(peer: dict, profile: str | None, key: str) -> str:
|
||||
"""The mirror a target addresses. Bot Mode shows a peer's default profile as @hermes
|
||||
(#118076), but a peer may also serve a real pre-reservation profile named ``hermes``, which
|
||||
must keep winning — so ``/p/hermes`` is tried first and ``/p/default`` is used only when the
|
||||
peer itself answers that it has no such profile (an older peer has no alias on its side)."""
|
||||
base = _base_url(peer, profile)
|
||||
if not profile or profile.lower() != DEFAULT_PROFILE_HANDLE:
|
||||
return base
|
||||
try:
|
||||
_request(f"{base}/health", key)
|
||||
except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:
|
||||
if _peer_lacks_profile(exc):
|
||||
return _base_url(peer, "default")
|
||||
return base
|
||||
|
||||
|
||||
def _find_bot_chat(base: str, key: str) -> str | None:
|
||||
"""The remote canonical Bot Chat's session id, or None.
|
||||
|
||||
@@ -413,7 +443,7 @@ def cmd_peer(args) -> int:
|
||||
except (LookupError, PermissionError) as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 1
|
||||
base = _base_url(peer, profile)
|
||||
base = _resolve_base(peer, profile, key)
|
||||
if action in {"status", "stop"}:
|
||||
return _peer_run_ctl(args, action, peer_name, profile, base, key)
|
||||
message = _message_from_args(args)
|
||||
|
||||
@@ -41,9 +41,70 @@ def test_base_url_bare_and_profile():
|
||||
assert peer_cmd._base_url(peer, "researcher") == "http://spark.lan:8377/p/researcher"
|
||||
|
||||
|
||||
def test_base_url_addresses_the_default_handle_by_profile_name():
|
||||
# Bot Mode shows a peer's default profile as @hermes; an older peer serves it only at /p/default (#118076).
|
||||
assert peer_cmd._base_url({"url": "http://spark.lan:8377"}, "Hermes") == "http://spark.lan:8377/p/default"
|
||||
class _ProfilePeer(BaseHTTPRequestHandler):
|
||||
"""A peer whose /p/<profile>/ prefix answers like the real api_server middleware: a profile it
|
||||
does not serve is a 404 ``{"error": "Unknown or unconfigured profile"}`` before any handler."""
|
||||
|
||||
served: set = set()
|
||||
probe_status: int = 200
|
||||
hits: list = []
|
||||
|
||||
def _answer(self):
|
||||
_, _, profile, rest = (self.path.split("/", 3) + ["", "", "", ""])[:4]
|
||||
type(self).hits.append(self.path)
|
||||
if profile not in type(self).served:
|
||||
return 404, {"error": "Unknown or unconfigured profile"}
|
||||
if rest == "health":
|
||||
return type(self).probe_status, {"status": "ok"}
|
||||
if rest.startswith("api/sessions?"):
|
||||
return 200, {"data": [{"id": f"bc_{profile}", "title": "Bot Chat"}]}
|
||||
if rest.endswith("/chat"):
|
||||
return 200, {"session_id": f"bc_{profile}", "message": {"content": f"from {profile}"}}
|
||||
return 200, {"run_id": "run_1", "status": f"run in {profile}"}
|
||||
|
||||
def _reply(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length", 0)))
|
||||
status, payload = self._answer()
|
||||
body = json.dumps(payload).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
do_GET = do_POST = _reply
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("served,probe_status,expected", [
|
||||
({"default", "hermes"}, 200, "hermes"), # a real legacy 'hermes' profile keeps precedence
|
||||
({"default"}, 200, "default"), # the peer says it has none: the @hermes handle is its default
|
||||
({"default", "hermes"}, 503, "hermes"), # a transient failure is no verdict, so never reroute
|
||||
])
|
||||
def test_hermes_handle_reaches_the_profile_the_peer_serves(monkeypatch, capsys, served, probe_status, expected):
|
||||
"""``box/hermes`` names the peer's real 'hermes' profile when it has one, and its default
|
||||
profile (Bot Mode's @hermes handle, #118076) only when the peer answers it has no such profile;
|
||||
dm, status and stop all address the same mirror."""
|
||||
_ProfilePeer.served, _ProfilePeer.probe_status, _ProfilePeer.hits = served, probe_status, []
|
||||
server = HTTPServer(("127.0.0.1", 0), _ProfilePeer)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"box": {"url": f"http://127.0.0.1:{server.server_port}"}})
|
||||
monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")
|
||||
try:
|
||||
replies = [
|
||||
peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="box/hermes", message="hi", json=True)),
|
||||
peer_cmd.cmd_peer(SimpleNamespace(peer_action="status", target="box/hermes", run_id="run_1", json=True)),
|
||||
peer_cmd.cmd_peer(SimpleNamespace(peer_action="stop", target="box/hermes", run_id="run_1", json=True)),
|
||||
]
|
||||
finally:
|
||||
server.shutdown()
|
||||
out = [json.loads(line) for line in capsys.readouterr().out.splitlines()]
|
||||
assert replies == [0, 0, 0]
|
||||
assert [out[0]["reply"], out[1]["status"], out[2]["status"]] == [
|
||||
f"from {expected}", f"run in {expected}", f"run in {expected}"]
|
||||
assert {hit.split("/")[2] for hit in _ProfilePeer.hits if not hit.endswith("/health")} == {expected}
|
||||
|
||||
|
||||
# ── registry round-trip (isolated config) ────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user