Skip to content

The agent that grows with you

perf(bot-mode): cold DM hops skip the live /models probe; relay replies land within 250ms

Teknium32fe1293244f
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index 4ed608fd246..fb78714afdb 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -370,6 +370,58 @@ def _save_model_metadata_disk_cache(data: Dict[str, Dict[str, Any]]) -> None:
except Exception as e:
logger.debug("Failed to save OpenRouter model metadata disk cache: %s", e)
+def _get_endpoint_metadata_cache_path() -> Path:
+ """On-disk memo of remote ``/models`` probes (see ``_endpoint_disk_cache_get``)."""
+ from hermes_constants import get_hermes_home
+ return get_hermes_home() / "cache" / "endpoint_model_metadata.json"
+
+
+def _endpoint_disk_cache_get(normalized: str) -> Optional[Dict[str, Dict[str, Any]]]:
+ """Return a still-fresh (``_ENDPOINT_MODEL_CACHE_TTL``) disk memo for one endpoint.
+
+ The in-memory endpoint cache only helps within a process. One-shot runs
+ (``hermes -q``, cron, every Bot Mode DM hop) start cold and re-probed the
+ live ``/models`` endpoint on every launch — 0.3–0.6s of pure network per
+ process on Nous, whose persistent context cache is bypassed by design so
+ the portal stays authoritative. This memo keeps that authority (same TTL
+ as the in-memory cache, so reconciliation still lands within 5 minutes)
+ while sharing the answer across processes. Local endpoints are never
+ memoized: their loaded context is transient (LM Studio reloads).
+ """
+ try:
+ with _get_endpoint_metadata_cache_path().open("r", encoding="utf-8") as f:
+ data = json.load(f)
+ entry = data.get(normalized) if isinstance(data, dict) else None
+ if not isinstance(entry, dict):
+ return None
+ if (time.time() - float(entry.get("at", 0))) >= _ENDPOINT_MODEL_CACHE_TTL:
+ return None
+ models = entry.get("models")
+ return models if isinstance(models, dict) else None
+ except Exception:
+ return None
+
+
+def _endpoint_disk_cache_put(normalized: str, cache: Dict[str, Dict[str, Any]]) -> None:
+ """Memoize a successful remote ``/models`` probe; expired siblings are dropped."""
+ try:
+ path = _get_endpoint_metadata_cache_path()
+ data: Dict[str, Any] = {}
+ if path.exists():
+ with path.open("r", encoding="utf-8") as f:
+ loaded = json.load(f)
+ if isinstance(loaded, dict):
+ now = time.time()
+ data = {
+ k: v for k, v in loaded.items()
+ if isinstance(v, dict) and (now - float(v.get("at", 0))) < _ENDPOINT_MODEL_CACHE_TTL
+ }
+ data[normalized] = {"at": time.time(), "models": cache}
+ atomic_json_write(path, data, indent=0, separators=(",", ":"))
+ except Exception as e:
+ logger.debug("Failed to save endpoint model metadata disk cache: %s", e)
+
+
# Descending tiers for context length probing when the model is unknown.
# We start at 256K (covers GPT-5.x, many current large-context models) and
# step down on context-length errors until one works. Tier[0] is also the
@@ -1362,6 +1414,12 @@ def fetch_endpoint_model_metadata(
cached_at = _endpoint_model_metadata_cache_time.get(normalized, 0)
if cached is not None and (time.time() - cached_at) < _ENDPOINT_MODEL_CACHE_TTL:
return cached
+ if not is_local_endpoint(normalized):
+ memo = _endpoint_disk_cache_get(normalized)
+ if memo is not None:
+ _endpoint_model_metadata_cache[normalized] = memo
+ _endpoint_model_metadata_cache_time[normalized] = time.time()
+ return memo
# Blackholed endpoint: every candidate below would spend its full 5s
# connect budget. Returned empty rather than cached, so the endpoint is
@@ -1536,6 +1594,8 @@ def fetch_endpoint_model_metadata(
_endpoint_model_metadata_cache[normalized] = cache
_endpoint_model_metadata_cache_time[normalized] = time.time()
+ if cache and not is_local_endpoint(normalized):
+ _endpoint_disk_cache_put(normalized, cache)
return cache
except Exception as exc:
last_error = exc
diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py
index a6334eb71c9..3d0ccd4101c 100644
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@ -799,6 +799,36 @@ class TestFetchEndpointModelMetadata:
not_found.close.assert_called_once()
success.close.assert_called_once()
+ def test_remote_probe_is_memoized_on_disk_across_processes(self, tmp_path, monkeypatch):
+ """A fresh process (cleared in-memory cache) must answer from the disk
+ memo within the TTL instead of re-probing the endpoint — the cost every
+ one-shot Bot Mode DM hop paid on startup. Expired memos re-probe."""
+ import agent.model_metadata as mm
+
+ monkeypatch.setattr(
+ mm, "_get_endpoint_metadata_cache_path", lambda: tmp_path / "endpoint_model_metadata.json"
+ )
+ success = MagicMock()
+ success.status_code = 200
+ success.json.return_value = {"data": [{"id": "test/model", "context_length": 32768}]}
+
+ with patch("agent.model_metadata.requests.get", return_value=success) as mock_get:
+ assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768
+ # "New process": drop the in-memory cache only.
+ mm._endpoint_model_metadata_cache.clear()
+ mm._endpoint_model_metadata_cache_time.clear()
+ assert mm.fetch_endpoint_model_metadata("https://custom.example/v1")["test/model"]["context_length"] == 32768
+ mock_get.assert_called_once()
+
+ # Past the TTL the memo is stale and the endpoint is probed again.
+ mm._endpoint_model_metadata_cache.clear()
+ mm._endpoint_model_metadata_cache_time.clear()
+ with patch("agent.model_metadata.time.time", return_value=time.time() + mm._ENDPOINT_MODEL_CACHE_TTL + 1), patch(
+ "agent.model_metadata.requests.get", return_value=success
+ ) as mock_get:
+ mm.fetch_endpoint_model_metadata("https://custom.example/v1")
+ mock_get.assert_called_once()
+
# =========================================================================
# Nous Portal context-window resolution (provider="nous")
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.py
index b7b9f4a37ff..7b9fb528f1b 100644
--- a/tests/tools/test_bot_relay.py
+++ b/tests/tools/test_bot_relay.py
@@ -151,6 +151,31 @@ def test_waiter_command_quotes_and_targets_reply_file(root):
assert "rm -rf" not in cmd # sanity: single quoted -c payload
+def test_waiter_picks_up_reply_within_a_sub_second_cadence(root):
+ """The reply file is written once; the waiter must notice it fast, not
+ on a multi-second sleep (dead air the sender's completion notification
+ inherits on every cross-machine reply)."""
+ import shlex
+ import subprocess
+ import threading
+ import time
+
+ env = {"id": "c" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}
+ reply_path = bot_relay.relay_root(root) / bot_relay.REPLIES_DIR / f"{env['id']}.json"
+ reply_path.parent.mkdir(parents=True, exist_ok=True)
+
+ def write_reply():
+ time.sleep(0.3)
+ reply_path.write_text(json.dumps({"reply": "pong"}), encoding="utf-8")
+
+ threading.Thread(target=write_reply, daemon=True).start()
+ started = time.monotonic()
+ proc = subprocess.run(shlex.split(bot_relay.waiter_command(root, env)), capture_output=True, text=True, timeout=10)
+ elapsed = time.monotonic() - started
+ assert proc.returncode == 0 and "pong" in proc.stdout
+ assert elapsed < 1.5, f"waiter took {elapsed:.2f}s to notice a reply written at 0.3s"
+
+
def test_roster_rejects_connection_id_outside_handle_charset(root):
bad = [
{"profile": "researcher", "handle": "researcher", "connection_id": "vps'); print(1)"},
diff --git a/tools/bot_relay.py b/tools/bot_relay.py
index 08c6d3b044e..bc74a5952e5 100644
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@ -524,7 +524,10 @@ def waiter_command(root: Path | str, envelope: dict) -> str:
" print('Reply from ' + label + ':')\n"
" print(d.get('reply') or '(empty reply)')\n"
" sys.exit(0)\n"
- " time.sleep(2)\n"
+ # 250ms cadence: the reply file is written once by the target
+ # gateway's deliver path; a 2s sleep here added up to 2s of dead
+ # air to every cross-machine reply for no benefit (stat is cheap).
+ " time.sleep(0.25)\n"
f"print('No reply from ' + label + ' within {REPLY_WAIT_SECONDS}s. The message may "
"still be delivered when the Desktop reconnects; do not resend blindly.')\n"
"sys.exit(1)\n"