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."""