session_policy.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. """Frozen, explicit local-client launch policy for the existing TurnRunner."""
  2. from contextlib import contextmanager
  3. from contextvars import ContextVar
  4. from dataclasses import dataclass
  5. from functools import cached_property
  6. import contextlib
  7. import json
  8. import logging
  9. from pathlib import Path
  10. from hermes_state_runtime import RuntimeStoreError
  11. logger = logging.getLogger(__name__)
  12. CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',
  13. 'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor',
  14. 'yolo', 'safe_mode', 'ignore_user_config',
  15. 'skills', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config',
  16. 'service_tier', 'cwd_explicit', 'run_budget', 'verbose', 'row_cwd', 'client_env'})
  17. # Sections a ``follow_profile_config`` session re-reads from the owning profile's CURRENT config each
  18. # turn (main's Bot Chat row), credentials included: a frozen key never crosses a profile route change.
  19. FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases',
  20. 'platform_toolsets')
  21. # A Bot Chat an earlier build committed frozen follows its profile once a client opens it (``follow_bot_chat``).
  22. # The marker sits in the policy's own config, so no other receipt changes shape (an older owner restores
  23. # them all, and reads this chat as frozen), and the creation request, the exact-retry identity, stays as sent.
  24. # A chat created on the welcome trial's model carries it too (``stage_local_session``), so a provider the user
  25. # connects later replaces that model.
  26. FOLLOW_ADOPTED = 'follow_adopted'
  27. # A Desktop chat its creator's connection declared local (``process_identity.local_desktop_client``): its
  28. # turns run as work for the local Desktop (``local_desktop_turn``). Owner-set in the policy's own config, so
  29. # an exact create retry from a socket whose declaration has not landed carries the same creation request,
  30. # and ``launch_request`` never echoes it.
  31. LOCAL_DESKTOP_CHAT = 'desktop_local'
  32. # A launch field's state as a committed session edit left it, in the policy's own config: ``True`` the
  33. # session chose it (``/reasoning <level>``, a model pick carrying one), ``False`` a reset gave it back to
  34. # the profile. Either wins over the creation request (the launch identity, never rewritten) and the older
  35. # pick receipts.
  36. SESSION_PINS = 'session_pins'
  37. def session_pinned(config, field, launched):
  38. """Whether *field* is the session's own choice: its last committed session edit, else *launched*."""
  39. pins = config.get(SESSION_PINS)
  40. return pins[field] if isinstance(pins, dict) and isinstance(pins.get(field), bool) else launched
  41. def pin_reasoning_effort(config, effort, *, session=False):
  42. """Write an explicit session reasoning level into *config*: it wins over a per-model default
  43. (``reasoning_overrides``), at creation, on ``/reasoning`` and on a model pick that carries one.
  44. A *session* edit also records the pin."""
  45. config.setdefault('agent', {})['reasoning_effort'] = effort
  46. config['agent'].pop('reasoning_overrides', None)
  47. if session:
  48. config[SESSION_PINS] = {**(config.get(SESSION_PINS) or {}), 'reasoning': True}
  49. def profile_config(authority):
  50. """The owning profile's current ``config.yaml`` (its present sections), read fresh."""
  51. from gateway.run import _load_gateway_config
  52. return present_sections(_load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml'))
  53. def unpin_reasoning(config, profile):
  54. """``/reasoning reset``: the level is *profile*'s (its current config) again, re-read every turn by a
  55. following session and on each resume by any other; a create-time ``reasoning`` included."""
  56. from gateway.session_policy_refresh import _follow
  57. followed = profile.get('agent') if isinstance(profile.get('agent'), dict) else {}
  58. agent = config.setdefault('agent', {})
  59. for key in ('reasoning_effort', 'reasoning_overrides'):
  60. _follow(agent, followed, key)
  61. config[SESSION_PINS] = {**(config.get(SESSION_PINS) or {}), 'reasoning': False}
  62. FOLLOW_AGENT_KEYS = ('reasoning_effort', 'reasoning_overrides', 'service_tier', 'disabled_toolsets', 'coding_context')
  63. # What a pick (create-time ``model`` / committed ``/model``) owns of the ``model:`` block.
  64. SELECTION_KEYS = ('default', 'provider', 'base_url', 'api_mode', 'selection_profile', 'api_key_from', 'key_env',
  65. 'api_key_env')
  66. BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')
  67. _ACTIVE_POLICY: ContextVar = ContextVar('local_session_policy', default=None)
  68. _TURN_PROFILE: ContextVar = ContextVar('follow_profile_read', default=None) # (policy, live) for a turn
  69. # Creation label -> agent surface. ``tool`` (third-party integrations, ``hermes chat --source tool``) and
  70. # ``oneshot`` (finite ``chat -q`` / ``-z`` runs) run as the CLI but keep their own stored label, so human
  71. # pickers hide them (INTERNAL_LISTING_SOURCES).
  72. SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp', 'tool': 'cli', 'oneshot': 'cli'}
  73. # ``tool`` and ``oneshot`` stay stored under their own labels so pickers can hide them.
  74. # Creation labels of the owner's own chats: the only LOCAL routes that carry OpenAI Daybreak (agent.daybreak),
  75. # the approved account's own access (no third-party or downstream use). Not ``tool`` (third-party
  76. # integrations), ``acp`` (editor clients), or the ``bot_room`` / ``a2a`` policies hosted rooms and peers stage.
  77. DAYBREAK_LABELS = frozenset({'cli', 'tui', 'gui', 'oneshot'})
  78. # Every other creation label is rewritten to ``source='local'`` on peer refresh.
  79. _KEEP_STORED_LABEL = frozenset({'tool', 'oneshot'})
  80. STORED_AS_LOCAL = frozenset(SURFACES) - _KEEP_STORED_LABEL
  81. # Routing labels and the accounting placeholder: never a creating surface.
  82. _NOT_A_SURFACE = frozenset({None, '', 'local', 'unknown'})
  83. def created_surface(label):
  84. """``created_source`` for a policy or live label.
  85. ``local`` and ``unknown`` are not surfaces. A label stored as ``local`` maps
  86. through ``SURFACES`` (``gui`` is ``desktop``). Any other label, including
  87. ``tool`` and ``oneshot``, is kept as itself: created_source is provenance.
  88. """
  89. if label in _NOT_A_SURFACE:
  90. return None
  91. return SURFACES[label] if label in STORED_AS_LOCAL else label
  92. # Policy label and agent surface for one conversation, keyed by either name: ``--source gui``
  93. # and ``--source desktop`` are the same rows. ``tool`` and ``oneshot`` are not aliases of
  94. # ``cli`` here: they keep their own stored label.
  95. SURFACE_GROUPS = {name: group for group in (frozenset({label, SURFACES[label]}) for label in STORED_AS_LOCAL)
  96. for name in group}
  97. def _refuse(field, detail=None):
  98. """One named refusal: the launch field the check read, and why it failed.
  99. ``reason`` stays the bounded wire code every caller compares as a string; ``field`` and
  100. ``detail`` are what tells ~20 different create checks apart, in the client and in the
  101. gateway log, without a second run to find out which one fired (``RuntimeStoreError`` bounds
  102. and flattens both)."""
  103. raise RuntimeStoreError('invalid_params', field=field, detail=detail)
  104. # ``acp_adapter/edit_approval.py``'s AUTO_APPROVE_* values, in main's ACP mode order.
  105. EDIT_APPROVAL_POLICIES = ('ask', 'workspace_session', 'session')
  106. @dataclass(frozen=True)
  107. class LocalSessionPolicy:
  108. source: str
  109. platform: str
  110. cwd: str
  111. model: str | None
  112. toolsets: tuple[str, ...]
  113. config_json: str
  114. request_json: str
  115. terminal_json: str
  116. credential_ref: str | None = None
  117. config_secret_ref: str | None = None
  118. editor_mcp_json: str | None = None
  119. kanban_json: str | None = None
  120. # Troubleshooting isolation is derived by the owner at creation and frozen with the
  121. # route; safe_mode always implies ignore_user_config (normalized once in build_policy).
  122. safe_mode: bool = False
  123. ignore_user_config: bool = False
  124. # `-s/--skills` blocks rendered once at creation (render_launch_skills): the session's
  125. # ephemeral prompt never re-reads the skill files, like the CLI's startup preload.
  126. skills_prompt: str | None = None
  127. # Whether creation chose the coding posture (``agent.coding_context: focus`` in a client-named code
  128. # workspace). A following session replays this decision rather than re-probing its folder each turn: it
  129. # drops the posture when its profile leaves ``focus``, and one created outside it never gains it later.
  130. coding_posture: bool = False
  131. # The shell-launched client's allowlisted environment (``agent.session_client_env``), bound for this
  132. # session's turns only; None when the client sent none (Desktop, a session from before the field).
  133. client_env_json: str | None = None
  134. # The client sent one over an attach the gateway could not prove is on its host (no gateway-minted
  135. # ticket): only host-free values were kept, and its tools run with the gateway's own toolchain.
  136. client_env_remote: bool = False
  137. # The rules that map was normalised by (``client_env_rules``: allowlist, secret filter, locality) as
  138. # plain data: an exact retry is judged by them, never by the profile's current ones, and the session's
  139. # tools run without every toolchain name they cover that the client did not send.
  140. client_env_rules_json: str | None = None
  141. # An ACP session's edit approval (``session.mutate edit_policy``; main's ACP modes): ``ask`` (Default),
  142. # ``workspace_session`` (Accept Edits) or ``session`` (Don't Ask). Sensitive paths always ask.
  143. edit_approval_policy: str = 'ask'
  144. def client_env(self):
  145. return None if self.client_env_json is None else json.loads(self.client_env_json)
  146. def client_env_scope(self):
  147. from agent.session_client_env import client_env_scope
  148. rules = None if self.client_env_rules_json is None else json.loads(self.client_env_rules_json)
  149. return client_env_scope(self.client_env(), local=not self.client_env_remote, rules=rules)
  150. def config(self, authority=None, *, secrets=True):
  151. return self.effective(authority, secrets=secrets)[0]
  152. def effective(self, authority=None, *, secrets=True):
  153. """``(config, model)`` the next turn runs, both from ONE read of the owning profile when following
  154. (the turn's policy scope holds that read): a route never pairs one profile's model with another's
  155. endpoint. Explicit choices (create-time reasoning / tier / toolsets, a session ``/reasoning`` until
  156. reset, a pick that still holds) are applied over the followed defaults; frozen secrets of followed
  157. sections are never recovered."""
  158. config = present_sections(json.loads(self.config_json))
  159. live = self.read_profile(authority)
  160. if self.config_secret_ref is not None and authority is not None and secrets:
  161. from gateway.session_policy_credentials import disable_dropped_secrets, recover_config_secrets
  162. recovered = recover_config_secrets(authority, self)
  163. for path, value in recovered.items():
  164. if path[0] is None: # private terminal projection, not config
  165. continue
  166. target = config
  167. for key in path[:-1]:
  168. # An alias entry added after creation is absent from the frozen tree.
  169. target = target.setdefault(key, {}) if isinstance(target, dict) else target[key]
  170. target[path[-1]] = value
  171. disable_dropped_secrets(config, getattr(recovered, 'dropped', ()), getattr(recovered, 'session', None))
  172. model = self.model
  173. if live:
  174. frozen, request = config.get('model') or {}, json.loads(self.request_json)
  175. pick = frozen.get('selection_profile')
  176. held = pick is not None and pick == list(profile_target(live)) and entry_serves(frozen, live)
  177. pinned = {'platform_toolsets', 'disabled_toolsets'} if 'toolsets' in request else set()
  178. chosen = session_pinned(config, 'reasoning', 'reasoning' in request)
  179. pinned |= {'reasoning_effort', 'reasoning_overrides'} if chosen else set()
  180. pinned |= {'service_tier'} if 'service_tier' in request else set()
  181. for key in FOLLOW_SECTIONS:
  182. if key in pinned:
  183. continue
  184. if key in live:
  185. config[key] = live[key]
  186. else:
  187. config.pop(key, None)
  188. if held:
  189. config['model'] = _held_pick(frozen, config.get('model') or {})
  190. else:
  191. from gateway.run import _resolve_gateway_model
  192. model = _resolve_gateway_model(live) or self.model
  193. agent, live_agent = config.setdefault('agent', {}), live.get('agent') or {}
  194. for key in FOLLOW_AGENT_KEYS:
  195. if key in pinned:
  196. continue
  197. if key in live_agent:
  198. agent[key] = live_agent[key]
  199. else:
  200. agent.pop(key, None)
  201. source = (config.get('model') or {}).get('api_key_from') if isinstance(config.get('model'), dict) else None
  202. if source:
  203. # ``/model <alias>`` with a literal key: the receipt points at the alias entry's secret.
  204. value = config
  205. for part in source:
  206. value = value.get(part) if isinstance(value, dict) else None
  207. config['model']['api_key'] = value
  208. return config, model
  209. @cached_property
  210. def follows_profile(self):
  211. # Read ~8-10 times a turn on the event loop, and a frozen policy's config is a whole profile:
  212. # parse once per (immutable) policy; ``replace()`` builds a fresh instance with its own cache.
  213. return (json.loads(self.request_json).get('follow_profile_config') is True
  214. or json.loads(self.config_json).get(FOLLOW_ADOPTED) is True)
  215. def read_profile(self, authority):
  216. """The owning profile's current config for a following session, else None; inside this policy's
  217. turn scope, the turn's one read."""
  218. if authority is None or not self.follows_profile:
  219. return None
  220. held = _TURN_PROFILE.get()
  221. if held is not None and held[0] == self:
  222. return held[1]
  223. return profile_config(authority)
  224. def current_toolsets(self, config):
  225. """The next turn's toolsets from its resolved *config*: a following session without an explicit
  226. toolset pick runs the profile's current selection (main #124211), else the frozen launch set."""
  227. if (not self.follows_profile or self.source not in SURFACES or self.editor_mcp_json is not None
  228. or 'toolsets' in json.loads(self.request_json)):
  229. return self.toolsets
  230. # The workspace decision is the creation-time one: a project file the agent writes mid-session must
  231. # not switch this conversation's toolsets (prompt cache). Only a profile change (``focus`` off) does.
  232. return tuple(sorted(_resolve_toolsets({}, config, self.source, self.safe_mode, self.coding_posture)))
  233. def current_reasoning_config(self, runner, session_key=None):
  234. """The next turn's reasoning: a typed session /reasoning (the messaging handler's override), else
  235. the profile's current effort when following, else the frozen one."""
  236. peek = getattr(runner, '_peek_session_state', None)
  237. state = peek(session_key) if session_key and peek is not None else None
  238. if state is not None and state.conversation.reasoning_override is not None:
  239. return dict(state.conversation.reasoning_override)
  240. if not self.follows_profile:
  241. return self.reasoning_config
  242. from gateway.session_authorities import active_authority
  243. from hermes_constants import resolve_reasoning_config
  244. config, model = self.effective(active_authority(runner), secrets=False)
  245. return resolve_reasoning_config(config, model or '')
  246. def current_service_tier(self, runner, session_key):
  247. """The next turn's tier: a typed session /fast, else the policy's (frozen, or the profile's when following)."""
  248. from agent.fast_mode import parse_service_tier
  249. from gateway.session_authorities import active_authority
  250. from gateway.session_state import SERVICE_TIER_UNSET
  251. state = runner._peek_session_state(session_key) if session_key else None
  252. if state is not None and state.conversation.service_tier_override is not SERVICE_TIER_UNSET:
  253. return state.conversation.service_tier_override
  254. config = self.config(active_authority(runner), secrets=False)
  255. return parse_service_tier((config.get('agent') or {}).get('service_tier'))
  256. def current_model(self, authority):
  257. """The model this session's next turn runs: the profile's current default when following."""
  258. return self.effective(authority, secrets=False)[1]
  259. @property
  260. def provider(self):
  261. return self.config().get('model', {}).get('provider')
  262. @property
  263. def base_url(self):
  264. return self.config().get('model', {}).get('base_url')
  265. @property
  266. def ignore_rules(self):
  267. return self.safe_mode or json.loads(self.request_json).get('ignore_rules', False)
  268. @property
  269. def yolo(self):
  270. """`hermes chat --yolo`: this session's dangerous-command approvals are bypassed, exactly the
  271. scope `/yolo` gives a messaging chat; never the process-wide HERMES_YOLO_MODE."""
  272. return json.loads(self.request_json).get('yolo', False)
  273. @property
  274. def pass_session_id(self):
  275. """`--pass-session-id`: the session id rides the agent's system prompt."""
  276. return json.loads(self.request_json).get('pass_session_id', False)
  277. @property
  278. def checkpoints_enabled(self):
  279. """Frozen `checkpoints.enabled` (`--checkpoints` folds into it); legacy bool form accepted."""
  280. section = self.config().get('checkpoints', {})
  281. return bool(section.get('enabled', False) if isinstance(section, dict) else section)
  282. @property
  283. def max_turns(self):
  284. from hermes_cli.config import resolve_turn_limit
  285. cfg = self.config()
  286. return resolve_turn_limit(cfg.get('agent', {}).get('max_turns', cfg.get('max_turns')))
  287. @property
  288. def verbose(self):
  289. """`hermes chat -v`: the session's agent runs with quiet_mode off, so its status lines reach the
  290. viewer (``agent.print``) as main's in-process verbose agent printed them."""
  291. return json.loads(self.request_json).get('verbose', False)
  292. @property
  293. def run_budget_seconds(self):
  294. """Frozen `agent.run_budget_seconds` (`--run-budget` folds into it); None = no budget."""
  295. from agent.agent_init import _normalize_run_budget_seconds
  296. return _normalize_run_budget_seconds(self.config().get('agent', {}).get('run_budget_seconds'))
  297. @property
  298. def reasoning_config(self):
  299. from hermes_constants import resolve_reasoning_config
  300. return resolve_reasoning_config(self.config(), self.model or '')
  301. def profile_target(config):
  302. """(model, provider) a profile config selects; 'auto' is no provider (main's _config_model_target)."""
  303. model = config.get('model')
  304. if isinstance(model, dict):
  305. provider = str(model.get('provider') or '').strip()
  306. return str(model.get('default') or '').strip(), '' if provider.lower() == 'auto' else provider
  307. return (model.strip() if isinstance(model, str) else ''), ''
  308. def model_route(block):
  309. """``(provider, endpoint)`` identity of a ``model:`` block: what an endpoint-bound credential belongs to."""
  310. from hermes_cli.route_identity import normalize_route_base_url
  311. block = block if isinstance(block, dict) else {}
  312. return str(block.get('provider') or '').strip().lower(), normalize_route_base_url(block.get('base_url'))
  313. def bound_route_holds(bound, bound_config, block, config):
  314. """True when *block* (resolved in *config*) is the route *bound* was bound to, *bound* resolved in
  315. the config it was bound in: a respelled provider on one endpoint is one route, and a named entry
  316. whose ``base_url`` moved is another. An ``auto``/unset side keeps the literal comparison: a
  317. credential never follows a route the resolver picks later."""
  318. from gateway.session_route_identity import resolved_route, same_route
  319. bound = bound if isinstance(bound, dict) else {}
  320. identity, url = resolved_route(bound, bound_config)
  321. if 'auto' in (identity, resolved_route(block, config)[0]):
  322. return model_route(bound) == model_route(block)
  323. return same_route({**bound, 'base_url': url} if url else bound, block, config)
  324. def entry_serves(block, config):
  325. """False when *block* pins a ``base_url`` that the config entry its credential comes from no longer
  326. serves in *config*: its named provider (``providers:`` / ``custom_providers:``), or the alias its
  327. ``api_key_from`` points into. That entry's key (inline, ``key_env``, ``key_cmd``) authenticates the
  328. entry's own endpoint, so a pick held on the old one ends rather than carry the new key there."""
  329. from hermes_cli.route_identity import normalize_route_base_url
  330. block = block if isinstance(block, dict) else {}
  331. url = normalize_route_base_url(block.get('base_url'))
  332. if not url:
  333. return True
  334. from gateway.session_route_identity import _named_entry
  335. provider = str(block.get('provider') or '').strip()
  336. entries = [_named_entry(provider, config)] if provider else []
  337. source = block.get('api_key_from')
  338. if isinstance(source, list) and len(source) > 1:
  339. alias = config
  340. for part in source[:-1]:
  341. alias = alias.get(part) if isinstance(alias, dict) else None
  342. entries.append(alias)
  343. return all(normalize_route_base_url(entry.get('base_url')) == url for entry in entries
  344. if isinstance(entry, dict) and str(entry.get('base_url') or '').strip())
  345. def _held_pick(frozen, live):
  346. """A pick that still holds keeps its selection; on the profile's own endpoint the rest of the
  347. ``model:`` block (a rotated key included) is the profile's. Another endpoint never gets it."""
  348. if model_route(frozen) != model_route(live):
  349. return frozen
  350. return {**{k: v for k, v in live.items() if k not in SELECTION_KEYS},
  351. **{k: frozen[k] for k in SELECTION_KEYS if k in frozen}}
  352. def present_sections(config):
  353. """A bare ``gateway:`` key parses as YAML null; like load_config's merge (#58277), treat it as absent so
  354. ``cfg.get('gateway', {}).get(...)`` reads the default instead of crashing a fresh install's first turn."""
  355. config = {key: value for key, value in config.items() if value is not None}
  356. # A scalar ``model: <id>`` (a form every classic loader accepts) is the mapping's ``default``.
  357. if isinstance(config.get('model'), str):
  358. config['model'] = {'default': config['model']} if config['model'].strip() else {}
  359. return config
  360. def build_policy(params, config, *, private_secrets=None, profile_terminal=True, workspace_posture=False,
  361. client_local=False):
  362. from agent.runtime_cwd import resolve_agent_cwd
  363. from tools.terminal_scope import build_profile_terminal_scope, default_terminal_scope
  364. from hermes_constants import get_hermes_home
  365. source = params.get('source', 'cli')
  366. if source == 'a2a':
  367. from gateway.session_a2a import build_forward_policy
  368. return build_forward_policy(params, config, private_secrets=private_secrets)
  369. unknown = sorted(set(params) - CREATE_FIELDS)
  370. if unknown or not isinstance(source, str) or source not in SURFACES:
  371. _refuse(f'params.{unknown[0]}' if unknown else 'source',
  372. 'unknown create field' if unknown else f'not a surface: {source!r}')
  373. bad_bypass = next((name for name in BYPASS_FIELDS if name in params and type(params[name]) is not bool), None)
  374. if bad_bypass:
  375. _refuse(bad_bypass, 'must be a boolean')
  376. safe_mode = params.get('safe_mode', False)
  377. ignore_user_config = safe_mode or params.get('ignore_user_config', False)
  378. if 'api_key' in params and (not isinstance(params['api_key'], str) or not params['api_key'].strip()):
  379. _refuse('api_key', 'must be a non-empty string')
  380. model = params.get('model')
  381. if 'model' in params and (not isinstance(model, str) or not model.strip()):
  382. _refuse('model', 'must be a non-empty string')
  383. cwd = params.get('cwd', str(resolve_agent_cwd()))
  384. if not isinstance(cwd, str) or not Path(cwd).is_absolute() or not Path(cwd).is_dir():
  385. _refuse('cwd', 'must be an absolute path to an existing directory')
  386. row_cwd = params.get('row_cwd')
  387. if 'row_cwd' in params and (not isinstance(row_cwd, str) or (row_cwd and not Path(row_cwd).is_absolute())):
  388. _refuse('row_cwd', 'must be an absolute path when set')
  389. if params.get('cwd_explicit') is False and 'cwd' in params:
  390. cwd = _profile_workspace_cwd(get_hermes_home()) or cwd
  391. from gateway.session_local_editor import validate_editor
  392. validate_editor(source, params.get('editor'))
  393. launch_skills(params)
  394. config = present_sections(json.loads(json.dumps(config)))
  395. picked_route = {'model', 'provider', 'base_url'} & set(_without_auto_pick(params))
  396. if params.get('follow_profile_config') is True and picked_route:
  397. # Any explicit route pick (a model, a provider, an endpoint) records its provenance before the
  398. # launch route folds in: it holds while the profile still targets this, and a later profile edit
  399. # supersedes it. Without it the first turn's followed route replaces the pick.
  400. config.setdefault('model', {})['selection_profile'] = list(profile_target(config))
  401. _apply_launch_overrides(params, config)
  402. # The posture is opt-in (``session.create`` only) and needs a folder the client named: the daemon's own
  403. # directory (the fallback above) is no workspace, and ``tool`` is a third-party integration. An explicit
  404. # pick wins anyway; skipping it here also spares the probe.
  405. named = workspace_posture and source != 'tool' and 'cwd' in params and 'toolsets' not in params
  406. coding_posture = named and _in_coding_workspace(config, source, cwd)
  407. enabled = _resolve_toolsets(params, config, source, safe_mode, coding_posture, bypass=ignore_user_config)
  408. terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()
  409. # The client's launch folder is a path on THIS host: a remote or container backend keeps its own
  410. # configured cwd unless the user picked this folder for the session.
  411. if params.get('cwd_explicit') is True or terminal_uses_host_cwd(terminal):
  412. terminal['TERMINAL_CWD'] = cwd
  413. client_env = rules = None
  414. if 'client_env' in params:
  415. from agent.session_client_env import client_env_rules, normalise_client_env
  416. rules = client_env_rules(config, local=client_local)
  417. try:
  418. client_env = json.dumps(normalise_client_env(params['client_env'], rules), sort_keys=True)
  419. except ValueError as exc:
  420. _refuse('client_env', str(exc))
  421. rules = json.dumps(rules, sort_keys=True)
  422. # Values stay out of the request: ``launch_request`` is echoed to every viewer of the session.
  423. request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key', 'client_env'}}
  424. request.setdefault('source', 'cli')
  425. from gateway.session_local_mcp import private_editor_request
  426. private_editor_request(request, private_secrets)
  427. _extract_config_secrets(config, private_secrets)
  428. _extract_config_secrets(terminal, private_secrets, (None,))
  429. return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),
  430. json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),
  431. safe_mode=safe_mode, ignore_user_config=ignore_user_config,
  432. coding_posture=coding_posture, client_env_json=client_env,
  433. client_env_remote=client_env is not None and not client_local,
  434. client_env_rules_json=rules)
  435. def terminal_uses_host_cwd(terminal):
  436. """Whether the terminal works in the session's host cwd: the local backend, or docker mounting it at
  437. ``/workspace``. ssh, modal and the other sandboxes resolve their own cwd."""
  438. backend = str(terminal.get('TERMINAL_ENV') or 'local').strip().lower()
  439. mounts = str(terminal.get('TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE') or '').strip().lower() in {'1', 'true', 'yes', 'on'}
  440. return backend == 'local' or (backend == 'docker' and mounts)
  441. def _profile_workspace_cwd(home):
  442. """A NAMED profile's configured ``terminal.cwd``, which beats a client cwd the Desktop only inherited
  443. (``cwd_explicit: false``; main's ``_completion_cwd``). Placeholders and missing dirs are unset."""
  444. import os
  445. from hermes_constants import profile_name_for_home
  446. if profile_name_for_home(home) in {None, 'default'}:
  447. return None
  448. from hermes_cli.config import read_user_config_raw
  449. terminal = read_user_config_raw(Path(home) / 'config.yaml').get('terminal')
  450. raw = str((terminal if isinstance(terminal, dict) else {}).get('cwd') or '').strip()
  451. configured = os.path.abspath(os.path.expanduser(raw)) if raw not in {'', '.', 'auto', 'cwd'} else None
  452. return configured if configured and os.path.isdir(configured) else None
  453. def _without_auto_pick(params):
  454. """`provider: auto` is the thin client's "no pick" sentinel: the profile's route stands as configured."""
  455. if isinstance(params.get('provider'), str) and params['provider'].strip().lower() == 'auto':
  456. return {k: v for k, v in params.items() if k != 'provider'}
  457. return params
  458. def _keeps_profile_route(picked, config):
  459. """Whether a provider pick resolves to the profile's own route, so its endpoint and key pins stay.
  460. The same resolved provider under another spelling (`vllm` for `custom`, `deep-infra` for
  461. `deepinfra`, `custom:<name>` for a named entry) is the same route. A block with an endpoint
  462. and no provider (or `auto`) already routes to `custom` there.
  463. """
  464. from gateway.session_route_identity import profile_route_identity, resolved_route
  465. held_id = profile_route_identity(config)
  466. if held_id == 'auto' or not isinstance(picked, str) or not picked.strip():
  467. return False
  468. return resolved_route({'provider': picked}, config)[0] == held_id
  469. def _with_entry_pick(params, config):
  470. """*params* with a provider pick of the held entry's bare config key spelled as its ``custom:<key>``.
  471. A configured entry keyed like a canonical built-in (`providers: deepseek`) is shadowed by the
  472. built-in in raw provider resolution, so the bare spelling would route, and be frozen, as a
  473. different provider than the entry the profile runs (#140107). Only the held entry's bare key
  474. is that entry (Desktop's guard). A keyed entry's display name is not; a keyless legacy
  475. ``custom_providers:`` entry's is (``configured_entry_key``). A bare ``custom`` pick is the billing
  476. class a client echoed from the runtime, not a route: on a bare ``custom`` profile with an endpoint
  477. it is that profile's route unless it picks another endpoint, or another entry lists a model that
  478. is not the profile's default; otherwise it names the configured entry serving its endpoint/model
  479. (the profile's own first), else (no endpoint picked) the profile's own entry. A launch key for an
  480. entry the model alone chose is refused. Other picks stay as they came.
  481. """
  482. from gateway.session_route_identity import configured_entry_key, profile_route_identity
  483. picked = params.get('provider')
  484. if not isinstance(picked, str):
  485. return params
  486. identity = profile_route_identity(config)
  487. if picked.strip().lower() == 'custom':
  488. from hermes_cli.runtime_provider_custom import _route_key, routed_custom_identity
  489. url, model = params.get('base_url'), str(params.get('model') or '')
  490. own_url = _route_key(model_route(config.get('model'))[1])
  491. if identity == 'custom' and own_url and (
  492. _route_key(url) == own_url if url is not None
  493. else model.strip().lower() == profile_target(config)[0].lower()
  494. or not routed_custom_identity(None, model, config)):
  495. return params
  496. held = identity if identity.startswith('custom:') else None
  497. healed = routed_custom_identity(url, model, config, held=held) or (
  498. identity if identity.startswith('custom:') and url is None else None)
  499. if healed and healed != identity and url is None and 'api_key' in params:
  500. # The model alone chose this entry: a launch key the user gave is never sent to a host they did not name.
  501. _refuse('api_key', f'{healed} was chosen by model; name it with --provider or --base-url to use a launch key')
  502. return {**params, 'provider': healed} if healed else params
  503. if identity == 'auto' or picked.strip().lower() != (configured_entry_key(identity, config) or None):
  504. return params
  505. return {**params, 'provider': identity}
  506. def _apply_launch_overrides(params, config):
  507. """Validate the explicit model/agent launch overrides and fold them into *config*."""
  508. from urllib.parse import urlsplit
  509. from hermes_cli.config import resolve_turn_limit
  510. from hermes_constants import parse_reasoning_effort
  511. params = _with_entry_pick(_without_auto_pick(params), config)
  512. picks_profile_entry = 'provider' in params and _keeps_profile_route(params['provider'], config)
  513. if 'provider' in params and not picks_profile_entry:
  514. model = config.setdefault('model', {})
  515. # A provider pick is a route change: the profile's endpoint, wire protocol and
  516. # credential pointers belong to the provider being replaced, and pairing the new one
  517. # with them sends its key to the old host (401) or the old key down the new route.
  518. # They are dropped before the overrides fold in, so the target provider resolves its
  519. # own — the same route keys a committed /model switch rewrites (#138843). An explicit
  520. # base_url is applied after the drop, so a pinned endpoint survives without carrying
  521. # the replaced provider's other pins, and a same-provider re-pick keeps the profile's.
  522. from gateway.session_route_identity import ROUTE_BOUND_KEYS
  523. # The replaced provider's context window goes too: it was sized for the old model.
  524. for stale in ROUTE_BOUND_KEYS:
  525. model.pop(stale, None)
  526. for key in ('provider', 'base_url'):
  527. if key in params:
  528. value = params[key]
  529. if not isinstance(value, str) or not value.strip():
  530. _refuse(key, 'must be a non-empty string')
  531. if key == 'base_url':
  532. url = urlsplit(value)
  533. if (url.scheme not in {'http', 'https'} or not url.hostname
  534. or url.username or url.password or url.query or url.fragment):
  535. _refuse('base_url', 'must be an http(s) URL without credentials, query or fragment')
  536. config.setdefault('model', {})[key] = value
  537. bad_flag = next((flag for flag in ('ignore_rules', 'yolo', 'checkpoints', 'accept_hooks', 'pass_session_id',
  538. 'follow_profile_config', 'cwd_explicit', 'verbose')
  539. if flag in params and type(params[flag]) is not bool), None)
  540. if bad_flag:
  541. _refuse(bad_flag, 'must be a boolean')
  542. if 'service_tier' in params:
  543. # An explicit speed pick (Desktop Fast / Ultrafast / Normal): normal pins normal over a
  544. # profile tier; an unknown word is refused, never read as normal.
  545. from agent.fast_mode import parse_exact_service_tier
  546. try:
  547. tier = parse_exact_service_tier(params['service_tier']) if isinstance(params['service_tier'], str) else None
  548. except ValueError:
  549. tier = None
  550. if tier is None:
  551. _refuse('service_tier', f"not a known tier: {params['service_tier']!r}")
  552. config.setdefault('agent', {})['service_tier'] = tier or 'normal'
  553. if 'run_budget' in params:
  554. # `--run-budget SECONDS`: the wall-clock budget per run (80% wrap-up notice, capped provider
  555. # timeouts), frozen as the session's `agent.run_budget_seconds` like main's CLI flag over config.
  556. value = params['run_budget']
  557. if isinstance(value, bool) or not isinstance(value, (int, float)) or not value > 0:
  558. _refuse('run_budget', 'must be a positive number of seconds')
  559. config.setdefault('agent', {})['run_budget_seconds'] = float(value)
  560. if params.get('checkpoints'):
  561. section = config.get('checkpoints')
  562. section = dict(section) if isinstance(section, dict) else {'enabled': bool(section)} if section else {}
  563. config['checkpoints'] = {**section, 'enabled': True}
  564. if 'max_turns' in params:
  565. # The spellings `--max-turns` always took: a positive cap, or 0 / -1 / "none" / "unlimited"
  566. # for no cap (resolve_turn_limit). Frozen normalized; anything unreadable is refused.
  567. value = params['max_turns']
  568. limit = resolve_turn_limit(value, default=0) if isinstance(value, (int, str)) else 0
  569. if not limit:
  570. _refuse('max_turns', f'unreadable cap: {value!r}')
  571. config.setdefault('agent', {})['max_turns'] = limit
  572. if 'reasoning' in params:
  573. if not isinstance(params['reasoning'], str) or parse_reasoning_effort(params['reasoning']) is None:
  574. _refuse('reasoning', f"not a known effort level: {params['reasoning']!r}")
  575. pin_reasoning_effort(config, params['reasoning'])
  576. def _resolve_toolsets(params, config, source, safe_mode, coding_posture=False, bypass=False):
  577. """Validate explicit toolsets and return the session's enabled toolset set. Without a pick, a
  578. *coding_posture* session runs ``focus_toolsets`` instead of the profile default while the profile
  579. stays on ``focus``; the gateway decides it, never the client."""
  580. from hermes_cli.tools_config import _get_platform_tools, enabled_mcp_server_names
  581. from hermes_cli.toolset_validation import saved_toolset_resolver
  582. from toolsets import validate_toolset
  583. explicit = params.get('toolsets')
  584. if 'toolsets' in params:
  585. if not isinstance(explicit, list):
  586. _refuse('toolsets', f'must be a list of toolset names, got {type(explicit).__name__}')
  587. # The CLI validator's rule: a configured MCP server's toolset registers only after its first
  588. # connect, so an offline server is inactive, not a typo (#138748, #139154). A bypass launch never
  589. # reads the profile, so it takes the in-process registry alone.
  590. known = validate_toolset if bypass else saved_toolset_resolver(config)
  591. configured = config.get('mcp_servers') if isinstance(config.get('mcp_servers'), dict) else {}
  592. enabled_servers = enabled_mcp_server_names(config) if configured else set()
  593. for name in explicit:
  594. if not isinstance(name, str) or not known(name):
  595. _refuse('toolsets', f'unknown or invalid toolset name: {name!r}')
  596. server = name[4:] if name.startswith('mcp-') and name not in configured else name
  597. if server in configured and server not in enabled_servers:
  598. # Picking a disabled server must not match nothing and fall through to every enabled one.
  599. why = 'is disabled in config' if isinstance(configured[server], dict) else 'has no usable config entry'
  600. _refuse('toolsets', f'MCP server {server!r} {why}')
  601. if 'desktop_ui' in explicit and source != 'gui':
  602. _refuse('toolsets', f'desktop_ui is only available on the Desktop, not on {source}')
  603. config.setdefault('platform_toolsets', {})['acp' if source == 'acp' else 'cli'] = explicit
  604. posture = None
  605. if explicit is None and coding_posture:
  606. from agent.coding_context import focus_toolsets
  607. posture = focus_toolsets(config)
  608. enabled = set(posture) if posture is not None else _get_platform_tools(config, 'acp' if source == 'acp' else 'cli')
  609. if explicit is not None:
  610. from toolsets import resolve_toolset
  611. requested = {t for name in explicit for t in resolve_toolset(name)}
  612. effective = {t for name in enabled for t in resolve_toolset(name)}
  613. if not requested <= effective:
  614. _refuse('toolsets', f"not available on this surface: {', '.join(sorted(requested - effective))}")
  615. if explicit is None and source in {'tui', 'gui'}:
  616. # Same surface toolsets as the native TUI factory, without its env inference.
  617. # The fold-in lands after _get_platform_tools subtracted agent.disabled_toolsets, so
  618. # subtract again or `disabled_toolsets: [project]` is a no-op here (#54433).
  619. # desktop_ui is the client's own control surface, not a model toolset.
  620. from agent.skill_utils import parse_config_string_list
  621. from toolsets import CLIENT_SURFACE_TOOLSETS
  622. disabled = set(parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')))
  623. surface = set(CLIENT_SURFACE_TOOLSETS) if source == 'gui' else {'project'}
  624. enabled |= surface - (disabled - {'desktop_ui'})
  625. if safe_mode:
  626. # Plugin toolsets are user customizations; the safe worker never imports them.
  627. from hermes_cli.tools_config import _get_plugin_toolset_keys
  628. enabled -= _get_plugin_toolset_keys()
  629. return enabled
  630. def _in_coding_workspace(config, source, cwd):
  631. """Whether *cwd* selects the coding posture (``agent.coding_context: focus`` in a code workspace).
  632. A detection failure keeps the profile default rather than refusing the session."""
  633. from agent.coding_context import in_focus_workspace
  634. try:
  635. return in_focus_workspace(platform=SURFACES[source], cwd=cwd, config=config)
  636. except Exception:
  637. logger.debug('coding posture detection failed for %s; keeping the profile default', cwd, exc_info=True)
  638. return False
  639. def _extract_config_secrets(value, private, path=()):
  640. # Reuse the configuration owner's structural classification; opaque keys need
  641. # not match a vendor prefix. Only the authority keeps their original values.
  642. from hermes_cli.config import _SECRET_CONFIG_KEYS
  643. from agent.credential_persistence import _is_secret_payload_key
  644. containers = {'env', 'headers', 'extra_headers', 'docker_env', 'docker_extra_args',
  645. 'terminal_docker_env', 'terminal_docker_extra_args'}
  646. items = value.items() if isinstance(value, dict) else enumerate(value) if isinstance(value, list) else ()
  647. for key, child in items:
  648. child_path = path + (key,)
  649. sensitive = isinstance(key, str) and (key.lower() in _SECRET_CONFIG_KEYS
  650. or key.lower() in containers or _is_secret_payload_key(key))
  651. if sensitive and child and child not in ('{}', '[]'):
  652. if private is None:
  653. raise RuntimeStoreError('launch_credentials_unavailable')
  654. private[child_path] = child
  655. value[key] = None
  656. else:
  657. _extract_config_secrets(child, private, child_path)
  658. def launch_skills(params):
  659. """The validated `-s/--skills` identifiers of a create request (empty when absent). Skills
  660. live in the profile, which a bypass launch must never read: refused there, not dropped."""
  661. skills = params.get('skills', [])
  662. if 'skills' in params and (not isinstance(skills, list) or not skills
  663. or any(not isinstance(s, str) or not s.strip() for s in skills)):
  664. _refuse('skills', 'must be a non-empty list of skill names')
  665. if skills and any(params.get(name) is True for name in BYPASS_FIELDS):
  666. _refuse('skills', 'a bypass launch never reads the profile, so skills cannot be preloaded')
  667. return [s.strip() for s in skills]
  668. def render_launch_skills(params, session_id):
  669. """`-s/--skills` preload blocks for a new session, rendered ONCE at creation and frozen in its
  670. policy (the CLI's startup preload). Blocking skill-tree reads: callers run it off the owner
  671. loop. A typo among good names is logged and skipped, like the CLI; none resolving refuses."""
  672. skills = launch_skills(params)
  673. if not skills:
  674. return None
  675. from agent.skill_commands import build_preloaded_skills_prompt, format_missing_skills
  676. prompt, loaded, missing = build_preloaded_skills_prompt(skills, task_id=session_id)
  677. if not loaded:
  678. raise RuntimeStoreError('unknown_skill')
  679. if missing:
  680. import logging
  681. logging.getLogger(__name__).warning('Skipping %s for session %s; continuing with: %s',
  682. format_missing_skills(missing), session_id, ', '.join(loaded))
  683. return prompt or None
  684. def accept_launch_hooks(policy):
  685. """`--accept-hooks` / `HERMES_ACCEPT_HOOKS=1` on a launch: consent to the profile's configured
  686. shell hooks in the per-user allowlist (no prompt; kept in memory if that write fails), which
  687. the open's ``refresh_profile_hooks`` then registers. A bypass launch has no profile hooks to
  688. consent to, so the flag is a no-op there rather than a refusal. Allowlist I/O: off the loop."""
  689. if json.loads(policy.request_json).get('accept_hooks') and not policy.ignore_user_config:
  690. from agent.shell_hooks import accept_for_launch
  691. from gateway.run import _load_gateway_config
  692. accept_for_launch(_load_gateway_config())
  693. def refresh_profile_hooks(policy):
  694. """Bring this owner's shell hooks in step with the profile on every local session open
  695. (create and resume): hooks added to ``config.yaml`` or approved since the gateway started
  696. register, removed or revoked ones stop firing, as each new CLI process did on main. Reads the
  697. owner home's LIVE config (as session creation does), never the session's frozen copy: the
  698. registry is shared by every session and surface of this profile. Consent comes from the
  699. allowlist (the launching client's TTY prompt, or ``accept_launch_hooks``) or an opt-in in force
  700. on the gateway itself; this never prompts. A bypass launch registers nothing (main's safe mode
  701. registered none). Config read + allowlist I/O: run off the loop."""
  702. if policy is None or policy.ignore_user_config:
  703. return
  704. from agent.shell_hooks import sync_from_config
  705. from gateway.run import _load_gateway_config
  706. try:
  707. sync_from_config(_load_gateway_config) # it never removes on an empty (failed-open) config
  708. except Exception: # health: allow BLE001 -- best effort; a hook re-sync never blocks opening a session
  709. logger.warning("shell-hook re-sync failed; keeping the registered hooks", exc_info=True)
  710. def register_worker_hooks(policy):
  711. """Worker side of the same contract: tools run in the managed child, so its own plugin
  712. manager needs the session's shell hooks and outbound webhooks, registered from the frozen
  713. config with the launch's consent (a Kanban attempt always consents), as the classic one-shot
  714. CLI registered both at startup. Bypass sessions register nothing (the safe policy also
  715. refuses inside both registrars)."""
  716. if policy.ignore_user_config:
  717. return
  718. kanban = json.loads(policy.kanban_json or 'null') or {}
  719. accept = json.loads(policy.request_json).get('accept_hooks') is True or kanban.get('accept_hooks') is True
  720. from agent.outbound_webhooks import register_from_config as register_outbound_webhooks
  721. from agent.shell_hooks import register_from_config
  722. config = policy.config()
  723. register_from_config(config, accept_hooks=accept)
  724. register_outbound_webhooks(config)
  725. def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None, owner_key=False,
  726. client_request=None):
  727. """CLI keys live only in this authority lifetime, never its durable receipt.
  728. Restart deliberately revokes them. History remains readable; inference must
  729. report launch_credentials_unavailable, never select a profile fallback key.
  730. An ``owner_key`` (an alias's, expanded by the owner) of the same create request as the attempt
  731. holding the slot (``same_create_retry``, its ``client_env`` in ``client_request``) takes the held
  732. key: a ``.env`` rotation between overlapping attempts is not a changed request, and the policy
  733. then fingerprints the key it runs with.
  734. """
  735. from dataclasses import replace
  736. import hmac
  737. from gateway.session_local_mcp import PRIVATE_KEY, bind_editor_mcp
  738. config_secrets = dict(config_secrets or {})
  739. policy = bind_editor_mcp(authority, session_id, policy, config_secrets.pop(PRIVATE_KEY, None))
  740. if api_key is None and not config_secrets:
  741. # Nothing private remains (a followed section's secret, or a cleared key): a stale reference
  742. # would no longer match the re-fingerprinted policy identity.
  743. return replace(policy, credential_ref=None, config_secret_ref=None)
  744. keys = getattr(authority, '_local_launch_keys', None)
  745. if keys is None:
  746. keys = authority._local_launch_keys = {}
  747. ref = f'{authority.instance_id}:{authority.epoch}:{session_id}'
  748. old = keys.get(ref)
  749. owners = getattr(authority, '_local_owner_key_requests', None)
  750. if owners is None:
  751. owners = authority._local_owner_key_requests = {}
  752. if owner_key and api_key is not None and old is not None and ref in owners:
  753. from hermes_state_local import same_create_retry
  754. api_key = old if same_create_retry(owners[ref], policy.request_json, client_request or {}) else api_key
  755. # Only a key that IS being bound can conflict: binding config secrets alone (a provider
  756. # change drops the launch key) must not be refused by the key the session already holds.
  757. if api_key is not None and old is not None and not hmac.compare_digest(old, api_key):
  758. raise RuntimeStoreError('admission_conflict')
  759. configs = getattr(authority, '_local_config_secrets', None)
  760. if configs is None:
  761. configs = authority._local_config_secrets = {}
  762. config_ref = ref
  763. if config_secrets and getattr(authority, 'db', None) is not None:
  764. from gateway.session_policy_credentials import config_reference
  765. config_ref = config_reference(authority, session_id, policy, config_secrets)
  766. if config_ref in configs and configs[config_ref] != config_secrets:
  767. raise RuntimeStoreError('admission_conflict')
  768. if config_secrets:
  769. configs[config_ref] = dict(config_secrets)
  770. if api_key is not None and old is None and owner_key:
  771. owners[ref] = {k: getattr(policy, k) for k in ('request_json', 'client_env_json', 'client_env_rules_json')}
  772. if api_key is not None:
  773. keys[ref] = api_key
  774. # The durable ref carries the key's fingerprint (the digest config_secret_ref already
  775. # persists for config keys) so a restarted owner can verify a re-supplied key
  776. # (rebind_launch_key); the key itself is never durable.
  777. from agent.credential_persistence import fingerprint_secret_value
  778. return replace(policy, credential_ref=f'{ref}#{fingerprint_secret_value(api_key)}' if api_key is not None else None,
  779. config_secret_ref=config_ref if config_secrets else None)
  780. def _key_slot(credential_ref):
  781. """The in-memory slot of a durable credential ref (``<instance>:<epoch>:<sid>[#<fingerprint>]``)."""
  782. return credential_ref.split('#', 1)[0]
  783. def rebind_launch_key(authority, session, api_key):
  784. """``session.resume`` re-supplying a launch-only key after an owner restart revoked it
  785. (call after authorizing *session*, a SessionRef).
  786. Only a session launched with a key can take one, and only that same key (its durable
  787. fingerprint); anything else is an override of the frozen route and is refused. Like the
  788. original, the key lives in this authority's memory only."""
  789. import hmac
  790. from agent.credential_persistence import fingerprint_secret_value
  791. from gateway.config import Platform
  792. if not isinstance(api_key, str) or not api_key.strip():
  793. _refuse('api_key', 'must be a non-empty string')
  794. source = authority.sessions[session.session_id].source
  795. if source is None or source.platform != Platform.LOCAL:
  796. raise RuntimeStoreError('admission_conflict')
  797. from hermes_state_local import local_receipt
  798. ref = restore_policy(local_receipt(authority.db, session.session_id)['policy']).credential_ref
  799. if ref is None:
  800. raise RuntimeStoreError('admission_conflict')
  801. keys = getattr(authority, '_local_launch_keys', None)
  802. if keys is None:
  803. keys = authority._local_launch_keys = {}
  804. held = keys.get(_key_slot(ref))
  805. if held is not None:
  806. if not hmac.compare_digest(held, api_key):
  807. raise RuntimeStoreError('admission_conflict')
  808. return
  809. _, _, fingerprint = ref.partition('#')
  810. if not fingerprint or not hmac.compare_digest(fingerprint, fingerprint_secret_value(api_key) or ''):
  811. raise RuntimeStoreError('admission_conflict')
  812. keys[_key_slot(ref)] = api_key
  813. def _secret_refs(authority, retired):
  814. """The launch-key slots and config-secret references the LOCAL policies outside *retired* name: the
  815. live sessions', and those of closed conversations ``session_retirement`` let go, which keep their
  816. frozen policy on the local adapter and resume on it (a branch on its parent's slots)."""
  817. from gateway.config import Platform
  818. sources = [live.source for sid, live in authority.sessions.items() if sid not in retired]
  819. chats = {source.chat_id for source in sources if source is not None and source.platform == Platform.LOCAL}
  820. chats.update(sid for sid in getattr(authority, 'retired_local', ()) if sid not in retired)
  821. if not chats:
  822. return set() # only a restored or retired LOCAL session has a policy in the adapter map
  823. from gateway.session_local_recovery import local_adapter_map
  824. policies = getattr(local_adapter_map(authority).get(Platform.LOCAL), 'policies', None) or {}
  825. refs = set()
  826. for policy in filter(None, map(policies.get, chats)):
  827. refs.update(ref for ref in (policy.credential_ref and _key_slot(policy.credential_ref),
  828. policy.config_secret_ref) if ref)
  829. return refs
  830. def release_launch_secrets(authority, session_ids):
  831. """Drop retired sessions' launch keys, frozen config secrets and editor MCP servers.
  832. They live only in this authority's memory for the session's lifetime; a deleted session can
  833. never run again, so keeping them would hold its credentials until the process exits. A branch's
  834. policy names its parent's slots, so a slot named after a retired session stays while a policy the
  835. local adapter holds references it, and then until restart, which revokes every launch secret anyway. Only
  836. slots named after *session_ids* are released, so the set never exceeds release by name: no later
  837. sweep, and a binding not yet published always sits under its own live session's name. Call
  838. before the retired sessions leave ``authority.sessions``."""
  839. import hashlib
  840. from gateway.session_policy_credentials import PREFIX
  841. retired = {str(sid) for sid in session_ids}
  842. if not retired:
  843. return
  844. kept = _secret_refs(authority, retired)
  845. prefix = f'{authority.instance_id}:{authority.epoch}:'
  846. keys = getattr(authority, '_local_launch_keys', None) or {}
  847. # A key re-supplied after a restart sits in the slot of the epoch that minted it.
  848. owners = getattr(authority, '_local_owner_key_requests', None) or {}
  849. for ref in [ref for ref in keys if ref.split(':', 2)[-1] in retired and ref not in kept]:
  850. del keys[ref]
  851. owners.pop(ref, None)
  852. configs = getattr(authority, '_local_config_secrets', None) or {}
  853. for ref in list(configs):
  854. if ref.startswith(PREFIX):
  855. owner = json.loads(ref[len(PREFIX):]).get('session')
  856. else:
  857. owner = ref[len(prefix):] if ref.startswith(prefix) else None
  858. if owner in retired and ref not in kept:
  859. del configs[ref]
  860. editors = getattr(authority, '_local_editor_mcp', None) or {}
  861. for sid in retired:
  862. editors.pop('editor-session:' + hashlib.sha256(f'{authority.profile_id}:{sid}'.encode()).hexdigest(), None)
  863. def launch_key(authority, policy):
  864. if policy.credential_ref is None:
  865. return None
  866. value = getattr(authority, '_local_launch_keys', {}).get(_key_slot(policy.credential_ref))
  867. if value is None:
  868. raise RuntimeStoreError('launch_credentials_unavailable')
  869. return value
  870. def route_launch_key(authority, policy, config):
  871. """The launch key a turn on *config* (the route it runs, a followed profile's included) sends.
  872. A launch key authenticates the frozen route it was bound with: once the followed profile
  873. supersedes that pick and moves to another endpoint, the key stays behind with its route."""
  874. bound = present_sections(json.loads(policy.config_json)) # the route the key was bound with
  875. if not bound_route_holds(bound.get('model'), bound, config.get('model'), config):
  876. return None
  877. return launch_key(authority, policy)
  878. def restore_policy(data):
  879. """Reject incomplete private policy rather than rebuilding from current defaults."""
  880. try:
  881. policy = LocalSessionPolicy(**data)
  882. from gateway.session_a2a import is_forward_policy
  883. surfaces = {**SURFACES, 'cron': 'cron', 'kanban': 'cli', 'bot_room': 'bot_room'}
  884. if ((not is_forward_policy(policy) and
  885. (policy.source not in surfaces or policy.platform != surfaces[policy.source]))
  886. or not isinstance(policy.cwd, str) or not Path(policy.cwd).is_absolute()
  887. or not isinstance(policy.model, str) or not policy.model.strip()
  888. or not isinstance(policy.toolsets, (list, tuple))
  889. or any(not isinstance(name, str) for name in policy.toolsets)
  890. or type(policy.safe_mode) is not bool or type(policy.ignore_user_config) is not bool
  891. or not isinstance(policy.skills_prompt, (str, type(None)))
  892. or type(policy.coding_posture) is not bool
  893. or not _valid_client_env(policy.client_env_json) or type(policy.client_env_remote) is not bool
  894. or not _valid_client_env(policy.client_env_rules_json, list)
  895. or policy.edit_approval_policy not in EDIT_APPROVAL_POLICIES
  896. or (policy.edit_approval_policy != 'ask' and policy.source != 'acp')
  897. or (policy.safe_mode and not policy.ignore_user_config)):
  898. raise ValueError('invalid policy')
  899. from dataclasses import replace
  900. for value in (policy.config_json, policy.request_json, policy.terminal_json):
  901. if not isinstance(json.loads(value), dict):
  902. raise ValueError('invalid policy object')
  903. terminal = json.loads(policy.terminal_json)
  904. if terminal_uses_host_cwd(terminal) and terminal.get('TERMINAL_CWD') != policy.cwd:
  905. raise ValueError('terminal policy mismatch')
  906. return replace(policy, toolsets=tuple(policy.toolsets))
  907. except (KeyError, TypeError, ValueError) as exc:
  908. raise RuntimeStoreError('storage_unavailable') from exc
  909. def _valid_client_env(value, kind: type = str):
  910. """A stored client map (names to strings) or its rules (``kind=list``: rule names to string lists)."""
  911. if value is None:
  912. return True
  913. env = json.loads(value) if isinstance(value, str) else None
  914. return isinstance(env, dict) and all(isinstance(k, str) and isinstance(v, kind) and (
  915. kind is str or all(isinstance(item, str) for item in v)) for k, v in env.items())
  916. def policy_turn_toolsets(authority, policy, config, session_id):
  917. """A local turn's toolsets: the policy's current set, plus ``onboarding`` for an onboarding chat
  918. (``agent.onboarding_session.onboarding_chat_toolsets``)."""
  919. from agent.onboarding_session import onboarding_chat_toolsets
  920. return onboarding_chat_toolsets(list(policy.current_toolsets(config)), getattr(authority, 'db', None), session_id)
  921. def local_desktop_turn(runner, source, scope):
  922. """*scope* (the profile scope a turn enters), also marked as work for the local Desktop when the
  923. turn belongs to a Desktop chat its creator's connection declared local (``stage_local_session``);
  924. any other turn gets *scope* untouched. Read from the live policy without raising: a cold policy
  925. is restored, or refused, by the turn."""
  926. from gateway.config import Platform
  927. policy = None
  928. if getattr(source, 'platform', None) == Platform.LOCAL:
  929. policy = getattr(runner._adapter_for_source(source), 'policies', {}).get(source.chat_id)
  930. # The request_json mark: a chat an earlier build created, which stamped it into the creation request.
  931. if policy is None or policy.source != 'gui' or not any(
  932. json.loads(raw).get(LOCAL_DESKTOP_CHAT) is True for raw in (policy.config_json, policy.request_json)):
  933. return scope
  934. return _serving_local_desktop_within(scope)
  935. @contextmanager
  936. def _serving_local_desktop_within(scope):
  937. from hermes_cli.process_identity import serving_local_desktop
  938. with scope, serving_local_desktop(True):
  939. yield
  940. def policy_for_source(runner, source):
  941. from gateway.session_local import LocalSessionAdapter
  942. from gateway.config import Platform
  943. if source is None or source.platform != Platform.LOCAL: # None: a history mount, which runs nothing
  944. return None
  945. adapter = runner._adapter_for_source(source)
  946. if isinstance(adapter, LocalSessionAdapter) and adapter.authorize_source(source):
  947. policy = adapter.policies.get(source.chat_id)
  948. if policy is None:
  949. # Cold recovery must restore the frozen policy before executing, not
  950. # reinterpret a LOCAL route as a default CLI launch.
  951. raise RuntimeStoreError('storage_unavailable')
  952. return policy
  953. return None
  954. def workspace_ready(policy) -> bool:
  955. """Readiness, not structure: a removed workspace keeps the chat readable and movable, but no
  956. turn runs in a missing directory."""
  957. return Path(policy.cwd).is_dir()
  958. def workspace_unavailable_result(policy) -> dict:
  959. """A failed, never-run turn for a session whose frozen working directory is gone. Nothing ran
  960. and an unchanged resend fails the same way, so the reply names the folder and the way out
  961. instead of the generic "something went wrong" apology."""
  962. from agent.i18n import t
  963. from agent.turn_failure_copy import stamp_failure
  964. text = t("gateway.errors.workspace_unavailable", path=policy.cwd)
  965. return stamp_failure({"final_response": text, "messages": [], "api_calls": 0, "tools": [],
  966. "failed": True, "completed": False, "error": text},
  967. "workspace_unavailable", False)
  968. def refused_turn_result(policy, exc) -> dict | None:
  969. """A failed, never-run turn for an owner refusal at scope entry that an unchanged resend repeats
  970. (gone working folder, changed launch key); None for any other refusal."""
  971. from agent.error_surface import build_error_surface_from_result
  972. from agent.turn_failure_copy import launch_credentials_copy, stamp_failure
  973. if exc.reason == 'workspace_unavailable':
  974. result = workspace_unavailable_result(policy)
  975. elif exc.reason == 'launch_credentials_unavailable':
  976. text = launch_credentials_copy(exc)
  977. result = stamp_failure({"final_response": text, "messages": [], "api_calls": 0, "tools": [],
  978. "failed": True, "completed": False, "error": text},
  979. "launch_credentials_unavailable", False)
  980. else:
  981. return None
  982. # The descriptor makes settlement commit the explanation and its card as the transcript's
  983. # failed-turn boundary (gateway_refusal_boundary), so a reopened chat still shows the way out.
  984. result["error_surface"] = build_error_surface_from_result(result)
  985. return result
  986. @contextmanager
  987. def policy_scope(policy, *, authority=None):
  988. if policy is None:
  989. yield
  990. return
  991. if not workspace_ready(policy):
  992. raise RuntimeStoreError('workspace_unavailable', field='cwd', detail=policy.cwd)
  993. from agent.runtime_cwd import set_session_cwd
  994. from tools.terminal_scope import set_terminal_scope, reset_terminal_scope
  995. terminal = json.loads(policy.terminal_json)
  996. if policy.config_secret_ref is not None:
  997. from gateway.session_policy_credentials import recover_config_secrets
  998. for path, value in recover_config_secrets(authority, policy).items():
  999. if path[0] is None:
  1000. terminal[path[1]] = value
  1001. # A following session's turn reads its profile once; every resolution in the turn uses that read.
  1002. profile_token = _TURN_PROFILE.set((policy, policy.read_profile(authority)))
  1003. active = policy
  1004. if policy.follows_profile:
  1005. from dataclasses import replace
  1006. active = replace(policy, toolsets=policy.current_toolsets(policy.config(authority, secrets=False)))
  1007. cwd_token = set_session_cwd(policy.cwd)
  1008. terminal_token = set_terminal_scope(terminal)
  1009. policy_token = _ACTIVE_POLICY.set(active)
  1010. from gateway.session_local_editor import editor_scope
  1011. try:
  1012. from agent.auxiliary_task_config import session_auxiliary_scope
  1013. from gateway.session_local_mcp import editor_mcp_scope
  1014. # Side tasks follow the profile's config.yaml, as every other side-task reader does; a bypass
  1015. # session never reads the profile: its side tasks use its own saved section (code defaults only).
  1016. aux_scope = (session_auxiliary_scope(policy.config(authority, secrets=False).get('auxiliary'))
  1017. if policy.ignore_user_config else contextlib.nullcontext())
  1018. with (editor_scope(policy), editor_mcp_scope(authority, policy), aux_scope,
  1019. policy.client_env_scope()):
  1020. yield
  1021. finally:
  1022. _ACTIVE_POLICY.reset(policy_token)
  1023. reset_terminal_scope(terminal_token)
  1024. cwd_token.var.reset(cwd_token)
  1025. _TURN_PROFILE.reset(profile_token)
  1026. def bind_turn_workspace(policy, task_id):
  1027. """Make the session's frozen workspace its terminal cwd override for this turn's tools (#140665).
  1028. The client's cwd (or ``--in DIR``) is frozen into the policy at admission, but the terminal tool
  1029. mounts ``resolve_task_overrides(task_id)['cwd']`` into a per-session Docker container. Before the
  1030. one-gateway runtime each ``hermes chat`` was its own process with its own ``TERMINAL_CWD``; now the
  1031. turn runs here, so register it under the turn's own task id (inside the turn's routed scope, which
  1032. qualifies the key). Docker mounting the host cwd only: the local backend already runs in the
  1033. policy's ``TERMINAL_CWD``, and ssh and the other sandboxes keep their own cwd. Re-registered only
  1034. when the workspace changed, so an agent's ``cd`` inside the session survives later turns.
  1035. """
  1036. if policy is None or not task_id:
  1037. return
  1038. terminal = json.loads(policy.terminal_json)
  1039. if str(terminal.get('TERMINAL_ENV') or '').strip().lower() != 'docker' or not terminal_uses_host_cwd(terminal):
  1040. # The session moved off a host-cwd Docker mount (e.g. to SSH with its own terminal.cwd): the
  1041. # binding an earlier turn registered would otherwise win in _plan_execution on the new backend.
  1042. unbind_turn_workspace(task_id)
  1043. return
  1044. from tools.terminal_tool import register_task_env_overrides, resolve_task_overrides, workspace_key_for
  1045. current = resolve_task_overrides(task_id)
  1046. if current.get('cwd') == policy.cwd and current.get('cwd_source') == 'session':
  1047. return
  1048. register_task_env_overrides(task_id, {**current, 'cwd': policy.cwd, 'cwd_source': 'session',
  1049. 'workspace_key': workspace_key_for(policy.cwd)})
  1050. def unbind_turn_workspace(task_id):
  1051. """Drop the workspace override :func:`bind_turn_workspace` registered for *task_id*, and the cwd
  1052. record it seeded. Only its own entry (tagged ``workspace_key``): an ACP/TUI workspace or an RL
  1053. image override registered by someone else under the same id stays."""
  1054. if not task_id:
  1055. return
  1056. from tools.terminal_tool import _qualify_task_key, _task_env_overrides, clear_session_cwd, get_session_cwd
  1057. key = _qualify_task_key(task_id)
  1058. current = _task_env_overrides.get(key) or {}
  1059. if 'workspace_key' not in current:
  1060. return
  1061. _task_env_overrides.pop(key, None)
  1062. if get_session_cwd(task_id) == current.get('cwd'):
  1063. clear_session_cwd(task_id)
  1064. def release_session_workspaces(authority, session_ids):
  1065. """Session teardown: drop each session's workspace binding under its owning profile's scope (the
  1066. key the turn bound it under), so the override table does not grow with every closed session."""
  1067. from gateway.session_authorities import owner_scope
  1068. with owner_scope(authority):
  1069. for sid in session_ids:
  1070. unbind_turn_workspace(sid)
  1071. @contextmanager
  1072. def profile_read_scope(policy, authority):
  1073. """Hold ONE read of a following session's profile for every resolution inside, as a turn's
  1074. ``policy_scope`` does, without that scope's workspace and terminal setup (a session control
  1075. reads the route, it runs nothing)."""
  1076. token = _TURN_PROFILE.set((policy, policy.read_profile(authority)))
  1077. try:
  1078. yield
  1079. finally:
  1080. _TURN_PROFILE.reset(token)
  1081. def active_policy():
  1082. """The frozen launch policy of the turn executing in this context, or ``None`` (standalone
  1083. serve / messaging turns). Consumers read it instead of re-deriving from live config."""
  1084. return _ACTIVE_POLICY.get()