session_onboarding.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. """First-run onboarding on the session authority: ``onboarding.start`` and ``onboarding.skip``.
  2. The onboarding chat is an ordinary local Desktop session the authority owns from its first row: the
  3. start creates it here, writes the run record (``agent.onboarding_record``) before any agent is built,
  4. attaches the asking connection and admits the hidden opening turn through the same durable FIFO as a
  5. typed message. The record is what makes it an onboarding chat for every later turn: the ``onboarding``
  6. toolset fold-in (``run_turn``), the scripted greeting and name card and the per-turn note
  7. (``run_turn_runner``), all from ``agent.onboarding_session``. ``onboarding.state`` and
  8. ``onboarding.set_run`` read and write only config and stay on the sidecar handler.
  9. """
  10. from __future__ import annotations
  11. import asyncio
  12. import logging
  13. import threading
  14. import uuid
  15. from functools import partial
  16. from gateway.session_contract import SessionRef
  17. from hermes_state_runtime import RuntimeStoreError
  18. logger = logging.getLogger(__name__)
  19. ONBOARDING_PROFILE = 'default'
  20. class OnboardingRefusal(RuntimeStoreError):
  21. """A refusal on the sidecar handler's wire: its JSON-RPC code and human message."""
  22. def __init__(self, code, message):
  23. super().__init__('onboarding_refused', detail=message)
  24. self.wire_code, self.wire_message = code, message
  25. class _NoModelForTheRun(Exception):
  26. """The claim was blocked and nothing else can carry the run's first chat."""
  27. def handlers(connection):
  28. return {'onboarding.start': partial(start, connection), 'onboarding.skip': partial(skip, connection)}
  29. def _onboarding_connection(connection):
  30. return connection._sibling_for(ONBOARDING_PROFILE) or connection
  31. async def start(connection, ref, params):
  32. from tui_gateway.contracts.profiles_vault_complete_foreign_subagents import OnboardingStartParams
  33. from pydantic import ValidationError
  34. try:
  35. request = OnboardingStartParams.model_validate(params)
  36. except ValidationError as exc:
  37. raise RuntimeStoreError('invalid_params', detail=str(exc)) from exc
  38. target = _onboarding_connection(connection)
  39. if target is not connection:
  40. # Dispatch entered the asking profile's scope; the claim, the facts and the chat's policy are default's.
  41. from gateway.session_authorities import owner_scope
  42. with owner_scope(target.authority):
  43. return await start(target, ref, params)
  44. if 'session:create' not in connection.actor.capabilities:
  45. raise RuntimeStoreError('permission_denied')
  46. authority = connection.authority
  47. lock = getattr(authority, '_onboarding_start_lock', None)
  48. if lock is None:
  49. lock = authority._onboarding_start_lock = asyncio.Lock()
  50. # Held through the opening's admission: two windows pressing start at once get one chat and one opening.
  51. async with lock:
  52. plan = await asyncio.to_thread(_choose_run, authority, request)
  53. stored = plan['stored'] or await _create_chat(connection)
  54. from gateway.session_mutations import retire_live_sessions
  55. from gateway.session_runtime_workers import tracked_write
  56. discards = _discards(authority)
  57. if request.fresh_launch:
  58. discards.ids.update(sid for sid in plan['replaced']
  59. if (live := authority.sessions.get(sid)) is None or not live.subscribers)
  60. def retire(deleted):
  61. retire_live_sessions(authority, deleted)
  62. return deleted
  63. try:
  64. deleted = await tracked_write(authority, partial(_settle_runs, authority, request, plan, stored, discards),
  65. retire)
  66. finally:
  67. discards.ids.difference_update(plan['replaced'])
  68. if plan['claimed'] is not None:
  69. from hermes_cli import free_tier_bootstrap
  70. await asyncio.to_thread(free_tier_bootstrap.refresh_record)
  71. _withdraw_setup_cards(authority, [sid for sid in plan['replaced'] if sid not in deleted])
  72. chat = SessionRef(authority.profile_id, stored)
  73. await connection.resume(chat, {})
  74. opening = plan['opening'] if plan['stored'] else await asyncio.to_thread(_opening_for, authority, stored)
  75. if opening is not None:
  76. run_id = await asyncio.to_thread(_run_id, authority, stored)
  77. await connection.submit(chat, {'session_id': stored, 'text': opening, 'display_kind': 'hidden',
  78. 'submission_id': f'onboarding-opening:{run_id or stored}'})
  79. return {'session_id': stored, 'stored_session_id': stored, 'resumed': plan['stored'] is not None,
  80. 'run_id': await asyncio.to_thread(_run_id, authority, stored)}
  81. def _choose_run(authority, request):
  82. """A refused claim (5079) or a blocked one with nothing else to run on (5080) leaves no chat, so
  83. the install stays due."""
  84. from agent.onboarding_facts import read_facts
  85. from agent.onboarding_flow import Facts
  86. from agent.onboarding_record import load, open_session_ids
  87. from agent.onboarding_text import opening_prompt
  88. from hermes_cli.auth_constants import AuthError
  89. db = authority.db
  90. open_ids = open_session_ids(db)
  91. stored = None if request.rerun or request.fresh_launch else next(iter(open_ids), None)
  92. plan = {'stored': stored, 'open_ids': open_ids, 'claimed': None, 'facts': None, 'opening': None,
  93. 'replaced': [sid for sid in open_ids if sid != stored]}
  94. if stored is not None:
  95. facts = Facts.from_stored(load(db, stored)['facts'])
  96. if not (db.get_session(stored) or {}).get('message_count'):
  97. plan['opening'] = opening_prompt(facts)
  98. plan['facts'] = facts
  99. return plan
  100. plan['facts'] = read_facts(facts_source=request.facts_source.value, locale=request.locale)
  101. if not request.rerun:
  102. try:
  103. plan['claimed'] = _claim_before_run(assume_fresh=request.assume_fresh)
  104. except AuthError as exc:
  105. logger.info('onboarding.start: welcome trial not claimed: %s', exc)
  106. raise OnboardingRefusal(5079, str(exc)) from exc
  107. except _NoModelForTheRun as exc:
  108. logger.info('onboarding.start: no chat opened: %s', exc)
  109. raise OnboardingRefusal(5080, str(exc)) from exc
  110. return plan
  111. def _claim_before_run(*, assume_fresh):
  112. """``onboarding.run: true`` on disk before the welcome-trial claim, so a crash after the claim still
  113. opens onboarding next launch."""
  114. from hermes_cli import anon_auth
  115. from hermes_cli.onboarding_run import set_run
  116. from hermes_cli.welcome_trial import claim_desktop_free_tier, provider_configured
  117. if not anon_auth.on_local_desktop_backend():
  118. # A CLI or TUI holds a native ticket too: its start schedules nothing. A rerun (Settings, any
  119. # Desktop) never claims and never reaches here.
  120. raise _NoModelForTheRun('First-run onboarding starts only in the Desktop app on this machine.')
  121. set_run(True)
  122. claimed = claim_desktop_free_tier(assume_fresh=assume_fresh)
  123. if claimed is None and not (anon_auth.free_inference_active() or provider_configured()):
  124. raise _NoModelForTheRun('The welcome trial is not available here, and no provider is set up.')
  125. return claimed
  126. async def _create_chat(connection):
  127. from gateway.session_local import stage_local_session
  128. from gateway.session_local_recovery import restore_local_session
  129. from gateway.session_runtime_workers import tracked_write
  130. from hermes_state_local import commit_local_session
  131. authority = connection.authority
  132. staged = stage_local_session(authority, connection.actor, {'source': 'gui', 'request_id': uuid.uuid4().hex},
  133. client_local=connection.native_owner,
  134. desktop_local=getattr(connection.transport, 'desktop_local', False))
  135. if not (staged['policy'] or {}).get('model'):
  136. raise OnboardingRefusal(5080, 'No model is set up to run onboarding on.')
  137. await tracked_write(authority, partial(commit_local_session, authority.db, epoch=authority.epoch, receipt=staged))
  138. return restore_local_session(authority, staged['session_id']).session_id
  139. class _Discards:
  140. """The chats a fresh launch's start deletes because no window watched them when it looked. A window
  141. that resumes one before its delete takes it back (``keep_from_discard``); the lock makes the take-back
  142. and the delete one or the other, never a viewer on a deleted chat."""
  143. def __init__(self):
  144. self.lock = threading.Lock()
  145. self.ids = set()
  146. def _discards(authority):
  147. discards = getattr(authority, '_onboarding_discards', None)
  148. if discards is None:
  149. discards = authority._onboarding_discards = _Discards()
  150. return discards
  151. async def keep_from_discard(authority, session_id):
  152. """``attach``, after its last other await: a chat a fresh launch was about to delete is kept. The
  153. take-back itself never yields, so the viewer joins in the same loop step and a later start sees it
  154. watched; a start claims only on the loop. A delete in flight holds the lock across its write, so
  155. that wait runs off the loop and the take-back is retried after it."""
  156. discards = getattr(authority, '_onboarding_discards', None)
  157. while discards is not None and session_id in discards.ids:
  158. if discards.lock.acquire(blocking=False):
  159. discards.ids.discard(session_id)
  160. discards.lock.release()
  161. return
  162. def delete_finished():
  163. with discards.lock:
  164. pass
  165. await asyncio.to_thread(delete_finished)
  166. def _settle_runs(authority, request, plan, stored, discards):
  167. """The new chat's record and title, and the end of every other open run; returns the chats it
  168. deleted. One open run at a time: the kept run is open before the others end, so the install flag
  169. never closes in between."""
  170. from agent.onboarding_flow import End
  171. from agent.onboarding_record import advance, start
  172. from agent.onboarding_text import CHAT_TITLE
  173. db = authority.db
  174. if plan['stored'] is None:
  175. # The record exists before any agent is built, so the first turn already folds the toolset in.
  176. start(db, stored, plan['facts'])
  177. deleted = []
  178. if request.fresh_launch:
  179. deleted = _discard_unfinished_runs(db, plan['replaced'], discards)
  180. for old in plan['replaced']:
  181. if old not in deleted:
  182. advance(db, old, End('replaced'))
  183. if plan['stored'] is None:
  184. # After the discard, so a run started over keeps the title its deleted chat had.
  185. db.set_session_title(stored, db.get_next_title_in_lineage(CHAT_TITLE))
  186. return deleted
  187. def _discard_unfinished_runs(db, stored_ids, discards):
  188. """A new launch's start: the runs the app was closed on never count as done. A chat no window
  189. watches (still in *discards*) is deleted the way ``session.delete`` deletes it, which ends its run
  190. (``deleted``) and tells every window; the caller retires the deleted ids from the authority. A chat a
  191. window reopened, or one a turn still writes (the delete refuses it), is kept, and its run ends as
  192. ``replaced`` so it is never resumed."""
  193. from pathlib import Path
  194. from agent.onboarding_record import delete_chat
  195. sessions_dir = Path(db.db_path).parent / 'sessions'
  196. deleted = []
  197. for old in stored_ids:
  198. with discards.lock:
  199. if old not in discards.ids:
  200. continue
  201. try:
  202. if delete_chat(db, old, lambda old=old: db.delete_session(
  203. old, sessions_dir=sessions_dir, exclude_active_write_guards=True)):
  204. deleted.append(old)
  205. except Exception:
  206. logger.exception('onboarding.start could not delete unfinished chat %s', old)
  207. return deleted
  208. def ending_run_on_delete(db, session_id, commit):
  209. """*commit* (the canonical delete's receipt transaction) wrapped so deleting the chat that holds
  210. the live run ends that run (``deleted``) and tells every window, as the sidecar's
  211. ``session.delete`` did. Returns the receipt."""
  212. from agent.onboarding_record import delete_chat
  213. receipt = []
  214. def delete():
  215. receipt.append(commit())
  216. return session_id in receipt[0]['deleted_ids']
  217. delete_chat(db, session_id, delete)
  218. return receipt[0]
  219. def _withdraw_setup_cards(authority, stored_ids):
  220. """Close the card still waiting in a chat whose run just ended; its answer would be refused."""
  221. from gateway.session_server_requests import withdraw
  222. for sid in stored_ids:
  223. live = authority.sessions.get(sid)
  224. if live is not None:
  225. withdraw(live.event_stream, sid, 'setup_beat')
  226. def _opening_for(authority, stored):
  227. from agent.onboarding_flow import Facts
  228. from agent.onboarding_record import load
  229. from agent.onboarding_text import opening_prompt
  230. if (authority.db.get_session(stored) or {}).get('message_count'):
  231. return None
  232. return opening_prompt(Facts.from_stored(load(authority.db, stored)['facts']))
  233. def _run_id(authority, stored):
  234. from agent.onboarding_record import load
  235. return (load(authority.db, stored) or {}).get('run_id') or ''
  236. async def skip(connection, ref, params):
  237. """Skip setup: end the chat's run and close the card that waits. The card's asker reads the
  238. skipped record when it wakes (``setup_beat``)."""
  239. from agent.onboarding_flow import End
  240. from agent.onboarding_record import advance, load
  241. from gateway.session_runtime_workers import tracked_write
  242. from gateway.session_server_requests import withdraw
  243. from pydantic import ValidationError
  244. from tui_gateway.contracts.profiles_vault_complete_foreign_subagents import OnboardingSkipParams
  245. try:
  246. request = OnboardingSkipParams.model_validate(params)
  247. except ValidationError as exc:
  248. raise RuntimeStoreError('invalid_params', detail=str(exc)) from exc
  249. if not request.session_id:
  250. raise RuntimeStoreError('invalid_params')
  251. authority = connection.authority
  252. authority.authorize(connection.actor, ref, 'session:control')
  253. db = authority.db
  254. if load(db, db.get_compression_tip(ref.session_id) or ref.session_id) is None:
  255. return {'skipped': False}
  256. step = await tracked_write(authority, partial(advance, db, ref.session_id, End('skipped')))
  257. live = authority.sessions.get(ref.session_id)
  258. if live is not None:
  259. withdraw(live.event_stream, ref.session_id, 'setup_beat')
  260. return {'skipped': bool(step.result.get('skipped_all'))}
  261. def arm_onboarding_turn(agent, owner, history):
  262. """The onboarding chat's per-turn inputs on an authority-owned local turn: the turn note (which
  263. card is closed and how to bring it back) appended to the API-only notes, and the scripted opening
  264. returned for ``run_conversation(prelude=...)``. Nothing for a chat without ``setup_beat``."""
  265. from agent.onboarding_session import append_turn_note, builds_onboarding, onboarding_prelude, onboarding_turn_note
  266. if owner is None or not builds_onboarding(agent):
  267. return None
  268. from gateway.session_server_requests import waiting
  269. authority, session_id, _generation = owner
  270. live = authority.sessions.get(session_id)
  271. card_waiting = live is not None and waiting(live.event_stream, session_id, 'setup_beat')
  272. append_turn_note(agent, onboarding_turn_note(agent, history_empty=not history, card_waiting=card_waiting))
  273. return onboarding_prelude(agent, history)