Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions custom_components/openclaw/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down