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
8 changes: 8 additions & 0 deletions src/claude_agent_sdk/_internal/message_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ def parse_message(data: dict[str, Any]) -> Message | None:
raise MessageParseError(
f"Missing required field in user message: {e}", data
) from e
except (TypeError, AttributeError) as e:
# e.g. data["message"] is not a dict, so indexing into it fails
raise MessageParseError(f"Malformed user message: {e}", data) from e

case "assistant":
try:
Expand Down Expand Up @@ -222,6 +225,11 @@ def parse_message(data: dict[str, Any]) -> Message | None:
raise MessageParseError(
f"Missing required field in assistant message: {e}", data
) from e
except (TypeError, AttributeError) as e:
# e.g. data["message"] is not a dict, so indexing into it fails
raise MessageParseError(
f"Malformed assistant message: {e}", data
) from e

case "system":
try:
Expand Down
20 changes: 16 additions & 4 deletions src/claude_agent_sdk/_internal/session_store_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,25 @@


def _store_implements(store: SessionStore, method: str) -> bool:
"""True if ``store`` overrides ``method`` rather than inheriting the
Protocol default that raises :class:`NotImplementedError`."""
"""True if ``store`` provides ``method`` rather than inheriting the
Protocol default that raises :class:`NotImplementedError`.

Resolved against the instance rather than the class: ``SessionStore`` is a
structural Protocol, so an implementation assigned in ``__init__``
(delegation, ``functools.partial``, a test double) counts just as much as a
class-level ``def``.
"""
impl = getattr(store, method, None)
if impl is None:
# A non-callable attribute is not an implementation: accepting it would
# defer the failure to the call site mid-session, which is exactly what
# this pre-flight check exists to prevent.
if not callable(impl):
return False
default = getattr(SessionStore, method, None)
return getattr(type(store), method, None) is not default
# Compare the underlying function so a bound method is matched against the
# Protocol default; anything that is not a bound method (a plain callable
# assigned on the instance) is compared directly and is never the default.
return getattr(impl, "__func__", impl) is not default


def validate_session_store_options(options: ClaudeAgentOptions) -> None:
Expand Down
7 changes: 7 additions & 0 deletions tests/test_message_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -976,6 +976,13 @@ def test_parse_invalid_data_type(self):
assert "Invalid message data type" in str(exc_info.value)
assert "expected dict, got str" in str(exc_info.value)

def test_parse_non_dict_message_field(self):
"""A non-dict 'message' field raises MessageParseError, not a bare TypeError."""
for message_type in ("user", "assistant"):
with pytest.raises(MessageParseError) as exc_info:
parse_message({"type": message_type, "message": "not a dict"})
assert f"Malformed {message_type} message" in str(exc_info.value)

def test_parse_missing_type_field(self):
"""Test that missing 'type' field raises MessageParseError."""
with pytest.raises(MessageParseError) as exc_info:
Expand Down
50 changes: 50 additions & 0 deletions tests/test_session_store_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,56 @@ def test_continue_conversation_ok_when_store_implements_list_sessions(
)
)

def test_continue_conversation_ok_when_list_sessions_set_on_instance(
self,
) -> None:
"""SessionStore is a structural Protocol, so an implementation assigned
on the instance (delegation, functools.partial, a test double) satisfies
it just as a class-level def does.
"""

class DelegatingStore(SessionStore):
def __init__(self, inner: SessionStore) -> None:
self.list_sessions = inner.list_sessions

async def append(self, key, entries):
pass

async def load(self, key):
return None

validate_session_store_options(
ClaudeAgentOptions(
session_store=DelegatingStore(InMemorySessionStore()),
continue_conversation=True,
)
)

def test_non_callable_instance_attribute_is_not_an_implementation(
self,
) -> None:
"""Resolving against the instance must still require a callable — a
non-callable attribute would otherwise pass validation here and fail
mid-session at the call site.
"""

class DisabledStore(SessionStore):
def __init__(self) -> None:
self.list_sessions = "disabled"

async def append(self, key, entries):
pass

async def load(self, key):
return None

with pytest.raises(ValueError, match="list_sessions"):
validate_session_store_options(
ClaudeAgentOptions(
session_store=DisabledStore(), continue_conversation=True
)
)

def test_continue_with_resume_and_store_lacking_list_sessions(self) -> None:
"""Parity with TS: when resume is explicitly set, continue=True
should not require list_sessions() — list_sessions is provably
Expand Down