session_local.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. """Fresh local routes owned by the authenticated gateway, not by a viewer.
  2. Source and supported launch settings are frozen per route, never process env.
  3. """
  4. from __future__ import annotations
  5. import json
  6. import logging
  7. import uuid
  8. from contextlib import contextmanager
  9. from gateway.config import Platform, PlatformConfig
  10. from gateway.platforms.base import BasePlatformAdapter, SendResult
  11. from gateway.session import SessionSource
  12. from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
  13. from hermes_state_runtime import RuntimeStoreError
  14. logger = logging.getLogger(__name__)
  15. class LocalSessionAdapter(BasePlatformAdapter):
  16. """Delivery stays in the canonical event stream; no second local transport."""
  17. def __init__(self, authority):
  18. super().__init__(PlatformConfig(enabled=True), Platform.LOCAL)
  19. self.authority = authority
  20. # Built outside ``_create_adapter``: without its runner a push wake skips the authority FIFO
  21. # and falls to a message handler this adapter never has (``deliver_wake``).
  22. self.gateway_runner = getattr(authority, 'runner', None)
  23. self.sources = {}
  24. self.policies = {}
  25. @staticmethod
  26. def _source_key(source):
  27. # A conversation its chat moved past keeps the chat's id, which every other one of that chat
  28. # shares: its own key names it (gateway/session_detached.py).
  29. from gateway.session_detached import detached_route_of
  30. return detached_route_of(source) or source.chat_id
  31. def authorize_source(self, source):
  32. saved = self.sources.get(self._source_key(source))
  33. if saved is None:
  34. return False
  35. original, identity = saved
  36. return (source is original and self._identity(source) == identity
  37. and any(live.source is source for live in self.authority.sessions.values()))
  38. @staticmethod
  39. def _identity(source):
  40. return source.platform, source.chat_id, source.user_id, source.profile, source.chat_type
  41. def register_source(self, source):
  42. self.sources[self._source_key(source)] = source, self._identity(source)
  43. def kept_source(self, source):
  44. """The object this route was admitted with when *source* is that same source: a closed
  45. conversation retired from memory comes back with it, so the results its background work
  46. still holds pass ``authorize_source`` (an identity check)."""
  47. saved = self.sources.get(self._source_key(source))
  48. return saved[0] if saved is not None and saved[0].to_dict() == source.to_dict() else source
  49. def forget(self, source, route):
  50. """A deleted conversation's admission source, frozen policy and post-delivery slot (a local
  51. route names one conversation; a detached copy keeps only its own key, its chat's stays)."""
  52. key = self._source_key(source)
  53. if self.sources.get(key, (None,))[0] is source:
  54. del self.sources[key]
  55. if key == source.chat_id and source.platform == Platform.LOCAL:
  56. self.policies.pop(key, None)
  57. self._post_delivery_callbacks.pop(route, None)
  58. async def connect(self, *, is_reconnect=False):
  59. return True
  60. async def disconnect(self):
  61. self.sources.clear()
  62. async def send(self, chat_id, content, reply_to=None, metadata=None):
  63. # TurnRunner already publishes model/tool deltas and settlement exactly once.
  64. return SendResult(success=True, message_id=uuid.uuid4().hex)
  65. async def edit_message(self, chat_id, message_id, content, *, finalize=False):
  66. return SendResult(success=True, message_id=message_id)
  67. async def _record_delivery_obligation(self, *args, **kwargs):
  68. # No platform ACK to lose: viewers replay the durable transcript. A ledger row would only
  69. # park a raw copy of the reply in state.db that no redelivery can ever use.
  70. return None
  71. async def send_typing(self, chat_id, metadata=None):
  72. return None
  73. async def get_chat_info(self, chat_id):
  74. return {'id': chat_id, 'type': 'dm'}
  75. async def send_exec_approval(self, **kwargs):
  76. # The existing callback owns registration in PendingControls. An ACK here
  77. # selects that rendering path without a plaintext fallback or a second waiter.
  78. return SendResult(success=True, message_id=uuid.uuid4().hex)
  79. async def send_clarify(self, chat_id, question, choices, clarify_id, session_key, metadata=None):
  80. error = self._unanswerable_clarify(chat_id)
  81. if error is not None:
  82. # Acknowledging this question would park the turn on an answer nobody can submit.
  83. # A structured decline releases the wait at once and skips the plain-text re-ask
  84. # (an ordinary failure would fall back to a send() that ACKs, and the turn would
  85. # wait the whole clarify timeout).
  86. from gateway.relay.egress import EGRESS_DECLINE_CODE
  87. return SendResult(success=False, error=error, error_kind='forbidden',
  88. raw_response={'success': False, 'code': EGRESS_DECLINE_CODE, 'error': error})
  89. # Local sessions keep the base prompt: a choice question also captures typed text.
  90. return await super().send_clarify(chat_id, question, choices, clarify_id, session_key, metadata)
  91. def _unanswerable_clarify(self, chat_id):
  92. """Why no one can answer a question asked in this chat now, or None to ask it.
  93. Hosted rooms (controls expose approvals only) and forwarded A2A conversations (the
  94. author is a remote peer with no prompt surface) never have an answering viewer. Any
  95. other chat can be answered by an attached viewer holding ``session:respond``; with none
  96. attached, a producer turn (Bot Chat DM, plugin/heartbeat injection) declines, while a
  97. viewer's own turn keeps waiting so its author can re-attach and answer."""
  98. policy = self.policies.get(chat_id)
  99. if policy is None:
  100. return None
  101. from gateway.session_a2a import is_forward_policy
  102. if policy.source == 'bot_room':
  103. return 'Clarification is unavailable in hosted rooms'
  104. if is_forward_policy(policy):
  105. return 'Clarification is unavailable to a forwarded peer'
  106. live = self.authority.sessions.get(chat_id)
  107. if live is None:
  108. return None
  109. with live.event_stream.lock:
  110. if any('session:respond' in member.capabilities for member in live.subscribers.values()):
  111. return None
  112. from hermes_state_runtime import list_session_admissions
  113. started = next((row for row in list_session_admissions(self.authority.db, session_id=chat_id)
  114. if row['status'] == 'started'), None)
  115. if started is not None and 'local_automation_v1' in started['payload']:
  116. return 'Clarification is unavailable: no viewer can answer this chat'
  117. return None
  118. def forget_live_session(authority, session_id, live):
  119. """What the local adapter and the authority keyed by a deleted live session."""
  120. authority.launch_sources.pop(session_id, None)
  121. if live.source is None or live.source.platform != Platform.LOCAL:
  122. return
  123. from gateway.session_local_recovery import local_adapter_map
  124. local = local_adapter_map(authority).get(Platform.LOCAL)
  125. if local is not None:
  126. local.forget(live.source, live.route)
  127. def authorize_local_source(runner, source):
  128. """None for legacy/nonlocal routes and history mounts; registered local adapters fail closed."""
  129. if source is None or source.platform != Platform.LOCAL:
  130. return None
  131. # A forged profile must not miss this adapter and fall into a messaging
  132. # allow-all policy. Local source identity is owned by this authority alone.
  133. from gateway.session_authorities import all_authorities
  134. owners = all_authorities(runner)
  135. adapter = runner._adapters_for_profile(source.profile).get(Platform.LOCAL)
  136. if not isinstance(adapter, LocalSessionAdapter):
  137. # A LOCAL source naming a profile this runtime does not serve must fail closed rather
  138. # than fall into a messaging allow-all policy; legacy runners (no authority) stay None.
  139. return False if owners else None
  140. # The adapter's authority must be one THIS runtime owns (the launch authority or a served
  141. # secondary's), never a stale/foreign object that happens to carry a LOCAL adapter.
  142. if not any(adapter.authority is owner for owner in owners):
  143. return False
  144. return adapter.authorize_source(source)
  145. def _bypass_policy(params, *, private_secrets, client_local=False):
  146. """Frozen snapshot for --safe-mode / --ignore-user-config: code defaults plus the explicit
  147. launch options. The profile's config.yaml/.env are never read, so a malformed profile cannot
  148. block or shape the session; there is no default model to inherit, so one must be explicit."""
  149. import copy
  150. from gateway.session_policy import build_policy
  151. from hermes_cli.config_defaults import DEFAULT_CONFIG
  152. if not params.get('model'):
  153. raise RuntimeStoreError('invalid_params', field='model',
  154. detail='a bypass launch has no profile to inherit a model from')
  155. defaults = copy.deepcopy(DEFAULT_CONFIG)
  156. if not isinstance(defaults.get('model'), dict): # code default is the empty string
  157. defaults['model'] = {}
  158. return build_policy(params, defaults, private_secrets=private_secrets, profile_terminal=False,
  159. client_local=client_local)
  160. def load_profile_config(home=None):
  161. """The profile's effective config.yaml for a NEW session's policy, ``${VAR}`` refs expanded against
  162. the profile's CURRENT ``.env`` (the source tool env refreshes from), not the env this daemon
  163. started with: a single-profile owner binds no secret scope and never reloads ``.env`` for local
  164. turns. A bound scope (a served profile's owner scope) already is that source and is kept; a miss
  165. on the launch profile still falls to the process env (systemd / ``op run`` injection)."""
  166. from pathlib import Path
  167. from gateway.run import _load_gateway_config
  168. with profile_env_scope(home):
  169. return _load_gateway_config(*(() if home is None else (Path(home) / 'config.yaml',)))
  170. @contextmanager
  171. def profile_env_scope(home=None):
  172. """Bind the profile's current ``.env`` (see ``load_profile_config``) unless a scope is bound."""
  173. from pathlib import Path
  174. from agent.secret_scope import build_profile_secret_scope, current_secret_scope, reset_secret_scope, set_secret_scope
  175. from gateway.run import _gateway_config_home
  176. if current_secret_scope() is not None:
  177. yield
  178. return
  179. home = Path(home) if home is not None else _gateway_config_home() # default: the active gateway home
  180. token = set_secret_scope(build_profile_secret_scope(home), profile_home=str(home))
  181. try:
  182. yield
  183. finally:
  184. reset_secret_scope(token)
  185. def project_plugins_warning(policy):
  186. """The plain notice for a session whose client opted into project plugins (its forwarded
  187. ``HERMES_ENABLE_PROJECT_PLUGINS``) in a folder that has some: the gateway never loads them."""
  188. from pathlib import Path
  189. from utils import is_truthy_value
  190. # The client's folder is a path on this host only for a client the gateway proved local.
  191. env = policy.client_env() if policy is not None and not policy.client_env_remote else None
  192. folder = Path(policy.cwd) / '.hermes' / 'plugins' if env else None
  193. if not env or not is_truthy_value(env.get('HERMES_ENABLE_PROJECT_PLUGINS')) or not folder.is_dir():
  194. return None
  195. try:
  196. if not any(folder.iterdir()):
  197. return None
  198. except OSError: # an unlistable folder skips the optional notice, never the session
  199. return None
  200. return (f'project plugins in {folder} are not loaded: the gateway that runs Hermes sessions does not '
  201. 'load ./.hermes/plugins, so HERMES_ENABLE_PROJECT_PLUGINS has no effect here.')
  202. def create_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None,
  203. client_local=False):
  204. """Stage, commit and publish a local session inline (synchronous callers)."""
  205. from gateway.session_local_recovery import restore_local_session
  206. from hermes_state_local import commit_local_session
  207. staged = stage_local_session(authority, actor, params, trusted_policy=trusted_policy,
  208. trusted_secrets=trusted_secrets, skills_prompt=skills_prompt,
  209. client_local=client_local)
  210. if isinstance(staged, dict):
  211. commit_local_session(authority.db, epoch=authority.epoch, receipt=staged)
  212. staged = restore_local_session(authority, staged['session_id'])
  213. return staged
  214. def staged_creation_follows(authority, actor, request_id):
  215. """Whether a retry of *request_id* may ask to follow the profile.
  216. True when nothing is staged under that identity, or the staged request already follows.
  217. False only when an older build committed the session without ``follow_profile_config`` and
  218. stopped before its title. The next attempt reuses the identity, and a different request is
  219. refused for good. The retry then carries the frozen request.
  220. """
  221. if not isinstance(request_id, str) or not request_id:
  222. return True
  223. from gateway.session_local_recovery import local_identity
  224. from hermes_state_local import local_receipt
  225. sid = local_identity(authority.profile_id, actor.subject, request_id)
  226. if authority.db.get_session(sid) is None:
  227. return True
  228. try:
  229. request = json.loads(local_receipt(authority.db, sid)['policy']['request_json'])
  230. except (KeyError, TypeError, ValueError, RuntimeStoreError):
  231. return True
  232. return isinstance(request, dict) and request.get('follow_profile_config') is True
  233. def stage_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None,
  234. client_local=False, desktop_local=False):
  235. """Everything before the creation commit: the existing session's ref on an exact retry, else the
  236. receipt ``commit_local_session`` writes (the async RPC commits it off the owner loop).
  237. ``client_local``: the gateway's own proof that the client is on this host (its connection redeemed a
  238. ticket minted over the private control socket), never a value the client sends. ``desktop_local``:
  239. that client is also the Desktop app (``process_identity.local_desktop_client``); a Desktop chat
  240. records it so its turns run as work for the local Desktop (``session_policy.local_desktop_turn``)."""
  241. if actor.profile_id != authority.profile_id:
  242. raise RuntimeStoreError('profile_mismatch')
  243. if 'session:create' not in actor.capabilities:
  244. raise RuntimeStoreError('permission_denied')
  245. from gateway.session_policy import build_policy, BYPASS_FIELDS, FOLLOW_ADOPTED, LOCAL_DESKTOP_CHAT
  246. from gateway.run import _resolve_gateway_model
  247. from dataclasses import replace
  248. private_secrets = dict(trusted_secrets or {})
  249. client_key = params.get('api_key') # the client's own; an alias's key is the owner's expansion
  250. if trusted_policy is not None:
  251. policy = trusted_policy
  252. elif any(params.get(name) is True for name in BYPASS_FIELDS):
  253. policy = _bypass_policy(params, private_secrets=private_secrets, client_local=client_local)
  254. else:
  255. from gateway.session_local_route import resolve_launch_route
  256. raw_model, sent = params.get('model'), params
  257. with profile_env_scope(): # an alias's ``key_env`` / ``${VAR}`` key reads the same .env
  258. config = load_profile_config()
  259. params = resolve_launch_route(params, config)
  260. # A client's session.create is the one caller whose named folder may select the coding posture.
  261. policy = build_policy(params, config, private_secrets=private_secrets, workspace_posture=True,
  262. client_local=client_local)
  263. if params is not sent: # resolved, even to a model of the alias's own name
  264. # Owner-stamped provenance (not create fields): a remote client cannot re-resolve the typed
  265. # `-m` alias against its own home, so resume and an exact retry compare a repeat against the
  266. # name, and ``route_derived`` names the fields the route (not the client) filled.
  267. import json
  268. derived = sorted(key for key in ('provider', 'base_url') if key in params and key not in sent)
  269. policy = replace(policy, request_json=json.dumps(
  270. {**json.loads(policy.request_json), 'model_requested': raw_model, 'route_derived': derived},
  271. sort_keys=True))
  272. marks = {LOCAL_DESKTOP_CHAT: True} if desktop_local and policy.source == 'gui' else {}
  273. if policy.model is None:
  274. from hermes_cli.anon_auth import GUEST_MODEL
  275. policy = replace(policy, model=_resolve_gateway_model(policy.config()) or None)
  276. if policy.model == GUEST_MODEL:
  277. # Follows its profile, so the provider the user connects later replaces the trial model.
  278. marks[FOLLOW_ADOPTED] = True
  279. if marks:
  280. import json
  281. policy = replace(policy, config_json=json.dumps({**json.loads(policy.config_json), **marks}))
  282. request_id = params.get('request_id', uuid.uuid4().hex)
  283. if not isinstance(request_id, str) or not request_id or len(request_id) > 256:
  284. raise RuntimeStoreError('invalid_params', field='request_id',
  285. detail='must be a non-empty string of at most 256 characters')
  286. from dataclasses import asdict
  287. from gateway.session import SessionEntry
  288. from gateway.session_lifecycle import _now
  289. from gateway.session_local_recovery import local_identity, restore_local_session
  290. authority._require_admission_open()
  291. sid = local_identity(authority.profile_id, actor.subject, request_id)
  292. from gateway.session_policy import bind_launch_key, restore_policy, launch_key
  293. if authority.db.get_session(sid) is not None:
  294. from hermes_state_local import local_receipt
  295. saved = local_receipt(authority.db, sid)
  296. original = restore_policy(saved['policy'])
  297. from hermes_state_local import same_create_retry
  298. if not same_create_retry(saved['policy'], policy.request_json, params):
  299. raise RuntimeStoreError('invalid_params', field='request_id',
  300. detail='a resumed request_id must carry the same frozen request')
  301. import hmac
  302. import json
  303. if 'model_requested' in json.loads(original.request_json):
  304. # An owner-resolved alias: its key came from the profile (a `.env` rotation is not a changed
  305. # request) and the client sent none, so one it sends now is a different request.
  306. if client_key is not None:
  307. raise RuntimeStoreError('admission_conflict')
  308. elif original.credential_ref is not None or params.get('api_key') is not None:
  309. key = launch_key(authority, original)
  310. if key is None or not hmac.compare_digest(key, params.get('api_key') or ''):
  311. raise RuntimeStoreError('admission_conflict')
  312. return restore_local_session(authority, sid)
  313. from gateway.session_policy import launch_skills
  314. if launch_skills(params) and skills_prompt is None:
  315. # `-s` is rendered off-loop by the RPC handler (render_launch_skills); a caller that
  316. # skipped it must not mint a session silently missing its preload.
  317. raise RuntimeStoreError('invalid_params', field='skills',
  318. detail='the caller must render -s skills before minting the session')
  319. policy = replace(policy, skills_prompt=skills_prompt)
  320. if warning := project_plugins_warning(policy):
  321. logger.warning('session %s: %s', sid, warning)
  322. client_request = {k: params[k] for k in ('client_env',) if k in params}
  323. policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets,
  324. owner_key=client_key is None, # an overlapping exact retry takes the held one
  325. client_request=client_request)
  326. from gateway.session_local_recovery import local_source
  327. source = local_source(authority, sid, actor.subject)
  328. route = authority.runner.session_store._generate_session_key(source)
  329. # Same clock as every other routing entry: the recovery sweeps compare against a
  330. # naive cutoff, and one aware entry aborts the whole iteration.
  331. now = _now()
  332. entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
  333. # Prefill is read now, at creation (main's CLI: at startup), and held only if this attempt commits.
  334. from gateway.session_worker_construct import stage_session_prefill
  335. staged = stage_session_prefill(authority, policy, {
  336. 'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
  337. 'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)})
  338. # Owner memory, never stored: an overlapping create's commit judges this request's own map by the
  339. # winner's committed rules, as a sequential retry is.
  340. staged.client_request = client_request
  341. return staged
  342. def publish_local_policy(authority, session_id, *, evict=True):
  343. from hermes_state_local import local_receipt
  344. from gateway.session_policy import restore_policy
  345. live = authority.sessions[session_id]
  346. from gateway.session_local_recovery import local_adapter_map
  347. adapter = local_adapter_map(authority)[Platform.LOCAL]
  348. adapter.policies[live.source.chat_id] = restore_policy(local_receipt(authority.db, session_id)['policy'])
  349. if evict:
  350. authority.runner._evict_cached_agent(live.route)
  351. def _lazy_model(authority, policy):
  352. """The model a not-yet-built session will run: with no provider pinned, the free tier's agent
  353. build pins ``nous/welcome`` (``pin_model_for_route``), so the configured default is not it."""
  354. import json
  355. model = policy.current_model(authority) if policy else None
  356. if (policy is None or json.loads(policy.request_json).get('model')
  357. or str(policy.provider or '').strip().lower() not in {'', 'auto'}):
  358. return model
  359. from gateway.session_authorities import owner_scope
  360. from hermes_cli.anon_auth import GUEST_MODEL, free_tier_route
  361. with owner_scope(authority):
  362. return GUEST_MODEL if free_tier_route() else model
  363. def _reasoning_fields(agent, policy, model, authority=None, override=None):
  364. """Main's session-info effort/tier fields, from the built agent or (lazy) what the policy's next turn
  365. resolves (a following session's current profile): a resumed Desktop slice holds its reasoning pill
  366. pending until ``reasoning_effort`` arrives."""
  367. from agent.fast_mode import parse_service_tier
  368. from agent.voice_turn_route import session_runtime_view
  369. if agent is None and policy is None:
  370. return {}
  371. view = session_runtime_view(agent) if agent is not None else None
  372. if view is None:
  373. from hermes_constants import resolve_reasoning_config
  374. effective, next_model = policy.effective(authority, secrets=False)
  375. route = effective.get('model') or {}
  376. config = (getattr(view, 'reasoning_config', None) if view is not None
  377. else override if override is not None else resolve_reasoning_config(effective, next_model or ''))
  378. tier = (getattr(view, 'service_tier', None) if view is not None
  379. else parse_service_tier((effective.get('agent') or {}).get('service_tier'))) or ''
  380. provider = getattr(view, 'provider', None) if view is not None else route.get('provider')
  381. base_url = getattr(view, 'base_url', None) if view is not None else route.get('base_url')
  382. return effort_fields(config, tier, model, provider, base_url, getattr(view, 'api_mode', None))
  383. def effort_fields(config, tier, model, provider, base_url, api_mode=None):
  384. """Session-info ``reasoning_effort`` / ``_wire`` / ``service_tier`` / ``fast`` for one resolved route."""
  385. from agent.fast_mode import STATIC_TIERS
  386. from agent.reasoning_effort import clamp_effort, route_supported_efforts
  387. from hermes_cli.models import resolve_fast_mode_overrides
  388. tier = tier or ''
  389. effort = ''
  390. if isinstance(config, dict):
  391. effort = 'none' if config.get('enabled') is False else str(config.get('effort') or '')
  392. wire = ''
  393. if effort and effort != 'none':
  394. wire = str(clamp_effort(effort, route_supported_efforts(provider, model, api_mode)) or '')
  395. try:
  396. fast = tier in STATIC_TIERS and resolve_fast_mode_overrides(
  397. model, provider=provider or None, base_url=base_url or None, tier=tier) is not None
  398. except Exception: # health: allow BLE001 -- main's _fast_tier_applies gate: unknown means not Fast
  399. fast = False
  400. return {'reasoning_effort': effort, 'reasoning_effort_wire': wire, 'service_tier': tier, 'fast': fast}
  401. def local_session_info(authority, ref):
  402. live = authority.sessions[ref.session_id]
  403. agent = authority.agent(ref)
  404. from gateway.session_authorities import served_profile_name
  405. from gateway.session_policy import policy_for_source
  406. policy = policy_for_source(authority.runner, live.source)
  407. if live.source is None: # a history mount: what its stored row says
  408. source = authority.db.get_session(ref.session_id)['source']
  409. else:
  410. source = policy.source if policy else live.source.platform.value
  411. info = {'source': source,
  412. 'model': (getattr(agent, 'model', policy.current_model(authority) if policy else None) if agent is not None
  413. else _lazy_model(authority, policy)),
  414. 'lazy': agent is None,
  415. 'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
  416. # Main's TUI labels a named profile's composer (``alpha ❯``) from this field.
  417. 'profile_name': served_profile_name(authority.profile_id),
  418. **({'cwd': policy.cwd} if policy else {}),
  419. # An ACP session's edit approval policy: every attached surface reads the same one.
  420. **({'edit_approval_policy': policy.edit_approval_policy} if policy and policy.source == 'acp' else {})}
  421. peek = getattr(authority.runner, '_peek_session_state', None)
  422. state = peek(live.route) if peek is not None else None
  423. override = state.conversation.reasoning_override if state is not None else None # a typed /reasoning
  424. if agent is None and policy is None and live.source is not None and live.source.platform != Platform.LOCAL:
  425. # A messaging chat not built yet: what its next turn resolves (its /model and /reasoning picks
  426. # included), so a viewer's model and reasoning pill never wait on a field that never comes.
  427. from gateway.session_messaging_picks import messaging_route_info
  428. info.update(messaging_route_info(authority.runner, live))
  429. else:
  430. info.update(_reasoning_fields(agent, policy, info['model'], authority, override))
  431. if policy:
  432. # The creation request the route was frozen with (secrets already extracted), so a
  433. # resuming client can tell "same flags again" from a real override attempt.
  434. import json
  435. info['launch_request'] = json.loads(policy.request_json)
  436. from agent.session_client_env import NOT_LOCAL_WARNING
  437. # Session-start notices main's TUI already renders as ``config_warning``.
  438. notices = (project_plugins_warning(policy), NOT_LOCAL_WARNING if policy.client_env_remote else None)
  439. if warning := ' '.join(filter(None, notices)):
  440. info['config_warning'] = warning
  441. info.update(_classic_cli_fields(authority, ref, live, agent, policy))
  442. return info
  443. def _classic_cli_fields(authority, ref, live, agent, policy):
  444. """What main's HermesCLI read off itself for /status, the status bar and the exit summary: the
  445. stored title and times, the session's yolo, api_mode, the loaded tool count and a masked
  446. credential hint (never the key). Lazy sessions report what is known without building an agent."""
  447. import contextlib
  448. stored_id = ref.session_id
  449. with contextlib.suppress(Exception):
  450. from hermes_state_local import local_receipt
  451. stored_id = local_receipt(authority.db, ref.session_id)['entry']['session_id'] or stored_id
  452. row = {}
  453. with contextlib.suppress(Exception):
  454. row = authority.db.get_session(stored_id) or {}
  455. yolo = bool(policy is not None and getattr(policy, 'yolo', False))
  456. with contextlib.suppress(Exception):
  457. from tools.approval import is_session_yolo_enabled
  458. yolo = yolo or is_session_yolo_enabled(live.route)
  459. api_mode = getattr(agent, 'api_mode', None) if agent is not None else None
  460. if api_mode is None and policy is not None:
  461. with contextlib.suppress(Exception):
  462. api_mode = (policy.effective(authority, secrets=False)[0].get('model') or {}).get('api_mode')
  463. hint = None
  464. if agent is not None and getattr(agent, 'api_key', None):
  465. from agent.redact import mask_secret
  466. hint = mask_secret(str(agent.api_key))
  467. tools = getattr(agent, 'tools', None) if agent is not None else None
  468. started = row.get('started_at')
  469. return {'title': row.get('title'), 'started_at': started,
  470. 'last_active_at': row.get('last_activity_at') or started, 'yolo': yolo,
  471. 'api_mode': api_mode or None, 'tool_count': len(tools) if isinstance(tools, list) else None,
  472. 'credential_hint': hint}