"""Session state and conversation history manager.""" from datetime import UTC, datetime from app.models.config import AppConfig from app.models.message import Message from app.utils.token_counter import TokenCounter class SessionContext: """In-memory conversation state manager. Tracks conversation history, token usage estimates, and session metadata. """ def __init__(self, config: AppConfig) -> None: """Initialize session context. Args: config: Application configuration. """ self._config = config self._history: list[Message] = [] self._token_counter = TokenCounter(config.agent.max_conversation_tokens) self._start_time = datetime.now(UTC) self._message_count: int = 0 def add_message(self, role: str, content: str | None = None, **kwargs: object) -> Message: """Create and append a message to conversation history. Args: role: Message role (system, user, assistant, tool). content: Text content of the message. **kwargs: Additional Message fields (tool_calls, tool_call_id, name). Returns: The created Message instance. """ message = Message(role=role, content=content, **kwargs) # type: ignore[arg-type] self._history.append(message) self._message_count += 1 return message def get_history(self) -> list[Message]: """Return a shallow copy of the conversation history.""" return list(self._history) def clear_history(self) -> None: """Clear conversation history and reset counters.""" self._history.clear() self._message_count = 0 self._token_counter = TokenCounter(self._config.agent.max_conversation_tokens) @property def estimated_tokens(self) -> int: """Estimated token count for the current conversation history.""" return self._token_counter.estimate_messages_tokens(self._history) @property def token_counter(self) -> TokenCounter: """The token counter instance.""" return self._token_counter @property def message_count(self) -> int: """Number of messages added to this session.""" return self._message_count @property def start_time(self) -> datetime: """Session start timestamp (UTC).""" return self._start_time