session_refine.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """``/refine`` for a local session whose cached agent is gone (T7).
  2. ``/moa`` arms a one-shot model swap that evicts the session's cached agent, and its settle evicts
  3. the MoA-built one, so the cached agent is not where a local session's conversation lives. The
  4. session's stored transcript is: the review runs over it on a side agent built from the session's
  5. frozen launch policy (the route ``/bg`` and ``/btw`` use, ``gateway/session_tui_side.py``), and its
  6. summary lands on the session's event stream as ``review.summary``, as a turn-time review does.
  7. Messaging sessions keep the cached-agent path unchanged.
  8. """
  9. import asyncio
  10. import contextlib
  11. import uuid
  12. from agent.i18n import t
  13. def _local_session(runner, source):
  14. from gateway.config import Platform
  15. from gateway.session_setting_commands import local_authority_live
  16. if source is None or getattr(source, 'platform', None) != Platform.LOCAL:
  17. return None, None
  18. return local_authority_live(runner, source)
  19. async def refine_local_session(runner, source, focus):
  20. """The ``/refine`` reply for a local session, or None when ``source`` is not one."""
  21. authority, live = _local_session(runner, source)
  22. if live is None:
  23. return None
  24. from gateway.session_contract import SessionRef
  25. from gateway.session_local_recovery import transcript_target
  26. from gateway.session_policy import policy_for_source
  27. policy = policy_for_source(runner, live.source)
  28. if policy is None:
  29. return None
  30. ref = SessionRef(authority.profile_id, source.chat_id)
  31. def load():
  32. target = transcript_target(authority, ref)
  33. return target, authority.db.get_messages_as_conversation(target, include_ancestors=True)
  34. target, history = await asyncio.to_thread(load)
  35. if not history:
  36. return t('gateway.refine.nothing_yet')
  37. from agent.background_review import finish_background_review_run, prepare_background_review_run
  38. from gateway.session_tui_side import _side_agent, _side_scope, _spawn
  39. # The guard is the session's (its side agent is per call): a /refine while one runs joins it, as
  40. # the resident agent's does, and the session's next turn cancels it (``_execute_claimed``).
  41. run = prepare_background_review_run(live.review)
  42. tail = t('gateway.refine.focus_suffix', focus=focus) if focus else ''
  43. if run is None:
  44. return t('gateway.refine.started', focus_suffix=tail)
  45. task_id = f'refine_{uuid.uuid4().hex[:6]}'
  46. holder = [None]
  47. loop = asyncio.get_running_loop()
  48. def publish(message):
  49. current = authority.sessions.get(ref.session_id)
  50. if current is not None:
  51. current.event_stream.publish(ref.session_id, {'text': str(message)}, event_type='review.summary')
  52. def body():
  53. try:
  54. review_body()
  55. finally: # whatever raised first, the session's guard is released
  56. finish_background_review_run(live.review, run)
  57. from gateway.session_retirement import retire_after_review
  58. with contextlib.suppress(RuntimeError): # the loop already closed
  59. loop.call_soon_threadsafe(retire_after_review, authority, ref, live)
  60. return '' # the summary (if any) was published above; an empty review.summary draws nothing
  61. def review_body():
  62. from agent.background_review import spawn_background_review_thread
  63. from agent.turn_finalizer import _clone_background_review_messages
  64. with _side_scope(authority, policy, task_id):
  65. # The session's own id: the review's usage is recorded against it, and the agent never
  66. # runs a turn of its own, so it writes no row. close() would tear down that id's terminal,
  67. # browser and memory provider (the session's), so only the agent's own clients are released.
  68. # No memory provider of its own either (release_clients would not stop it): the review
  69. # reads the transcript, as the background review fork does (skip_memory=True).
  70. agent = holder[0] = _side_agent(authority, policy, live, task_id, session_id=target,
  71. skip_memory=True)
  72. agent._end_session_on_close = False
  73. agent.background_review_callback = publish
  74. agent._print_fn = lambda *_a, **_k: None
  75. try:
  76. review, _prompt = spawn_background_review_thread(
  77. agent, _clone_background_review_messages(history), review_memory=True,
  78. review_skills='skill_manage' in getattr(agent, 'valid_tool_names', set()),
  79. focus=focus or None, review_run=run, explicit=True)
  80. review()
  81. finally:
  82. with contextlib.suppress(Exception):
  83. agent.release_clients()
  84. try:
  85. _spawn(authority, ref, task_id, 'review.summary', body, holder=holder)
  86. except RuntimeError as exc: # the review thread could not start
  87. finish_background_review_run(live.review, run)
  88. return t('gateway.refine.start_failed', error=exc)
  89. return t('gateway.refine.started', focus_suffix=tail)