session_controls.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. """Authenticated WS projection of the gateway authority; no TUI execution fallback."""
  2. import asyncio
  3. import logging
  4. import re
  5. from dataclasses import asdict
  6. from functools import partial
  7. from pathlib import Path
  8. import sqlite3
  9. import uuid
  10. from gateway.config import Platform
  11. from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL, SessionActor, SessionRef, Submission
  12. from gateway.session_llm_oneshot import DeferredReply
  13. from hermes_constants import profile_name_for_home
  14. from hermes_state_runtime import RuntimeStoreError
  15. logger = logging.getLogger(__name__)
  16. # A refusal names the check that fired: the client prints ``field``/``detail`` beside the reason
  17. # code, and this log line is what a report can quote when the client's copy is not enough.
  18. def _refusal_data(exc: RuntimeStoreError) -> dict:
  19. """The ``error.data`` for one ``RuntimeStoreError``: always the reason, plus the field and the
  20. detail when the raiser named them."""
  21. data = {'reason': exc.reason}
  22. for key in ('field', 'detail'):
  23. value = getattr(exc, key, None)
  24. if value:
  25. data[key] = value
  26. for key in ('revision', 'execution_generation'):
  27. if isinstance(getattr(exc, key, None), int):
  28. data[key] = getattr(exc, key)
  29. if getattr(exc, 'admitted', None) is False:
  30. # Nothing of this request was admitted: bot_relay.deliver's sender may finalize with
  31. # ``bot_relay.settle``; groups.send's words may come back for editing.
  32. data['admitted'] = False
  33. return data
  34. def _profile_label(profile_id) -> str:
  35. """The profile as a log line should carry it: a named profile by name, a root profile (keyed by its
  36. home path) by its name, never the path itself."""
  37. if not profile_id:
  38. return 'default'
  39. text = str(profile_id)
  40. if '/' not in text and '\\' not in text:
  41. return text
  42. return profile_name_for_home(text) or 'default'
  43. def _log_refusal(profile, method, exc: RuntimeStoreError) -> None:
  44. """One line per refusal, at the level its audience deserves.
  45. A refusal that names the check that fired is a launch diagnostic (warning). A bare reason code is
  46. the client's own state: ``permission_denied`` on a submit, ``not_found``, ``session_busy`` are
  47. routine, and a retrying client must not be able to flood the gateway log, so those stay at debug
  48. where they were silent before. ``admission_conflict field=request_id`` is a client's explicit retry of
  49. a send already admitted (the dedupe working), so it is info: expected, never in errors.log. Any other
  50. reason tagged ``field=request_id`` (session.create's ``invalid_params``) is a real refusal: warning. The shape follows the
  51. gateway's own refusal log lines (``gateway/run_notifications.py``): what was refused, for which
  52. profile, and why."""
  53. line = '%s refused for profile=%s: %s%s%s'
  54. args = (method, _profile_label(profile), exc.reason,
  55. f' field={exc.field}' if getattr(exc, 'field', None) else '',
  56. f' detail={exc.detail}' if getattr(exc, 'detail', None) else '')
  57. field = getattr(exc, 'field', None)
  58. if exc.reason == 'session_busy' or not (field or getattr(exc, 'detail', None)):
  59. logger.debug(line, *args)
  60. elif field == 'request_id' and exc.reason == 'admission_conflict':
  61. logger.info(line, *args)
  62. else:
  63. logger.warning(line, *args)
  64. # (method, error class) pairs whose traceback this process already logged.
  65. _STORAGE_TRACEBACKS = set()
  66. def _log_storage_failure(profile, method, session_id, exc: sqlite3.Error) -> None:
  67. """Keep SQLite's diagnostic at the gateway while its wire error stays retryable.
  68. Clients retry on ``storage_unavailable``, so, like ``_log_refusal``, a retrying client must not
  69. flood the log: every failure keeps one line with its cause, the traceback comes once per method
  70. and error class, and the client-supplied ``session_id`` is capped."""
  71. key = (method, type(exc).__name__)
  72. first = key not in _STORAGE_TRACEBACKS
  73. _STORAGE_TRACEBACKS.add(key)
  74. shown = repr(session_id)
  75. if len(shown) > 64:
  76. shown = f'{shown[:48]}… ({len(shown)} chars)'
  77. logger.warning('%s storage failure for profile=%s session_id=%s: %s',
  78. method, _profile_label(profile), shown, exc, exc_info=first)
  79. # ``session.detach end_reason``: a short snake_case label, stored verbatim as ``sessions.end_reason``.
  80. _END_REASON = re.compile(r'[a-z][a-z_]{0,31}')
  81. # Verbs whose param sets are closed and never carried a ``profile`` key.
  82. _PROFILE_IMPLICIT = frozenset({'session.create', 'session.list', 'session.info', 'session.resume', 'session.detach',
  83. 'prompt.submit', 'prompt.receipt', 'prompt.cancel', 'prompt.resolve_unknown',
  84. 'prompt.steer_queued', 'prompt.replace_queued',
  85. 'session.interrupt', 'session.events.since', 'session.mutate', 'session.stats',
  86. 'approval.respond', 'clarify.respond'})
  87. def display_projection(history, profile_home):
  88. """Main's TUI display rows for a snapshot's stored rows: the sidecar's own
  89. ``_history_to_messages`` (compaction handoffs stripped, ``/steer`` unwrapped, tool rows
  90. labelled from the paired assistant ``tool_calls``), never a re-implementation."""
  91. from tui_gateway import server
  92. rows = [{**row, '_row_id': row['row_id']} if 'row_id' in row else row for row in history]
  93. return server._history_to_messages(rows, profile_home=profile_home)
  94. def model_only(row):
  95. """A live row the model reads but nobody typed as one message (a micro-compaction merge): never rendered."""
  96. from agent.context_compressor import MODEL_ONLY_DISPLAY_METADATA_KEY
  97. metadata = row.get('display_metadata')
  98. return isinstance(metadata, dict) and bool(metadata.get(MODEL_ONLY_DISPLAY_METADATA_KEY))
  99. async def _resume_transcript(authority, ref, snapshot, history, omit):
  100. """A resume reply's transcript fields. *omit* (``omit_messages``): no rows and ``messages_omitted``, the
  101. stored count and the todo plan of the physical target the attach resolved, as the stdio resume answers
  102. it; the display-row lineage read is skipped (the todo lookup still walks the lineage's todo rows)."""
  103. # Its home module, not tui_gateway.server: importing the stdio sidecar points sys.stdout at stderr.
  104. from tui_gateway.tool_progress import _todo_state_from_history
  105. if not omit:
  106. # The newest todo result in the transcript, the snapshot the session's agent hydrates
  107. # from and its ``todo.updated`` frames carried: a viewer attaching shows the plan now.
  108. return {'messages': history, 'message_count': len(history), 'todo_state': _todo_state_from_history(history)}
  109. from gateway.session_local_recovery import omitted_history_state
  110. # A delete committed since the attach is ``not_found``, as one during the attach is.
  111. todo_state, count = await asyncio.to_thread(authority.unless_deleted, ref, partial(
  112. omitted_history_state, authority.db, snapshot.transcript_target))
  113. return {'messages': [], 'messages_omitted': True, 'message_count': count, 'todo_state': todo_state}
  114. class AuthorityConnection:
  115. def __init__(self, authority, transport, identity, *, operator=False):
  116. self.authority = authority
  117. self.transport = transport
  118. capabilities = frozenset({'session:read', 'session:submit', 'session:control',
  119. 'session:approve', 'session:respond'})
  120. if identity:
  121. capabilities |= {'session:create'}
  122. if 'capabilities' in identity:
  123. capabilities = frozenset(identity['capabilities'])
  124. # Only verified transport gates may issue this capability, never identity data.
  125. capabilities -= {'session:operator'}
  126. if operator is True:
  127. capabilities |= {'session:operator'}
  128. if (not identity.get('user_id')
  129. or identity.get('instance_id', authority.instance_id) != authority.instance_id):
  130. capabilities = frozenset()
  131. from gateway.owner_identity import principal_subject
  132. self.actor = SessionActor(principal_subject(identity),
  133. identity.get('profile_id', authority.profile_id),
  134. capabilities, uuid.uuid4().hex)
  135. from gateway.session_local_migration import bind_native_transport
  136. bind_native_transport(authority, self.actor, identity)
  137. self.native_owner = identity.get('native_bootstrap') is True
  138. self.subscriptions = {}
  139. # session_id -> (epoch, sequence) the last reconnect replay answered; spent by the next resume.
  140. self.replay_cursors = {}
  141. self.handed_back = set() # sessions this live client detached without closing (the TUI's switcher)
  142. self._identity, self._operator, self._siblings = identity, operator, {}
  143. authority.events[self.actor.transport_id] = transport
  144. @property
  145. def host_scoped(self):
  146. """A host-scoped grant (the Desktop's shared-primary socket, the dashboard gate) acts for
  147. every profile this process serves; any other grant is bound to its own profile."""
  148. return self._identity.get('profile_scope') == 'host'
  149. def _sibling_for(self, profile):
  150. """Connection bound to the sibling authority a ``profile`` param names, or None for our own
  151. home. Only a host-scoped grant (the Desktop's shared-primary socket, the dashboard gate)
  152. reaches a sibling; a profile-bound ticket naming any other profile is a mismatch, exactly
  153. like a profile nobody here serves. Never a fallback, never a rewritten profile_id."""
  154. from hermes_cli.profiles import profile_matches_home
  155. if profile_matches_home(profile, Path(self.authority.profile_id)):
  156. return None
  157. if not self.host_scoped:
  158. raise RuntimeStoreError('profile_mismatch')
  159. registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
  160. for sibling in (registry or ()):
  161. if sibling is not self.authority and profile_matches_home(profile, Path(sibling.profile_id)):
  162. connection = self._siblings.get(sibling.profile_id)
  163. # A re-served profile is a new authority under the same id: never keep routing to
  164. # the retired one (it refuses every admission for the rest of this socket's life).
  165. if connection is None or connection.authority is not sibling:
  166. identity = dict(self._identity, profile_id=sibling.profile_id, instance_id=sibling.instance_id)
  167. connection = AuthorityConnection(sibling, self.transport, identity, operator=self._operator)
  168. self._siblings[sibling.profile_id] = connection
  169. return connection
  170. if registry is not None and registry.starting(profile) is not None:
  171. # Hot-serve is still building it: retryable, not the final verdict for an unserved profile.
  172. # A shared socket holds such a frame until the start ends (``awaits_profile_start``); this
  173. # answers one whose wait ran out.
  174. raise RuntimeStoreError('runtime_draining', field='profile', detail='the profile is still starting')
  175. raise RuntimeStoreError('profile_mismatch')
  176. def awaits_profile_start(self, request, held=()):
  177. """Whether a shared socket holds *request* off its serial lane: ``(key, started)`` when a
  178. host-scoped frame names a profile hot-serve is still building (``started`` is set once the
  179. build ends), ``(key, None)`` when it names one of *held*, the starts whose earlier frames the
  180. socket still holds, so it queues behind them. None for every other frame."""
  181. params = request.get('params') if isinstance(request, dict) else None
  182. profile = params.get('profile') if isinstance(params, dict) else None
  183. registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
  184. if not (self.host_scoped and isinstance(profile, str) and profile and registry is not None):
  185. return None
  186. from hermes_cli.profiles import profile_matches_home
  187. key = next((key for key in held if profile_matches_home(profile, Path(key))), None)
  188. return (key, None) if key is not None else registry.starting(profile)
  189. def handlers(self):
  190. """Method → handler for every verb ``dispatch`` serves outside the group controls; each
  191. name is declared in ``tui_gateway/contracts`` (``METHODS`` or ``CANONICAL_METHODS``)."""
  192. handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,
  193. 'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,
  194. 'plugins.list': self.plugins_list, 'command.observe': self.command_observe,
  195. 'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,
  196. 'session.list': self.list_sessions, 'session.info': self.info,
  197. 'session.mutate': self.mutate, 'bot_relay.deliver': self.bot_deliver,
  198. 'bot_relay.settle': self.bot_settle, 'bot_relay.cancel': self.bot_cancel,
  199. 'bot_relay.roster.sync': self.bot_roster, 'bot_relay.outbox.drain': self.bot_outbox,
  200. 'bot_relay.reply': self.bot_reply, 'a2a.forward': self.a2a_forward,
  201. 'kanban.run': self.kanban_run,
  202. 'cron.submit': self.cron_submit, 'cron.status': self.cron_status,
  203. 'cron.cancel': self.cron_cancel, 'cron.recover': self.cron_recover,
  204. 'worker.register': self.worker_register, 'worker.adopt': self.worker_adopt,
  205. 'worker.persist': self.worker_persist,
  206. 'setup.status': self.setup_status, 'setup.runtime_check': self.setup_runtime_check,
  207. 'session.resume': self.resume, 'session.detach': self.detach,
  208. 'prompt.submit': self.submit,
  209. 'prompt.receipt': self.receipt, 'prompt.cancel': self.cancel,
  210. 'prompt.resolve_unknown': self.resolve_unknown,
  211. 'session.interrupt': self.interrupt, 'session.events.since': self.events_since,
  212. 'approval.respond': self.respond, 'clarify.respond': self.respond_clarify}
  213. from gateway.session_busy_controls import handlers as busy_handlers
  214. handlers.update(busy_handlers(self))
  215. from gateway.session_queued_controls import handlers as queued_handlers
  216. handlers.update(queued_handlers(self))
  217. from gateway.session_config import handlers as config_handlers
  218. handlers.update(config_handlers(self))
  219. from gateway.session_tui_config import handlers as tui_config_handlers
  220. handlers.update(tui_config_handlers(self))
  221. from gateway.session_ancillary import handlers as ancillary_handlers
  222. handlers.update(ancillary_handlers(self))
  223. from gateway.session_shell import handlers as shell_handlers
  224. handlers.update(shell_handlers(self))
  225. from gateway.session_tui_ops import handlers as tui_ops_handlers
  226. handlers.update(tui_ops_handlers(self))
  227. from gateway.session_tui_side import handlers as side_handlers
  228. handlers.update(side_handlers(self))
  229. from gateway.session_llm_oneshot import handlers as oneshot_handlers
  230. handlers.update(oneshot_handlers(self))
  231. from gateway.session_images import attach_bytes
  232. from functools import partial
  233. handlers['image.attach_bytes'] = partial(attach_bytes, self)
  234. from gateway.session_complete_path import complete_path
  235. handlers['complete.path'] = partial(complete_path, self)
  236. from gateway.session_prune import prune
  237. handlers['session.prune'] = partial(prune, self)
  238. from gateway.session_usage import stats
  239. handlers['session.stats'] = partial(stats, self)
  240. from gateway.session_active_list import active_list
  241. handlers['session.active_list'] = partial(active_list, self)
  242. from gateway.session_viewer_automation import automation
  243. handlers['session.automation'] = partial(automation, self)
  244. from gateway.session_reactions import react
  245. handlers['message.react'] = partial(react, self)
  246. from gateway.session_clarify_lock import clarify_lock
  247. handlers['clarify.lock'] = partial(clarify_lock, self)
  248. from gateway.session_connections import handlers as connection_handlers
  249. handlers.update(connection_handlers(self))
  250. from gateway.session_control_actions import control
  251. handlers['session.control'] = partial(control, self)
  252. from gateway.session_onboarding import handlers as onboarding_handlers
  253. handlers.update(onboarding_handlers(self))
  254. return handlers
  255. async def dispatch(self, request):
  256. from gateway.session_server_requests import is_response_frame
  257. if is_response_frame(request):
  258. # A viewer answering one of the owner's server→client requests (the sudo prompt): a
  259. # response gets no reply (JSON-RPC), and only a viewer entitled to respond on that
  260. # session settles it.
  261. self._resolve_response(request)
  262. return None
  263. rid = request.get('id')
  264. method = request.get('method')
  265. params = request.get('params') or {}
  266. if not isinstance(params, dict):
  267. # Every handler indexes params as a mapping; refuse the frame before ``.get``.
  268. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  269. 'code': 4001, 'message': 'invalid_params', 'data': {'reason': 'invalid_params'}}}
  270. from gateway.drain_control import ws_method_refused_while_draining
  271. if self._operator is True and ws_method_refused_while_draining(getattr(self.authority, 'runner', None), method):
  272. # An interactive socket reaches a draining owner only in a restart's after-turn wait:
  273. # it may answer the parked turn and queue input, never change this owner's state.
  274. exc = RuntimeStoreError('runtime_draining')
  275. _log_refusal(getattr(self.actor, 'profile_id', None), method, exc)
  276. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  277. 'code': 4001, 'message': exc.reason, 'data': _refusal_data(exc)}}
  278. profile = params.get('profile')
  279. if isinstance(profile, str) and profile:
  280. try:
  281. routed = self._sibling_for(profile)
  282. except RuntimeStoreError as exc:
  283. _log_refusal(getattr(self.actor, 'profile_id', None), method, exc)
  284. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  285. 'code': 4001, 'message': exc.reason, 'data': _refusal_data(exc)}}
  286. if routed is not None:
  287. return await routed.dispatch(request)
  288. # Our own home: the scope is implicit for the strict session verbs, which refuse
  289. # unknown keys; every other handler validates ``profile`` itself.
  290. if method in _PROFILE_IMPLICIT:
  291. params = {key: value for key, value in params.items() if key != 'profile'}
  292. ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))
  293. from tui_gateway.contracts.registry import (
  294. CANONICAL_METHODS, METHODS, canonical_param_problems, check_params_accepted, check_result,
  295. unknown_method_message,
  296. )
  297. contract = CANONICAL_METHODS.get(method)
  298. if contract is not None and (problems := canonical_param_problems(contract, params)):
  299. # The declared wire contract (``tui_gateway/contracts/canonical.py``) is the closed
  300. # key set: an unknown or missing key never reaches the handler.
  301. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  302. 'code': 4001, 'message': 'invalid_params', 'data': {'reason': 'invalid_params', 'fields': problems}}}
  303. original_params = dict(params)
  304. contract = contract or METHODS.get(method)
  305. authority = self.authority
  306. if (isinstance(ref.session_id, str) and ref.session_id and not getattr(authority, 'retiring', False)
  307. and ref.profile_id == getattr(authority, 'profile_id', None)
  308. and ref.session_id not in getattr(authority, 'sessions', {ref.session_id: None})):
  309. # A first read of a session recovery never restored: its compression catch-up (#140060)
  310. # commits in a worker here, so the handler's synchronous restore only reads.
  311. from gateway.session_local_adoption import adopt_before_restore
  312. await adopt_before_restore(authority, ref.session_id)
  313. handlers = self.handlers()
  314. try:
  315. from gateway.session_group_controls import GROUP_METHODS, dispatch_group_control
  316. # Every handler reads config/jobs/policy for the OWNING profile: enter its home so
  317. # ``_load_gateway_config`` / ``build_policy(get_hermes_home())`` never snapshot the
  318. # launch profile's config into a served secondary's session. Under a single profile
  319. # the scope is that profile's own home, so behaviour is unchanged.
  320. from gateway.session_authorities import async_owner_scope
  321. from gateway.session_connections import METHODS as CONNECTION_METHODS, session_owned
  322. async with async_owner_scope(self.authority):
  323. if method in GROUP_METHODS or method == 'profiles.list':
  324. result = await dispatch_group_control(self, method, params)
  325. elif method not in handlers or (method in CONNECTION_METHODS and not session_owned(params)):
  326. # JSON-RPC's own verdict: clients key compat fallbacks on -32601, and a
  327. # 4001 'invalid_params' would read as a bad argument on a method that exists.
  328. # An account-owned connector call (the Connectors page) keeps its legacy handler.
  329. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  330. 'code': -32601, 'message': unknown_method_message(method),
  331. 'data': {'reason': 'unknown_method'}}}
  332. else:
  333. result = await handlers[method](ref, params)
  334. if isinstance(result, DeferredReply): # answered off the serial dispatch
  335. check_params_accepted(contract, original_params)
  336. return result.start(self, rid, partial(check_result, contract))
  337. check_params_accepted(contract, original_params)
  338. check_result(contract, result)
  339. return {'jsonrpc': '2.0', 'id': rid, 'result': result}
  340. except RuntimeStoreError as exc:
  341. _log_refusal(getattr(self.actor, 'profile_id', None), method, exc)
  342. # A connector refusal keeps the legacy handlers' code and message (gateway/session_connections.py).
  343. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  344. 'code': getattr(exc, 'wire_code', 4001), 'message': getattr(exc, 'wire_message', exc.reason),
  345. 'data': _refusal_data(exc)}}
  346. except sqlite3.Error as exc:
  347. _log_storage_failure(getattr(self.actor, 'profile_id', None), method,
  348. params.get('session_id'), exc)
  349. return {'jsonrpc': '2.0', 'id': rid, 'error': {
  350. 'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}
  351. async def a2a_forward(self, ref, params):
  352. from gateway.session_a2a import forward
  353. return await forward(self, params)
  354. async def kanban_run(self, ref, params):
  355. from gateway.session_kanban import run_task
  356. return await run_task(self, params)
  357. async def cron_recover(self, ref, params):
  358. from gateway.session_cron import rpc
  359. return await rpc(self, 'recover', params)
  360. async def cron_submit(self, ref, params):
  361. from gateway.session_cron import rpc
  362. return await rpc(self, 'submit', params)
  363. async def cron_status(self, ref, params):
  364. from gateway.session_cron import rpc
  365. return await rpc(self, 'status', params)
  366. async def cron_cancel(self, ref, params):
  367. from gateway.session_cron import rpc
  368. return await rpc(self, 'cancel', params)
  369. async def bot_roster(self, ref, params):
  370. from gateway.session_bot import relay_operation
  371. return relay_operation(self, 'roster', params)
  372. async def bot_outbox(self, ref, params):
  373. from gateway.session_bot import relay_operation
  374. return relay_operation(self, 'outbox', params)
  375. async def bot_reply(self, ref, params):
  376. from gateway.session_bot import relay_operation
  377. return relay_operation(self, 'reply', params)
  378. async def bot_deliver(self, ref, params):
  379. from gateway.session_bot import deliver
  380. return await deliver(self, params)
  381. async def bot_settle(self, ref, params):
  382. from gateway.session_bot import settle
  383. return await settle(self, params)
  384. async def bot_cancel(self, ref, params):
  385. from gateway.session_bot_cancel import cancel
  386. return await cancel(self, params)
  387. async def worker_register(self, ref, params):
  388. from gateway.session_worker import worker_request
  389. return await worker_request(self, ref, params, operation='register')
  390. async def worker_adopt(self, ref, params):
  391. from gateway.session_worker import worker_request
  392. return await worker_request(self, ref, params, operation='adopt')
  393. async def worker_persist(self, ref, params):
  394. from gateway.session_worker import worker_request
  395. return await worker_request(self, ref, params, operation='persist')
  396. async def slash_exec(self, ref, params):
  397. from gateway.session_commands import execute_command
  398. return await execute_command(self, ref, params)
  399. async def command_dispatch(self, ref, params):
  400. from gateway.session_commands import execute_command
  401. return await execute_command(self, ref, params, dispatch=True)
  402. async def command_observe(self, ref, params):
  403. from gateway.session_commands import observe_command
  404. return await observe_command(self, ref, params)
  405. async def command_catalog(self, ref, params):
  406. from gateway.session_discovery import discover_commands
  407. return await discover_commands(self.authority, self.actor, params)
  408. async def plugins_list(self, ref, params):
  409. from gateway.session_discovery import list_plugins
  410. return await list_plugins(self.authority, self.actor, params)
  411. async def slash_completions(self, ref, params):
  412. from gateway.session_discovery import discover_commands
  413. return await discover_commands(self.authority, self.actor, params, completion=True)
  414. async def setup_status(self, ref, params):
  415. from gateway.session_readiness import readiness
  416. return await readiness(self.authority, self.actor, params, runtime=False)
  417. async def setup_runtime_check(self, ref, params):
  418. from gateway.session_readiness import readiness
  419. return await readiness(self.authority, self.actor, params, runtime=True)
  420. async def create(self, ref, params):
  421. from gateway.session_local_title import validate_title
  422. title = validate_title(params.pop('title')) if 'title' in params else None
  423. if title is None:
  424. return await self._create(params, None)
  425. # ``-c <title> --create-if-missing``: resolve -> create -> title is one owner step per
  426. # authority (the commits run off the loop), so concurrent programmatic callers converge.
  427. lock = getattr(self.authority, '_titled_create_lock', None)
  428. if lock is None:
  429. lock = self.authority._titled_create_lock = asyncio.Lock()
  430. async with lock:
  431. return await self._create(params, title)
  432. async def _create(self, params, title):
  433. from gateway.session_local import stage_local_session, staged_creation_follows
  434. from gateway.session_local_recovery import restore_local_session
  435. from gateway.session_local_title import resolve_titled_session, title_new_session
  436. from gateway.session_policy import BYPASS_FIELDS
  437. from gateway.session_runtime_workers import tracked_write
  438. from hermes_state_local import commit_local_session
  439. # Bot Mode's forever-chat mint: born hidden from the sidebar. `follow_profile_config` stays in
  440. # the frozen request: the policy re-reads the profile's current route every turn.
  441. hidden = params.pop('hidden', False)
  442. if type(hidden) is not bool:
  443. raise RuntimeStoreError('invalid_params', field='hidden', detail='must be a boolean')
  444. ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)
  445. if (not ref and title == 'Bot Chat'
  446. and not any(params.get(name) is True for name in BYPASS_FIELDS)
  447. and staged_creation_follows(self.authority, self.actor, params.get('request_id'))):
  448. # ``chat -c "Bot Chat" --create-if-missing`` and any other titled create. A safe-mode
  449. # or ignore-user-config launch never reads the profile, so it stays frozen. An exact
  450. # retry of a creation staged without the flag keeps that frozen request.
  451. params.setdefault('follow_profile_config', True)
  452. if not ref:
  453. skills_prompt = None
  454. if 'skills' in params:
  455. # Skill files are read off the owner loop, once per NEW session (a retried
  456. # request_id resumes the frozen policy and never re-renders).
  457. from gateway.session_local_recovery import local_identity
  458. from gateway.session_policy import render_launch_skills
  459. params.setdefault('request_id', uuid.uuid4().hex)
  460. sid = local_identity(self.authority.profile_id, self.actor.subject, params['request_id'])
  461. if self.authority.db.get_session(sid) is None:
  462. skills_prompt = await asyncio.to_thread(render_launch_skills, params, sid)
  463. # Host-bound client values apply only over the gateway's own ticketed attach (run_api).
  464. ref = stage_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt,
  465. client_local=self.native_owner,
  466. desktop_local=getattr(self.transport, 'desktop_local', False))
  467. if isinstance(ref, dict):
  468. # The creation commit runs off the owner loop: a held writer must not freeze
  469. # every session behind one new chat (N50).
  470. receipt = ref
  471. await tracked_write(self.authority, partial(
  472. commit_local_session, self.authority.db, epoch=self.authority.epoch, receipt=receipt))
  473. ref = restore_local_session(self.authority, receipt['session_id'])
  474. # `--accept-hooks`: record this launch's consent; ``resume`` below registers the hooks.
  475. if params.get('accept_hooks') is True:
  476. from gateway.session_policy import accept_launch_hooks, restore_policy
  477. from hermes_state_local import local_receipt
  478. policy = restore_policy(local_receipt(self.authority.db, ref.session_id)['policy'])
  479. await asyncio.to_thread(accept_launch_hooks, policy)
  480. if title:
  481. await tracked_write(self.authority, partial(title_new_session, self.authority, ref, title))
  482. if hidden:
  483. await tracked_write(self.authority, partial(self.authority.db.set_session_hidden, ref.session_id, True))
  484. return await self.resume(ref, {})
  485. async def ping(self, ref, params):
  486. if not self.actor.capabilities:
  487. raise RuntimeStoreError('permission_denied')
  488. if params:
  489. raise RuntimeStoreError('invalid_params')
  490. return {'pong': True}
  491. async def describe(self, ref, params):
  492. await self.ping(ref, params)
  493. from gateway.session_policy import CREATE_FIELDS, SURFACES
  494. from gateway.session_skin import resolved_skin
  495. return {'instance_id': self.authority.instance_id, 'profile_id': self.authority.profile_id,
  496. 'authority_epoch': self.authority.epoch,
  497. 'capabilities': ['durable-admission-v1', 'event-replay-v1', 'local-cli-create-v1', 'acp-editor-policy-v1',
  498. 'acp-session-mcp-v1', 'clarify-batch-v1'],
  499. 'session_create': {'sources': sorted(SURFACES),
  500. 'parameters': sorted(CREATE_FIELDS | {'title'})},
  501. # Main's ``gateway.ready.skin``: the canonical client's own ready carries it.
  502. 'skin': await asyncio.to_thread(resolved_skin)}
  503. async def info(self, ref, params):
  504. from gateway.session_local_inventory import snapshot_info
  505. if set(params) != {'session_id'}:
  506. raise RuntimeStoreError('invalid_params')
  507. await self.authority.resolve(self.actor, ref)
  508. return await snapshot_info(self.authority, ref)
  509. async def list_sessions(self, ref, params):
  510. if 'session:read' not in self.actor.capabilities:
  511. raise RuntimeStoreError('permission_denied')
  512. limit = params.get('limit', 200)
  513. if set(params) - {'limit', 'title', 'include_hidden', 'scope'} or type(limit) is not int or not 1 <= limit <= 200:
  514. raise RuntimeStoreError('invalid_params')
  515. if params.get('scope', 'live') not in {'live', 'stored'} or ('title' in params and 'scope' in params):
  516. raise RuntimeStoreError('invalid_params')
  517. if params.get('scope') == 'stored':
  518. from gateway.session_listing import stored_picker_sessions
  519. return await asyncio.to_thread(stored_picker_sessions, self.authority, self.actor,
  520. limit=limit, include_hidden=params.get('include_hidden', False))
  521. if 'title' in params:
  522. # Title-as-identity lookup (the Bots roster's forever-chat registry): the same
  523. # resolver `session.resume title=` uses, so a hidden canonical chat answers here
  524. # instead of being re-minted. Never confirms another principal's titles.
  525. from gateway.session_local_title import resolve_titled_session
  526. found = resolve_titled_session(self.authority, self.actor, params['title'], missing_ok=True)
  527. if found is None:
  528. return {'sessions': [], 'scope': 'stored'}
  529. row = self.authority.db.get_session(found.session_id) or {}
  530. root = self.authority.db.get_session(
  531. self.authority.db.resolve_session_by_title(params['title']) or found.session_id) or row
  532. return {'sessions': [{'session_id': found.session_id, 'id': root.get('id') or found.session_id,
  533. 'resolved_id': found.session_id, 'title': row.get('title') or '',
  534. 'root_title': root.get('title') or '', 'source': row.get('source'),
  535. 'started_at': row.get('started_at'),
  536. 'message_count': row.get('message_count', 0),
  537. 'running': found.session_id in self.authority.sessions}],
  538. 'scope': 'stored'}
  539. from hermes_state_sessions import INTERNAL_LISTING_SOURCES
  540. from gateway.session_live_listing import live_entries
  541. sessions = []
  542. for entry in await live_entries(self.authority, self.actor):
  543. row = entry.row
  544. # The human picker feed (TUI switcher): kanban workers, `--source tool` integrations and
  545. # finite one-shot runs are not conversations, as on every other picker. Closed by its last
  546. # viewer and idle: main lists it as resumable (the stored feed), not as a live session.
  547. if row.get('source') in INTERNAL_LISTING_SOURCES or entry.closed or (
  548. not params.get('include_hidden') and (row.get('hidden') or row.get('archived'))):
  549. continue
  550. sessions.append({'session_id': entry.session_id, 'id': entry.session_id, 'title': row.get('title') or '',
  551. 'source': row.get('source'), 'started_at': row.get('started_at'),
  552. 'message_count': row.get('message_count', 0), 'model': row.get('model'),
  553. 'running': entry.handle.execution_state == 'running'})
  554. sessions.sort(key=lambda row: row['started_at'] or 0, reverse=True)
  555. return {'sessions': sessions[:limit], 'scope': 'live'}
  556. async def resume(self, ref, params):
  557. from gateway.session_local_inventory import snapshot_info
  558. replay_from = self.replay_cursors.pop(ref.session_id, None)
  559. requested = ref.session_id
  560. if 'latest' in params:
  561. # Bare `-c` / `--resume latest`: the most recent session of that surface family the
  562. # actor may read (workspace first), resolved by the owner like a title.
  563. from gateway.session_local_title import resolve_latest_session
  564. ref = resolve_latest_session(self.authority, self.actor, params['latest'], params.get('workspace'))
  565. elif 'title' in params:
  566. from gateway.session_local_title import resolve_titled_session
  567. ref = resolve_titled_session(self.authority, self.actor, params['title'])
  568. else:
  569. # The TUI exit hint abbreviates canonical local IDs to ``local-`` plus 16 hex
  570. # characters. Resolve only that family before authorization so a unique hint reaches
  571. # the same durable local route as its full ID; ambiguous and missing prefixes retain
  572. # the normal not_found result.
  573. if re.fullmatch(r'local-[0-9a-f]{16}', ref.session_id):
  574. resolved_id = self.authority.db.resolve_session_id(ref.session_id)
  575. if resolved_id is not None:
  576. ref = SessionRef(ref.profile_id, resolved_id)
  577. from gateway.session_local_migration import adopts_client_history, resolve_local_target
  578. from gateway.session_policy_refresh import refresh_settled
  579. from hermes_state_local_migration import LEGACY_LOCAL_SOURCES
  580. # Another viewer's refresh mid-cleanup has committed a policy it has not published yet.
  581. await refresh_settled(self.authority, ref.session_id)
  582. row = self.authority.db.get_session(ref.session_id)
  583. # Canonical LOCAL compression/reset segments keep the receipt on their logical
  584. # owner, not on the physical transcript ID the history picker / Desktop supplies
  585. # after list_sessions projects the tip (#139306).
  586. if row and (row['source'] in LEGACY_LOCAL_SOURCES | {Platform.LOCAL.value}
  587. or adopts_client_history(self.authority, self.actor, row)):
  588. ref = resolve_local_target(self.authority, self.actor,
  589. self.authority.db.get_compression_tip(ref.session_id) or ref.session_id)
  590. elif row:
  591. # A messaging compression continuation attaches to its lineage root, the session
  592. # its lane's turns stream to; the reply names that root.
  593. from gateway.session_route_recovery import messaging_owner_ref
  594. ref = messaging_owner_ref(self.authority, ref)
  595. if params.get('editor') is not None:
  596. self.authority.authorize(self.actor, ref, 'session:control')
  597. from gateway.session_local_mcp import resume_editor_mcp
  598. resume_editor_mcp(self.authority, ref, params['editor'])
  599. if 'api_key' in params:
  600. # A launch-only key re-supplied after a restart (`--resume <id> --api-key`).
  601. self.authority.authorize(self.actor, ref, 'session:control')
  602. from gateway.session_policy import rebind_launch_key
  603. rebind_launch_key(self.authority, ref, params['api_key'])
  604. # Read-only mount (#85303): an ended row stays ended until the first admitted turn
  605. # reopens it (``reopen_local_session`` in the drain), so opening a finished chat
  606. # never re-lights DB-derived liveness with no new activity.
  607. self.authority.authorize(self.actor, ref, 'session:read')
  608. mounted = self.authority.sessions[ref.session_id].source
  609. # Only a local route has a stored creation policy to refresh; a platform lane's turns read the profile.
  610. if 'session:control' in self.actor.capabilities and getattr(mounted, 'platform', None) == Platform.LOCAL:
  611. # A client attaching (main's `hermes -c` was a new process) re-reads the config-derived settings
  612. # (CFG-2); a snapshot poll on this attachment does not. Any open still adopts a frozen Bot Chat
  613. # whose earlier open found it busy (Desktop's warm `session.activate` resumes on one connection).
  614. from gateway.session_policy_refresh import refresh_resumed_policy
  615. await refresh_resumed_policy(self.authority, ref, attached=ref.session_id in self.subscriptions)
  616. # ``omit_messages``: the client pages the transcript itself (Desktop over REST), so the attach reads no
  617. # compression lineage (a whole-lineage read here made every open of a long chat cost seconds).
  618. omit = params.get('omit_messages') is True
  619. snapshot = await self.authority.attach(
  620. self.actor, ref, history=not omit, replay_from=replay_from if ref.session_id == requested else None)
  621. self.subscriptions[ref.session_id] = snapshot.subscription_id
  622. self.handed_back.discard(ref.session_id)
  623. self._spawn_notice(ref)
  624. # Only local routes have a frozen local launch policy to project; with it, main's banner and
  625. # status-bar inventory (tools, skills, MCP, version, branch) for that policy.
  626. info = {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}
  627. source = self.authority.sessions[snapshot.handle.ref.session_id].source
  628. if source is not None and source.platform == Platform.LOCAL:
  629. from gateway.session_policy import policy_for_source, refresh_profile_hooks
  630. await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))
  631. info = await snapshot_info(self.authority, snapshot.handle.ref)
  632. from gateway.session_connections import pending_connection
  633. from gateway.session_server_requests import open_requests
  634. history, display = list(snapshot.history), {}
  635. if params.get('display_projection'):
  636. # A micro-compaction merge stays in ``messages`` (an undo target); its originals are what shows.
  637. display['display_messages'] = display_projection(
  638. [row for row in history if not model_only(row)], self.authority.profile_id)
  639. return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,
  640. **await _resume_transcript(self.authority, ref, snapshot, history, omit), **display,
  641. 'running': snapshot.handle.execution_state == 'running',
  642. 'authority_epoch': snapshot.handle.authority_epoch,
  643. 'replay_epoch': snapshot.replay_epoch, 'last_sequence': snapshot.last_sequence,
  644. 'subscription_id': snapshot.subscription_id, 'revision': snapshot.handle.revision,
  645. 'execution_generation': snapshot.handle.execution_generation,
  646. 'pending': [asdict(r) for r in snapshot.pending],
  647. 'prompts': list(snapshot.prompts), 'info': info,
  648. 'pending_connection': pending_connection(self.authority, ref.session_id),
  649. # Still-waiting server→client requests: the event ring cannot say "still open".
  650. 'open_requests': open_requests(self.authority.sessions[snapshot.handle.ref.session_id].event_stream,
  651. snapshot.handle.ref.session_id)}
  652. def _spawn_notice(self, ref):
  653. """Low-disk auto-prune question for this viewer, off the resume reply's path."""
  654. from gateway.run_housekeeping_disk import publish_local_auto_prune_notice
  655. task = asyncio.get_running_loop().create_task(publish_local_auto_prune_notice(self.authority, ref))
  656. tasks = self.__dict__.setdefault('_notice_tasks', set())
  657. tasks.add(task)
  658. task.add_done_callback(tasks.discard)
  659. async def detach(self, ref, params):
  660. if set(params) - {'end_reason'} != {'session_id', 'subscription_id'}:
  661. raise RuntimeStoreError('invalid_params')
  662. session_id = params['session_id']
  663. subscription_id = params['subscription_id']
  664. # ``end_reason``: this viewer is CLOSING the conversation (main's classic CLI stamped its row
  665. # ``cli_close`` / ``new_session`` / ``resumed_other`` / ``branched`` itself); the owner ends the
  666. # idle local row once no viewer is left. Absent, a detach is only a viewer leaving.
  667. end_reason = params.get('end_reason')
  668. if (not isinstance(session_id, str) or not session_id
  669. or not isinstance(subscription_id, str) or not subscription_id
  670. or (end_reason is not None
  671. and not (isinstance(end_reason, str) and _END_REASON.fullmatch(end_reason)))):
  672. raise RuntimeStoreError('invalid_params')
  673. result = {'session_id': session_id, 'subscription_id': subscription_id,
  674. 'detached': False}
  675. if self.subscriptions.get(session_id) != subscription_id:
  676. return result
  677. await self.authority.detach(self.actor, subscription_id, end_reason=end_reason)
  678. if self.subscriptions.get(session_id) == subscription_id:
  679. del self.subscriptions[session_id]
  680. (self.handed_back.discard if end_reason else self.handed_back.add)(session_id)
  681. result['detached'] = True
  682. return result
  683. async def events_since(self, ref, params):
  684. self.authority.authorize(self.actor, ref, 'session:read')
  685. sequence = params.get('last_sequence', params.get('last_seen', 0))
  686. epoch = params.get('replay_epoch')
  687. if type(sequence) is not int or sequence < 0 or (epoch is not None and not isinstance(epoch, str)):
  688. raise RuntimeStoreError('invalid_params')
  689. from gateway.session_server_requests import open_requests
  690. stream = self.authority.sessions[ref.session_id].event_stream
  691. replay = stream.since(epoch, sequence)
  692. if not replay['snapshot_required']:
  693. self.replay_cursors[ref.session_id] = (
  694. replay['replay_epoch'], max((frame['seq'] for frame in replay['events']), default=sequence))
  695. return {**replay, 'open_requests': open_requests(stream, ref.session_id)}
  696. async def submit(self, ref, params):
  697. if self._voice_stop_replay(ref, params) or await self._typed_voice_stop(ref, params):
  698. self._record_voice_stop(ref, params)
  699. return {'voice_stopped': True}
  700. # The interactive WS is the one surface a restart's after-turn wait admits (#139041).
  701. receipt = await self.authority.submit(self.actor, self.submission(ref, params),
  702. queue_while_restarting=self._operator is True)
  703. return asdict(receipt)
  704. def _voice_stop_key(self, ref, params):
  705. request_id = params.get('submission_id') or params.get('input_id')
  706. if not isinstance(request_id, str) or not request_id:
  707. return None
  708. return (self.actor.subject, ref.profile_id, ref.session_id, request_id)
  709. def _voice_stop_replay(self, ref, params):
  710. """A retry of a stop this owner already consumed (its reply was lost; Ink offers Alt+K on the
  711. same submission id). Voice is off by then, so the phrase check alone would admit ``stop`` as a
  712. turn: the request identity answers it again, as an admission's replay would."""
  713. key = self._voice_stop_key(ref, params)
  714. if key is None or key not in getattr(self.authority, '_consumed_voice_stops', {}):
  715. return False
  716. if ref.session_id not in self.subscriptions:
  717. return False # submission() refuses it as permission_denied
  718. self.authority.authorize(self.actor, ref, 'session:submit')
  719. return True
  720. def _record_voice_stop(self, ref, params):
  721. from collections import OrderedDict
  722. key = self._voice_stop_key(ref, params)
  723. if key is None:
  724. return
  725. consumed = self.authority.__dict__.setdefault('_consumed_voice_stops', OrderedDict())
  726. consumed[key] = True
  727. consumed.move_to_end(key)
  728. while len(consumed) > 256:
  729. consumed.popitem(last=False)
  730. async def _typed_voice_stop(self, ref, params):
  731. """TUI-26: a bare stop phrase typed while the session's voice chat is on ends the chat
  732. (the sidecar's ``methods_prompt._consume_typed_stop_phrase``, its typed twin of the spoken
  733. stop) and is never admitted. Only a submitter attached to the session may end it, and only
  734. on a LOCAL session: a messaging lane's own ``/voice`` mode belongs to that chat, so a
  735. viewer's typed text there is admitted untouched."""
  736. text = params.get('text')
  737. if not isinstance(text, str):
  738. return False
  739. if ref.session_id not in self.subscriptions:
  740. return False # submission() refuses it as permission_denied
  741. self.authority.authorize(self.actor, ref, 'session:submit')
  742. live = self.authority.sessions.get(ref.session_id)
  743. source = getattr(live, 'source', None)
  744. if source is None or source.platform != Platform.LOCAL:
  745. return False
  746. from gateway.session_config import local_voice_enabled
  747. if not local_voice_enabled(ref.session_id):
  748. return False
  749. from tui_gateway import server
  750. return await asyncio.to_thread(server._consume_typed_stop_phrase, text, ref.session_id, emit=False)
  751. def submission(self, ref, params):
  752. """The admission a ``prompt.submit``-shaped request asks for (``prompt.replace_queued`` too)."""
  753. if ref.session_id not in self.subscriptions:
  754. raise RuntimeStoreError('permission_denied')
  755. forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued', 'attachments', 'finite', 'unattended',
  756. 'surface', 'voice_context', 'interrupted', 'voice_turn', 'display_kind', 'title_preview',
  757. 'turn_author', 'api_text', 'model_override', 'clarify_batch'}
  758. if forbidden:
  759. raise RuntimeStoreError('invalid_params')
  760. request_id = params.get('submission_id') or params.get('input_id')
  761. if not isinstance(request_id, str) or not request_id:
  762. raise RuntimeStoreError('invalid_params')
  763. from gateway.session_finite import admit_finite
  764. from gateway.session_display import submit_display_fields
  765. from gateway.session_surface import submit_surface_fields
  766. from gateway.session_cli_turn import submit_cli_turn_fields
  767. payload = {'text': params.get('text'), **admit_finite(params, submitter=(self, ref)), **submit_surface_fields(params),
  768. **submit_display_fields(params), **submit_cli_turn_fields(params)}
  769. if 'attachments' in params:
  770. payload['attachments'] = params['attachments']
  771. return Submission(request_id, ref, payload, 'queue')
  772. async def mutate(self, ref, params):
  773. from gateway.session_mutations import mutate_session
  774. from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS, busy_refusal
  775. try:
  776. result = await mutate_session(self.authority, self.actor, ref, params)
  777. except MUTATION_GUARD_REFUSALS as exc:
  778. # A live turn lease / compression lock is the same retryable busy verdict a
  779. # running admission gets (REST maps it to 409), not an internal error.
  780. raise busy_refusal(exc) from exc
  781. except RuntimeStoreError as exc:
  782. if exc.reason in {'revision_conflict', 'stale_generation'}:
  783. # The fresh fences ride on the refusal, so the client retries once without a re-read.
  784. row = await asyncio.to_thread(self.authority.db.get_session, ref.session_id)
  785. if row is not None:
  786. exc.revision, exc.execution_generation = row['runtime_revision'], row['runtime_generation']
  787. raise
  788. # The branching viewer navigates straight into its new child; attach it
  789. # here (create parity) so the first submit is not refused as a stranger.
  790. child = result.get('branched_session_id') if isinstance(result, dict) else None
  791. if child and child not in self.subscriptions:
  792. await self.resume(SessionRef(ref.profile_id, child), {})
  793. return result
  794. async def receipt(self, ref, params):
  795. receipt = await self.authority.receipt(self.actor, ref, params.get('admission_id'))
  796. out = asdict(receipt)
  797. if params.get('include_result') is True and receipt.status == 'terminal':
  798. # The exact structured result the turn committed with settlement (`finish_result`):
  799. # a finite viewer reads its ledger (tokens, cost, model, exit reason) from here, the same
  800. # dict the in-process one-shot wrote from `run_conversation`.
  801. from gateway.session_results import admission_result
  802. saved = admission_result(self.authority.db, receipt.admission_id)
  803. if saved is not None:
  804. out['result'] = saved['result']
  805. out['usage'] = saved.get('usage') or {}
  806. return out
  807. async def cancel(self, ref, params):
  808. admission_id = params.get('admission_id')
  809. receipt = await self.authority.receipt(self.actor, ref, admission_id)
  810. from hermes_state_runtime import get_session_admission
  811. # A transferred steer also reads started (as its receiving claim): only its own claim is stopped here;
  812. # the transfer is refused below and settles with that claim.
  813. if receipt.status == 'started' and get_session_admission(
  814. self.authority.db, admission_id=admission_id)['status'] == 'started':
  815. # Stopped in this RPC: an editor that exits right after its cancel never sends a follow-up
  816. # interrupt. A stale generation means the turn already settled.
  817. try:
  818. await self.interrupt(ref, {'execution_generation': receipt.execution_generation})
  819. except RuntimeStoreError as exc:
  820. if exc.reason != 'stale_generation':
  821. raise
  822. return asdict(await self.authority.receipt(self.actor, ref, admission_id))
  823. if receipt.status != 'queued':
  824. return asdict(await self.authority.cancel_queued(self.actor, ref, admission_id))
  825. # Queued at this read, claimed by the drain before the cancel commit: Stop that exact claim (as
  826. # API and ACP do) instead of refusing while the withdrawn prompt runs.
  827. row = await self.authority.cancel_or_claimed(self.actor, ref, admission_id)
  828. if row is not None:
  829. await self.interrupt(ref, {'execution_generation': row['generation']})
  830. return asdict(await self.authority.receipt(self.actor, ref, admission_id))
  831. async def resolve_unknown(self, ref, params):
  832. if set(params) != {'session_id', 'admission_id', 'execution_generation'}:
  833. raise RuntimeStoreError('invalid_params')
  834. return asdict(await self.authority.resolve_unknown(
  835. self.actor, ref, params['admission_id'], params['execution_generation']))
  836. async def interrupt(self, ref, params):
  837. from gateway.session_managed_worker import interrupt_managed
  838. if interrupt_managed(self.authority, self.actor, ref, params.get('execution_generation')):
  839. return asdict(self.authority._handle(ref))
  840. return asdict(await self.authority.interrupt(self.actor, ref, params.get('execution_generation')))
  841. def _resolve_response(self, frame):
  842. from gateway.session_server_requests import may_settle, resolve
  843. asked = []
  844. def entitled(session_id, events):
  845. asked.append(session_id)
  846. # The same rule ``clarify.lock`` applies to the same request id (attached + respond). A
  847. # response frame names no profile: a host-scoped socket answers a sibling's request as the
  848. # sibling connection that attached it.
  849. return any(may_settle(connection.authority, connection.actor, session_id, events)
  850. for connection in (self, *self._siblings.values()))
  851. if not resolve(frame, session_ok=entitled):
  852. import logging
  853. what = 'a server request this connection may not settle' if asked else 'unknown server request'
  854. logging.getLogger(__name__).debug('dropping response for %s id=%r', what, frame.get('id'))
  855. async def respond(self, ref, params):
  856. if set(params) != {"session_id", "execution_generation", "prompt_id", "choice"}:
  857. raise RuntimeStoreError("invalid_params")
  858. return await self.authority.respond(self.actor, ref, params["execution_generation"],
  859. params["prompt_id"], {"choice": params["choice"]})
  860. async def respond_clarify(self, ref, params):
  861. if set(params) != {"session_id", "execution_generation", "prompt_id", "answer"}:
  862. raise RuntimeStoreError("invalid_params")
  863. return await self.authority.respond(self.actor, ref, params["execution_generation"],
  864. params["prompt_id"], {"answer": params["answer"]}, kind="clarify")
  865. async def close(self):
  866. for sibling in self._siblings.values():
  867. await sibling.close()
  868. self._siblings.clear()
  869. from gateway.session_llm_oneshot import forget
  870. forget(self) # nobody is left to read its one-shot replies
  871. # Deletion may already have evicted a subscribed session; its membership died
  872. # with it, and one retired ID must not leave the others (or the transport) attached.
  873. # A sibling's teardown runs under the primary socket's scope: detach as this owner, as dispatch does.
  874. from gateway.session_authorities import owner_scope
  875. with owner_scope(self.authority):
  876. for session_id, subscription in list(self.subscriptions.items()):
  877. live = self.authority.sessions.get(session_id)
  878. if live is not None and subscription in live.subscribers:
  879. await self.authority.detach(self.actor, subscription, orphaned=True)
  880. # Kept in the background by this client: losing it orphans them too, unless another viewer holds one.
  881. from gateway.session_viewer_close import arm_detached_orphan_close
  882. for session_id in self.handed_back:
  883. await arm_detached_orphan_close(self.authority, session_id)
  884. from gateway.session_local_migration import unbind_native_transport
  885. unbind_native_transport(self.authority, self.actor)
  886. self.subscriptions.clear()
  887. self.authority.events.pop(self.actor.transport_id, None)