From 4fa929e0c67f0b3c2b314f91139c9b8d3503f633 Mon Sep 17 00:00:00 2001 From: Mattheinrichs Date: Tue, 17 Nov 2026 11:26:49 +0000 Subject: [PATCH] fix: send lowercase session keys so prompt caching survives Home Assistant hands out conversation ids as uppercase ULIDs. OpenClaw session keys are canonically lowercase, so an uppercase key is refused on the session write and rewritten into the request envelope on the next turn. That makes the history non-append-only, which invalidates the provider prompt cache and forces a full prefill of the agent prompt every turn. Normalise the base id and the agent prefix in scope_agent_session_id, and cover the uppercase base id and already-scoped uppercase key with tests. --- custom_components/openclaw/helpers.py | 19 +++++++++++++++---- tests/test_helpers.py | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/custom_components/openclaw/helpers.py b/custom_components/openclaw/helpers.py index 0edd733..8ed1896 100644 --- a/custom_components/openclaw/helpers.py +++ b/custom_components/openclaw/helpers.py @@ -6,10 +6,21 @@ def scope_agent_session_id(base_id: str, agent_id: str | None) -> str: - """Namespace a session key for an OpenClaw agent without double-prefixing.""" - if not agent_id or base_id.startswith(f"agent:{agent_id}:"): - return base_id - return f"agent:{agent_id}:{base_id}" + """Namespace a session key for an OpenClaw agent without double-prefixing. + + OpenClaw session keys are canonically lowercase. Home Assistant hands out + conversation ids as uppercase ULIDs, and an uppercase base id is echoed + back into the request envelope, refused on the session write, and rewritten + on the next turn. That rewrite breaks the append-only history the provider + prompt cache depends on, so every turn re-prefills the whole prompt. + """ + key = base_id.lower() + if not agent_id: + return key + prefix = f"agent:{agent_id.lower()}:" + if key.startswith(prefix): + return key + return f"{prefix}{key}" def resolve_active_model( diff --git a/tests/test_helpers.py b/tests/test_helpers.py index f012724..99258dc 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -35,6 +35,20 @@ def test_is_idempotent_for_an_already_scoped_key(self) -> None: "agent:home:assist_user_123", ) + def test_lowercases_an_uppercase_ha_conversation_id(self) -> None: + self.assertEqual( + helpers.scope_agent_session_id("01M7KF8J84WTQTZWH6FCDSP4GN", "voice"), + "agent:voice:01m7kf8j84wtqtzwh6fcdsp4gn", + ) + + def test_lowercases_an_already_scoped_uppercase_key(self) -> None: + self.assertEqual( + helpers.scope_agent_session_id( + "agent:voice:01M7KF8J84WTQTZWH6FCDSP4GN", "voice" + ), + "agent:voice:01m7kf8j84wtqtzwh6fcdsp4gn", + ) + class ResolveActiveModelTests(unittest.TestCase): """Protect an explicit HA model choice across coordinator refreshes."""