claude-agent-sdk-python icon indicating copy to clipboard operation
claude-agent-sdk-python copied to clipboard

feat: add timestamp field to Message models

Open enioxt opened this issue 4 months ago • 0 comments

Description

Fixes #258

This PR adds the missing timestamp field to all Message models (UserMessage, AssistantMessage, SystemMessage, and ResultMessage).

Problem

The timestamp field is present in the JSONL file output from the CLI, but was not being captured in the Message type definitions. This made it impossible to access message timestamps for use cases like displaying timelines or analyzing conversation flow.

Solution

  • Added timestamp: str | None = None field to all message dataclasses
  • Updated message_parser.py to extract timestamp from JSONL data using data.get("timestamp")
  • Timestamp is optional for backward compatibility (defaults to None)

Changes

Files Modified:

  • src/claude_agent_sdk/types.py: Added timestamp field to 4 message dataclasses
  • src/claude_agent_sdk/_internal/message_parser.py: Updated parsing for all message types

New Test File:

  • tests/test_message_timestamp.py: Comprehensive test suite with 10 test cases

✅ Testing

Tests performed:

  • [x] UserMessage with timestamp
  • [x] UserMessage without timestamp (backward compatibility)
  • [x] AssistantMessage with timestamp
  • [x] AssistantMessage without timestamp
  • [x] SystemMessage with timestamp
  • [x] SystemMessage without timestamp
  • [x] ResultMessage with timestamp
  • [x] ResultMessage without timestamp
  • [x] Various timestamp format variations
  • [x] UserMessage with content blocks and timestamp

Test Results:

============================= test session starts =============================
collected 10 items

tests/test_message_timestamp.py::TestMessageTimestampField::... PASSED [100%]

============================== 10 passed in 1.86s ==============================

All tests passed: 10/10 new tests ✅
Regression tests: 124/124 total tests passed ✅

Code Quality

  • Formatted and linted with ruff
  • All existing tests pass without modification
  • Backward compatible (timestamp is optional)

Example Usage

from claude_agent_sdk import ClaudeAgent

agent = ClaudeAgent()
messages = agent.get_messages()

for msg in messages:
    if msg.timestamp:
        print(f"{msg.timestamp}: {msg.content}")

Sacred Code: 000.111.369.963.1618

enioxt avatar Oct 16 '25 13:10 enioxt