diff --git a/plugin/pheby/adapter.py b/plugin/pheby/adapter.py index a00107e..bb6ddcc 100644 --- a/plugin/pheby/adapter.py +++ b/plugin/pheby/adapter.py @@ -69,6 +69,7 @@ class PhebyAdapter(BasePlatformAdapter): self._server: Any = None self._loop: Optional[asyncio.AbstractEventLoop] = None self._drafts: Dict[str, Dict[str, Any]] = {} # conv → draft state + self._tool_desc_cache: Optional[Dict[str, str]] = None @property def authorization_is_upstream(self) -> bool: @@ -271,6 +272,36 @@ class PhebyAdapter(BasePlatformAdapter): logger.debug("[pheby] tool session lookup failed", exc_info=True) return None + def _tool_description(self, tool_name: str) -> Optional[str]: + """First line of the tool's catalog description, for the tool-call UI. + + Sourced from the same schema catalog the gateway sends to the model + (``model_tools.get_tool_definitions``) — cheap lookup, memoized per + toolset config. The UI clamps this to 2 lines; unknown tools send + no field at all (clients hide undefined data rather than showing a + placeholder). + """ + if not tool_name: + return None + try: + from model_tools import get_tool_definitions + if self._tool_desc_cache is None: + self._tool_desc_cache = { + str(td.get("function", {}).get("name") or ""): + str(td.get("function", {}).get("description") or "").strip() + for td in get_tool_definitions(quiet_mode=True) + } + desc = self._tool_desc_cache.get(tool_name) or None + except Exception: + logger.debug("[pheby] tool description lookup failed", exc_info=True) + self._tool_desc_cache = {} + return None + if not desc: + return None + # Keep the first descriptive line; UI shows max 2 lines. + first_line = desc.splitlines()[0].strip() + return proto.safe_str(first_line, 300) + def on_pre_tool_call(self, **kwargs: Any) -> None: conversation_id = self._conversation_for_session_id( str(kwargs.get("session_id") or "")) @@ -278,16 +309,20 @@ class PhebyAdapter(BasePlatformAdapter): return tool_id = str(kwargs.get("tool_call_id") or f"t-{proto.new_id()[:12]}") + tool_name = str(kwargs.get("tool_name") or "tool") event = { "type": proto.S_TOOL_EVENT, "conversation_id": conversation_id, "run_id": hermes_bridge.active_run_id(conversation_id), "tool_call_id": tool_id, - "tool_name": str(kwargs.get("tool_name") or "tool"), + "tool_name": tool_name, "status": "running", "args_redacted": _redact_args(kwargs.get("args")), "ts": proto.now_iso(), } + description = self._tool_description(tool_name) + if description: + event["description"] = description hermes_bridge.record_tool_event(conversation_id, event) self.schedule_broadcast(event) @@ -324,6 +359,9 @@ class PhebyAdapter(BasePlatformAdapter): # gets outcome status; verbose content stays in Hermes. "ts": proto.now_iso(), } + description = self._tool_description(tool_name) + if description: + event["description"] = description error_message = kwargs.get("error_message") if error_message and event["status"] == "failed": event["error"] = proto.safe_str(error_message, 200) diff --git a/scripts/verify_lineage.py b/scripts/verify_lineage.py new file mode 100644 index 0000000..3d476d9 --- /dev/null +++ b/scripts/verify_lineage.py @@ -0,0 +1,49 @@ +"""Verify (source, session_key) lineage read for the Home Assistant chat.""" +from pathlib import Path +import os +import sys + +os.environ["HERMES_HOME"] = "/opt/data" +sys.path.insert(0, "/opt/hermes") + +from hermes_state import SessionDB # noqa: E402 + + +def lineage_rows(db, session_id): + row = db.get_session(session_id) + if row is None: + return db.get_messages_as_conversation(session_id, include_row_ids=True) + session_key = row.get("session_key") + source = row.get("source") + ids = [session_id] + if session_key and source: + with db._read_ctx() as conn: + ids = [r["id"] for r in conn.execute( + "SELECT id FROM sessions WHERE session_key = ?" + " AND source = ? ORDER BY started_at", + (session_key, source)).fetchall()] + print(" lineage ids:", ids) + rows_ = db._fetch_conversation_rows(ids, " AND active = 1", with_session_id=False) + return db._rows_to_conversation(rows_, session_id=session_id, include_row_ids=True, include_ancestors=False, repair_alternation=False) + + +def main() -> None: + db = SessionDB(Path("/opt/data/state.db")) + sid = "20260910_055216_dcaa623c" # Home Assistant chat, current generation + + rows = db.get_messages_as_conversation(sid, include_row_ids=True) + conv = [r for r in rows if r.get("role") in ("user", "assistant")] + print("current-only -> user/assistant:", len(conv)) + + rows = lineage_rows(db, sid) + conv = [r for r in rows if r.get("role") in ("user", "assistant")] + print("lineage -> user/assistant:", len(conv)) + if conv: + print(" first:", str(conv[0].get("content"))[:70].replace("\n", " ")) + print(" last :", str(conv[-1].get("content"))[:70].replace("\n", " ")) + ids = [r.get("_row_id") for r in conv] + print(" row ids monotonic:", ids == sorted(ids), "| dupes:", len(ids) != len(set(ids))) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tests/test_pheby.py b/tests/test_pheby.py index 97911be..28b44cb 100644 --- a/tests/test_pheby.py +++ b/tests/test_pheby.py @@ -609,6 +609,83 @@ class TestBridge: assert ev["status"] == "completed" assert ev["duration_ms"] == 1234 + @pytest.mark.asyncio + async def test_tool_events_carry_description(self, tmp_path, monkeypatch): + """pre/post tool events include the catalog description (first line).""" + server = make_server(tmp_path) + client = FakeClientConnection() + client.authenticated = True + server._clients["t"] = client + + from pheby.adapter import PhebyAdapter + from gateway.config import PlatformConfig + real = PhebyAdapter(PlatformConfig( + enabled=True, extra={"secret": "test-secret-abc123"})) + real._server = server + real._loop = asyncio.get_running_loop() + monkeypatch.setattr(real, "_conversation_for_session_id", + lambda _sid: "conv1") + + import model_tools + monkeypatch.setattr( + model_tools, "get_tool_definitions", lambda **kw: [ + {"function": {"name": "web_search", + "description": "Search the web for " + "information.\nSecond line."}}, + ]) + from pheby import hermes_bridge + real.on_pre_tool_call( + session_id="s1", tool_name="web_search", + tool_call_id="call-d", args={}) + real.on_post_tool_call( + session_id="s1", tool_name="web_search", + tool_call_id="call-d", status="ok", duration_ms=5) + await asyncio.sleep(0) + tool_events = [e for e in client.ws.events() + if e["type"] == proto.S_TOOL_EVENT] + assert len(tool_events) == 2 + assert all(ev.get("description") == "Search the web for information." + for ev in tool_events) + # Runtime snapshot (reconnect replay) carries it too. The bridge's + # tool bucket is module-global across tests — look up by call id. + snap = hermes_bridge.runtime_snapshot("conv1") + snap_ev = next(t for t in snap["tools"] + if t["tool_call_id"] == "call-d") + assert snap_ev["description"] == "Search the web for information." + + @pytest.mark.asyncio + async def test_unknown_tool_event_has_no_description(self, tmp_path, + monkeypatch): + server = make_server(tmp_path) + client = FakeClientConnection() + client.authenticated = True + server._clients["t"] = client + + from pheby.adapter import PhebyAdapter + from gateway.config import PlatformConfig + real = PhebyAdapter(PlatformConfig( + enabled=True, extra={"secret": "test-secret-abc123"})) + real._server = server + real._loop = asyncio.get_running_loop() + monkeypatch.setattr(real, "_conversation_for_session_id", + lambda _sid: "conv1") + + import model_tools + monkeypatch.setattr( + model_tools, "get_tool_definitions", lambda **kw: [ + {"function": {"name": "web_search", + "description": "Search the web."}}, + ]) + real.on_pre_tool_call( + session_id="s1", tool_name="mystery_tool", + tool_call_id="call-x", args={}) + await asyncio.sleep(0) + ev = [e for e in client.ws.events() + if e["type"] == proto.S_TOOL_EVENT][-1] + # Hide-undefined-data: no description key at all, no placeholder. + assert "description" not in ev + assert ev["tool_name"] == "mystery_tool" + @pytest.mark.asyncio async def test_approval_push_and_resolve_roundtrip(self, tmp_path, monkeypatch):