session_mutations.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. """Action-specific authority mutations, shared by WS and authenticated HTTP.
  2. No legacy slash handler is executed after a receipt: those handlers own separate
  3. transactions. Local reset prepares its replacement in the receipt transaction;
  4. branch/compress/model still require their own prepared runtime publication.
  5. """
  6. import asyncio
  7. import logging
  8. from contextlib import nullcontext
  9. from functools import partial
  10. from gateway.session_messaging_picks import CHAT_PICKS, is_chat_pick
  11. from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
  12. from hermes_state_runtime import RuntimeStoreError, mutate_runtime_session
  13. logger = logging.getLogger(__name__)
  14. _METADATA = frozenset({'rename', 'archive', 'sidebar'})
  15. # Prepared off the commit like model, then published as a new frozen policy.
  16. _POLICY = frozenset({'model', 'reasoning', 'workspace', 'editor_mcp', 'edit_policy'})
  17. # Controls that leave the transcript alone authorize on the lineage owner (see ``_owner_ref``).
  18. _OWNER_AUTHORIZED = _METADATA | {'delete'}
  19. _FIELDS = frozenset({'session_id', 'request_id', 'expected_revision', 'operation', 'payload'})
  20. def _authorize_import(authority, actor, ref, params):
  21. """Import authorization; returns the imported session ids the write must claim."""
  22. if actor.profile_id != authority.profile_id or ref.profile_id != authority.profile_id:
  23. raise RuntimeStoreError('profile_mismatch')
  24. if 'session:create' not in actor.capabilities:
  25. raise RuntimeStoreError('permission_denied')
  26. from hermes_state_mutations import validate_action
  27. validate_action('import', params['payload'])
  28. normalized, errors = authority.db._validate_import_payload(params['payload']['sessions'])
  29. if errors:
  30. raise RuntimeStoreError('invalid_params')
  31. return tuple(item['session']['id'] for item in normalized)
  32. def _authorize_control(authority, actor, ref, params, owner=None):
  33. """Control authorization; True when the session is cold history the write must claim. *owner* is
  34. ``_owner_ref``'s answer when the caller already resolved it (one read per mutation, not two)."""
  35. from hermes_state_mutation_retirement import has_mutation_receipt
  36. if actor.profile_id != authority.profile_id or ref.profile_id != authority.profile_id:
  37. raise RuntimeStoreError('profile_mismatch')
  38. if 'session:control' not in actor.capabilities:
  39. raise RuntimeStoreError('permission_denied')
  40. cold_history = False
  41. # A receipt authorizes only its original principal's exact retry; the
  42. # transaction still verifies the entire digest and current epoch.
  43. if not has_mutation_receipt(authority.db, actor.subject, ref.session_id, params['request_id']):
  44. ref = owner or _owner_ref(authority, ref, params)
  45. if ref.session_id not in authority.sessions:
  46. from hermes_state_mutation_binding import authorize_history
  47. with authority.db._read_ctx() as conn:
  48. from gateway.session_local_migration import require_history_claim
  49. require_history_claim(authority, conn, actor, ref.session_id)
  50. cold_history = authorize_history(conn, actor, ref.session_id)
  51. if not cold_history:
  52. operation = params.get('operation')
  53. if operation in {'delete', 'archive', 'sidebar'}:
  54. # The read gate mounts a cold row first, so the checks below see what it is.
  55. authority.authorize(actor, ref, 'session:read')
  56. from gateway.session_history_mount import is_history_mount
  57. if operation == 'delete':
  58. from gateway.session_history_mount import require_history_leaf
  59. require_history_leaf(authority, ref.session_id)
  60. if not (operation in {'delete', 'archive', 'sidebar'} and is_history_mount(authority.sessions[ref.session_id])):
  61. # Stored history is read-only, but deleting it retires its own lineage only, and
  62. # archiving or pinning it flags that lineage's rows only.
  63. authority.authorize(actor, ref, 'session:control')
  64. return cold_history
  65. def _owner_ref(authority, ref, params):
  66. """A metadata control (rename, archive, pin) or a delete names the listed row, which may be a
  67. later reset or compression segment of a local conversation; the conversation's creation id owns
  68. its live session, so control and the session gate are checked on that owner. The write itself
  69. still names the listed row (a title or archive flag belongs to it; delete takes the lineage).
  70. Gating only ``delete`` answered rename/archive of a compressed conversation with
  71. ``storage_unavailable`` (#134889 LC-22, as LC-12 on resume).
  72. A transcript- or policy-changing operation (rewind, reset, compress, a policy pick) keeps the
  73. listed id: its busy gate, generation fence and eviction are keyed by the session it writes, so
  74. authorizing it on the owner while writing the segment would bypass the owner's FIFO. A segment
  75. of a live owner therefore stays a named refusal for those, as on main. A delete of a messaging
  76. conversation's later compression segment, or a model/reasoning pick on it, resolves to its
  77. lineage root, where its lane's session lives (``messaging_owner_ref``, as resume does)."""
  78. if params.get('operation') in CHAT_PICKS:
  79. # A messaging chat's picks are its lane's (route-keyed) overrides: a compression segment names
  80. # the lineage root its lane is mounted on. Any other row keeps its id.
  81. from gateway.session_route_recovery import messaging_owner_ref
  82. return messaging_owner_ref(authority, ref)
  83. if params.get('operation') not in _OWNER_AUTHORIZED:
  84. return ref
  85. from gateway.session_contract import SessionRef
  86. from hermes_state_local import local_lineage_owner
  87. with authority.db._read_ctx() as conn:
  88. owner = local_lineage_owner(conn, ref.session_id)
  89. if owner == ref.session_id and params.get('operation') == 'delete':
  90. from gateway.session_route_recovery import messaging_owner_ref
  91. return messaging_owner_ref(authority, ref)
  92. return ref if owner == ref.session_id else SessionRef(ref.profile_id, owner)
  93. async def mutate_session(authority, actor, ref, params):
  94. from gateway.session_runtime_workers import track_mutation
  95. authority._require_admission_open()
  96. # A request socket can disappear while its writer is inside to_thread. The owner task keeps
  97. # the session gate until commit AND publication finish, and retirement joins that same task.
  98. task = track_mutation(authority, _owned_mutation(authority, actor, ref, params))
  99. return await asyncio.shield(task)
  100. async def _owned_mutation(authority, actor, ref, params):
  101. if (params.get('operation') in {*_POLICY, 'compress', 'reset', 'rewind'}
  102. and ref.session_id not in authority.sessions and 'request_id' in params):
  103. _authorize_control(authority, actor, ref, params)
  104. owner = _owner_ref(authority, ref, params)
  105. live = authority.sessions.get(owner.session_id)
  106. if live is None:
  107. return await _mutate_session(authority, actor, ref, params, owner=owner)
  108. # Prepared policy/route publication is inseparable from its durable commit
  109. # for admission and claim: neither may observe a half-published policy.
  110. if params.get('operation') == 'compress':
  111. # The summarization (an LLM call) runs outside the session gate, so a submit or metadata
  112. # edit is not parked behind it; the commit is revision/generation-fenced against anything
  113. # that lands meanwhile. Claims wait on ``claim_gate``, so no turn runs under it.
  114. async with live.claim_gate:
  115. result = await _mutate_session(authority, actor, ref, params, commit_lock=live.mutation_lock, owner=owner)
  116. else:
  117. async with live.mutation_lock:
  118. try:
  119. result = await _mutate_session(authority, actor, ref, params, owner=owner)
  120. except (RuntimeStoreError, *MUTATION_GUARD_REFUSALS) as exc:
  121. # A pick on a running session is for the next turn (the running turn keeps its route).
  122. if (params.get('operation') not in {'model', 'reasoning'}
  123. or getattr(exc, 'reason', 'session_busy') != 'session_busy'):
  124. raise
  125. from gateway.session_deferred_pick import defer_pick
  126. # Its own BEGIN IMMEDIATE: off the loop, like the receipt commit.
  127. return await asyncio.to_thread(defer_pick, authority, actor, ref, params)
  128. if params.get('operation') in {*_POLICY, 'compress', 'reset'} and not is_chat_pick(live, params['operation']):
  129. authority._schedule(ref)
  130. return result
  131. async def _mutate_session(authority, actor, ref, params, *, commit_lock=None, owner=None):
  132. if (set(params) - {'expected_generation'} != _FIELDS
  133. or params['session_id'] != ref.session_id):
  134. raise RuntimeStoreError('invalid_params')
  135. operation = params['operation']
  136. if not isinstance(operation, str) or (operation in _POLICY and params.get('expected_generation') is None):
  137. raise RuntimeStoreError('invalid_params')
  138. from gateway.session_local_mcp import private_mutation_payload
  139. # Editor MCP transport specs (credentials) stay in owner memory; the store sees a fingerprint.
  140. payload, editor_servers = private_mutation_payload(operation, params['payload'])
  141. params = {**params, 'payload': payload}
  142. cold_history = False
  143. imported_ids = None
  144. if operation == 'import':
  145. imported_ids = _authorize_import(authority, actor, ref, params)
  146. else:
  147. cold_history = _authorize_control(authority, actor, ref, params, owner)
  148. if operation == 'branch' and 'session:create' not in actor.capabilities:
  149. raise RuntimeStoreError('permission_denied')
  150. authority._require_admission_open()
  151. live = authority.sessions.get((owner or ref).session_id)
  152. if is_chat_pick(live, operation):
  153. # No frozen policy to commit into: the chat's own /model and /reasoning override (#141152).
  154. from gateway.session_messaging_picks import apply_chat_pick
  155. return await apply_chat_pick(authority, ref, owner or ref, live, params, principal_id=actor.subject)
  156. def authorize_write(conn):
  157. from hermes_state_mutation_binding import authorize_history, import_history_control
  158. if operation == 'import':
  159. import_history_control(conn, actor, imported_ids)
  160. return
  161. if not authorize_history(conn, actor, ref.session_id, claim=True):
  162. raise RuntimeStoreError('permission_denied')
  163. return await write_mutation(authority, ref, params, editor_servers, principal_id=actor.subject,
  164. authorize_write=authorize_write if cold_history or operation == 'import' else None,
  165. commit_lock=commit_lock)
  166. def _runtime_owns_authority(authority) -> bool:
  167. """Whether *authority* is one of its own runner's authorities, so one process coordinates
  168. both writes of a delete: the receipt commit to ``authority.db`` and the routing retire
  169. through the runner store's routing index. Raw ``db_path`` equality only ever holds for the
  170. launch home — the routing index is pinned to the launch home for every profile (#66887) —
  171. so a multiplexed secondary profile's store never compares equal and each of its deletes
  172. was refused with ``runtime_coordination_required`` (#138826)."""
  173. runner = getattr(authority, 'runner', None)
  174. registry = getattr(runner, 'session_authorities', None)
  175. if registry is not None:
  176. return any(a is authority for a in registry)
  177. return getattr(runner, 'session_authority', None) is authority
  178. async def write_mutation(authority, ref, params, editor_servers, *, principal_id, authorize_write=None,
  179. commit_lock=None):
  180. """The writer phase of ``session.mutate``, and of the admission-start editor MCP re-freeze
  181. (``refreeze_editor_mcp``): fenced prepare, the receipt commit, then its runtime projections.
  182. The caller authorized the change and holds the session's locks; this takes neither."""
  183. operation = params['operation']
  184. live = authority.sessions.get(ref.session_id)
  185. applied = False
  186. def live_guard(targets):
  187. nonlocal applied
  188. applied = True
  189. if operation in _METADATA or operation == 'import':
  190. return
  191. # Idleness is the ledger's call (require_idle, same transaction). The drain
  192. # task outlives the final settlement by one loop iteration, so its liveness
  193. # would refuse a session whose receipt the client already saw as terminal.
  194. if operation == 'delete':
  195. store = getattr(authority.runner, 'session_store', None)
  196. if store is not None and (store._routing_db is None
  197. or not _runtime_owns_authority(authority)):
  198. raise RuntimeStoreError('runtime_coordination_required')
  199. if operation in {'rewind', 'reset'} and not callable(getattr(authority.runner, '_evict_cached_agent', None)):
  200. raise RuntimeStoreError('runtime_coordination_required')
  201. fields = dict(epoch=authority.epoch, principal_id=principal_id, session_id=ref.session_id,
  202. request_id=params['request_id'], expected_revision=params['expected_revision'],
  203. expected_generation=params.get('expected_generation'), operation=operation,
  204. payload=params['payload'], _live_guard=live_guard)
  205. async def prepare_only():
  206. # Its own BEGIN IMMEDIATE, so off the loop like the commit below.
  207. return await asyncio.to_thread(mutate_runtime_session, authority.db, **fields, _prepare_only=True)
  208. prepared = None
  209. if operation == 'branch':
  210. from gateway.session_local_mcp import prepare_branch_editor
  211. # Discovery launches the child's servers: the fences (receipt, revision, generation, idle) answer first.
  212. prepared, editor_servers = await prepare_branch_editor(authority, ref, editor_servers, prepare_only)
  213. if operation in {*_POLICY, 'compress'}:
  214. prepared = await prepare_only()
  215. if 'snapshot' in prepared:
  216. from gateway.session_mutation_model import prepare_model
  217. from gateway.session_mutation_compress import prepare_compress
  218. from gateway.session_mutation_policy import PREPARE
  219. from gateway.session_local_mcp import prepare_editor_mcp
  220. prepare = {'model': prepare_model, 'compress': prepare_compress, **PREPARE,
  221. 'editor_mcp': partial(prepare_editor_mcp, servers=editor_servers)}[operation]
  222. prepared = await prepare(authority, live, params['payload'], prepared)
  223. if prepared.get('status') in {'preview', 'noop', 'confirmation_required'}:
  224. # ``--preview`` and a compress that removes nothing are read-only reports, and a
  225. # guarded model target awaits the user's confirmation: no receipt, no publication,
  226. # no eviction.
  227. return {'session_id': ref.session_id, 'operation': operation, **prepared}
  228. applied = False
  229. result = None
  230. async with commit_lock or nullcontext():
  231. if prepared is not None and 'snapshot' not in prepared:
  232. # Exact retry: the durable receipt is the result. Never re-prepare (compress
  233. # would summarize again); the runtime repairs below still run, because the
  234. # first attempt may have committed and then failed before publishing them.
  235. result = prepared
  236. else:
  237. # The receipt transaction is synchronous SQLite: run it off the event loop so a large
  238. # state.db or a contended writer lock never stalls other clients (main 1769024ca3b).
  239. commit = partial(mutate_runtime_session, authority.db, **fields,
  240. _prepared=prepared, _authorize_write=authorize_write)
  241. if operation == 'delete':
  242. from gateway.session_onboarding import ending_run_on_delete
  243. commit = partial(ending_run_on_delete, authority.db, ref.session_id, commit)
  244. try:
  245. result = await asyncio.to_thread(commit)
  246. finally:
  247. if operation == 'compress':
  248. # Before the projection's boundary eviction ends the resident agent's engine
  249. # session; a refused commit only releases a one-off engine.
  250. from gateway.session_mutation_compress import finish_compress_engine
  251. await finish_compress_engine(authority, prepared, result if applied else None)
  252. try:
  253. await _project_result(authority, ref, live, params, result, editor_servers, applied=applied)
  254. finally:
  255. # The receipt is committed: a failed projection must not swallow the hook, and an exact
  256. # retry (applied=False) never refires it.
  257. if operation == 'compress' and applied and (prepared or {}).get('post_compaction'):
  258. from gateway.session_mutation_compress import fire_post_compaction_hook
  259. await fire_post_compaction_hook(authority, prepared, result)
  260. if operation == 'delete':
  261. # After the synchronous projections (no yield before retirement), off the loop: the
  262. # retired-media owner check is a messages-table pass (exact retries repeat it too).
  263. from hermes_state_media import collect_retired_media
  264. await asyncio.to_thread(collect_retired_media, authority.db)
  265. return result
  266. async def _project_result(authority, ref, live, params, result, editor_servers, *, applied):
  267. """A committed receipt's projections, under the writer's commit lock. They are idempotent reads
  268. of the committed receipt, so exact retries repeat them (like delete's retirement); only the
  269. one-shot event is fenced."""
  270. operation = params['operation']
  271. current = authority.db.get_session(ref.session_id)
  272. owns_projection = current is not None and (
  273. current['runtime_generation'] == result.get('execution_generation', params.get('expected_generation')))
  274. if operation == 'compress' and applied and owns_projection and live is not None:
  275. # Before the boundary evicts the agent whose compressor holds the running count.
  276. from gateway.session_usage import note_compression
  277. note_compression(authority, ref, live)
  278. elif operation == 'reset' and applied and live is not None:
  279. live.compression_count = 0 # a fresh conversation, as main's /new builds a fresh agent
  280. if editor_servers is not None and (operation == 'branch' or owns_projection):
  281. # Before the policy publication below, so no execution sees the policy without them.
  282. from gateway.session_local_mcp import install_editor_mcp
  283. install_editor_mcp(authority, result.get('branched_session_id', ref.session_id), editor_servers)
  284. if operation == 'editor_mcp' and not editor_servers:
  285. # An empty selection: the old servers must not keep running for a viewer.
  286. from gateway.session_local_mcp import retire_editor_mcp
  287. await asyncio.to_thread(retire_editor_mcp, authority, ref.session_id)
  288. if operation not in {*_POLICY, 'reset', 'compress', 'rewind'} or owns_projection:
  289. if operation == 'workspace':
  290. # Main's move drops the terminal environment so the next command starts in the new folder: the
  291. # route-keyed one a turn built and the cwd its commands recorded, which would win over the move.
  292. # Off-loop (a remote teardown takes seconds) and before the policy publishes and the queue runs,
  293. # so no turn starts on the old environment.
  294. from gateway.session_policy_refresh import drop_session_terminal
  295. try:
  296. await asyncio.to_thread(drop_session_terminal, authority, ref)
  297. except Exception: # health: allow BLE001 -- the move is committed: it must still publish
  298. logger.warning('Session %s moved without dropping its terminal environment', ref.session_id,
  299. exc_info=True)
  300. _project_committed(authority, ref, operation, result)
  301. if live is not None:
  302. if operation == 'rewind' and owns_projection:
  303. authority.runner._evict_cached_agent(live.route)
  304. if applied:
  305. live.event_stream.publish(ref.session_id, result, event_type='session.updated')
  306. from gateway.session_local_mcp import announce_tools_changed
  307. announce_tools_changed(live, ref.session_id, result)
  308. def _project_committed(authority, ref, operation, result):
  309. """Publish a committed receipt's runtime projections (safe to repeat on exact retry)."""
  310. if operation in _POLICY:
  311. from gateway.session_local import publish_local_policy
  312. # The edit policy is read per edit, never by the built agent: it keeps its agent (and prompt cache).
  313. publish_local_policy(authority, ref.session_id, evict=operation != 'edit_policy')
  314. # A drain that ran while the receipt committed off-loop saw the new stored policy beside
  315. # the old live one and paused; with both now equal, queued input must run, not wait for
  316. # the next submit or restart.
  317. authority._schedule(ref)
  318. if operation == 'reasoning' or (operation == 'model' and 'effort' in result):
  319. # The picked level is the policy's now; a typed /reasoning override must not shadow it, nor an older
  320. # command still waiting for a turn boundary.
  321. authority.runner._set_session_reasoning_override(authority.sessions[ref.session_id].route, None)
  322. authority.sessions[ref.session_id].pending_reasoning = None
  323. if operation in {'model', 'reasoning', 'workspace', 'edit_policy'}:
  324. # Every viewer repaints its model, reasoning pill or workspace from the published policy,
  325. # as main's _emit_session_info did after the live change.
  326. from gateway.session_local import local_session_info
  327. authority.sessions[ref.session_id].event_stream.publish(
  328. ref.session_id, local_session_info(authority, ref), event_type='session.info')
  329. if operation == 'branch':
  330. from gateway.session_local_recovery import restore_local_session
  331. restore_local_session(authority, result['branched_session_id'])
  332. if operation in {'reset', 'compress'}:
  333. from gateway.session_local_recovery import restore_local_session
  334. restore_local_session(authority, ref.session_id)
  335. # A session boundary, not a resource evict: memory providers get on_session_end first.
  336. evict = getattr(authority.runner, '_evict_cached_agent_at_boundary', None) or authority.runner._evict_cached_agent
  337. evict(authority.sessions[ref.session_id].route)
  338. # Publish the prepared entry, not just its target ID, so fresh-reset and
  339. # per-session counters match cold recovery in this process too.
  340. from hermes_state_local import local_receipt
  341. from gateway.session import SessionEntry
  342. store = authority.runner.session_store
  343. with store._lock:
  344. entry = SessionEntry.from_dict(local_receipt(authority.db, ref.session_id)['entry'])
  345. entry.origin = authority.sessions[ref.session_id].source
  346. store._entries[entry.session_key] = entry
  347. if operation == 'delete':
  348. # Repeat local retirement on an exact retry too: publication may have
  349. # failed after the transaction committed. Never repeat the event.
  350. retire_live_sessions(authority, result['deleted_ids'], require_fence=True)
  351. def retire_live_sessions(authority, session_ids, *, require_fence=False):
  352. """Drop committed deletions from this owner's memory: routes, launch secrets, live sessions
  353. and their cached agents. Shared by canonical delete and the owner-run bulk prune.
  354. ``require_fence``: refuse ``storage_unavailable`` when the shared routing fence could not be
  355. written (canonical delete, whose exact retry replays the receipt and repeats this call)."""
  356. store = getattr(authority.runner, 'session_store', None)
  357. fence_error = None
  358. if store is not None:
  359. store.retire_runtime_sessions(session_ids)
  360. # The delete transaction fenced and dropped routes in the owning store; a multiplexed
  361. # secondary's routes live in the launch home's shared index, so the store fences them
  362. # there too (fences + drop in one transaction). Without the fence in THAT database a
  363. # whole-index snapshot taken before this delete and saved after it restored the route
  364. # (#138826). The fence is keyed by this profile's routing namespace, so the launch
  365. # profile never takes it for its own deletion, and it ages out with a sweep's marker.
  366. # A failure surfaces after the rest of the cleanup: an exact retry replays the
  367. # committed receipt and repeats this fence.
  368. routing = getattr(store, '_routing_db', None)
  369. if session_ids and routing is not None and routing.db_path != authority.db.db_path:
  370. try:
  371. from gateway.session import _session_key_namespace
  372. from hermes_state_mutation_retirement import expiring_retirements
  373. registry = getattr(authority.runner, 'session_authorities', None)
  374. profile = registry.profile_name(authority) if registry is not None else None
  375. store.fence_retired_routes(
  376. session_ids, namespace=_session_key_namespace(profile).split(':', 1)[1],
  377. expiring=expiring_retirements(authority.db, session_ids))
  378. except Exception as exc:
  379. logger.warning('could not fence shared routing rows for deleted sessions', exc_info=True)
  380. fence_error = exc
  381. # The dropped routes stay in sessions.json until the next full save, which an idle gateway
  382. # may not make before a prune's fence ages out; the next start would then import them back.
  383. # Strip them now, after the fences, whatever write_sessions_json says.
  384. strip = getattr(store, 'strip_retired_mirror_routes', None)
  385. if session_ids and callable(strip):
  386. try:
  387. strip(session_ids)
  388. except Exception:
  389. logger.warning('could not strip retired routes from sessions.json', exc_info=True)
  390. from gateway.session_policy import release_launch_secrets, release_session_workspaces
  391. release_launch_secrets(authority, session_ids)
  392. release_session_workspaces(authority, session_ids)
  393. from tools.async_delegation import allow_for_session
  394. from gateway.session_vault_prompt import release_unlocks
  395. for sid in session_ids:
  396. # A closed session's refusal of new delegations (session_viewer_close) goes with its live state.
  397. allow_for_session((authority.profile_id, sid))
  398. # So do the password managers it unlocked: this path never reaches the viewer-close settle.
  399. release_unlocks(sid)
  400. candidate = authority.sessions.pop(sid, None)
  401. if candidate is None and sid in getattr(authority, 'retired_routes', ()):
  402. # A conversation retirement let go: its cached agent, and what the local adapter keeps for it.
  403. from gateway.session_retirement import forget_retired
  404. forget_retired(authority, sid)
  405. elif candidate is not None:
  406. getattr(authority, 'retired_routes', {}).pop(sid, None)
  407. if candidate is not None: # a detached conversation's route is its own key
  408. evict = getattr(authority.runner, '_evict_cached_agent', None)
  409. if callable(evict):
  410. evict(candidate.route)
  411. from gateway.session_local import forget_live_session
  412. forget_live_session(authority, sid, candidate)
  413. if candidate.detached: # the ids its key owned in the store (session_detached.detached_entry)
  414. from gateway.session_detached import drop_owner_hints
  415. drop_owner_hints(authority.runner.session_store, candidate.route)
  416. from gateway.session_local_mcp import release_editor_mcp
  417. release_editor_mcp(authority, session_ids)
  418. from gateway.session_worker_construct import release_session_prefill
  419. release_session_prefill(authority, session_ids)
  420. if fence_error is not None and require_fence:
  421. raise RuntimeStoreError('storage_unavailable') from fence_error