cli_session_switch.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Session-switch plumbing shared by /resume, /sessions and /branch.
  2. The switch itself lives in ``cli_commands_mixin``; the handoff it needs sits here: end the row
  3. being left, then repoint an already-built agent.
  4. """
  5. from __future__ import annotations
  6. from contextlib import suppress
  7. def _end_current_session(cli, reason: str) -> None:
  8. """Flush un-persisted messages, then end the current session row with ``reason``.
  9. Best-effort on both steps (the switch proceeds even if the DB write fails)."""
  10. if cli.agent:
  11. with suppress(Exception):
  12. cli.agent._flush_messages_to_session_db(
  13. cli.conversation_history, conversation_history=cli.conversation_history)
  14. with suppress(Exception):
  15. cli._session_db.end_session(cli.session_id, reason)
  16. def _sync_agent_to_session(cli, session_id: str, *, parent_session_id: str, reason: str) -> None:
  17. """Point an already-built agent at ``session_id`` after a /resume or /branch switch: reset
  18. per-session state, re-anchor the DB flush index, and notify memory providers with
  19. reset=False (their state stays valid and just targets the new id; parent keeps lineage)."""
  20. if not cli.agent:
  21. return
  22. cli.agent.session_id = session_id
  23. cli.agent.reset_session_state()
  24. if hasattr(cli.agent, "_last_flushed_db_idx"):
  25. cli.agent._last_flushed_db_idx = len(cli.conversation_history)
  26. if hasattr(cli.agent, "_todo_store"):
  27. with suppress(Exception):
  28. from tools.todo_tool import TodoStore
  29. cli.agent._todo_store = TodoStore()
  30. if hasattr(cli.agent, "_invalidate_system_prompt"):
  31. cli.agent._invalidate_system_prompt()
  32. with suppress(Exception):
  33. _mm = getattr(cli.agent, "_memory_manager", None)
  34. # reset=False: provider state follows the new id; parent_session_id keeps lineage (#6672).
  35. if _mm is not None:
  36. _mm.on_session_switch(
  37. session_id, parent_session_id=parent_session_id or "", reset=False, reason=reason)