Skip to content

The agent that grows with you

Merge origin/main (#23: 34 commits to dde8800ed91) into feat/unified-gateway-runtime

Teknium0a25fab6cf9e
diff --cc apps/desktop/e2e/core/no-idle-reap.spec.ts
index 00000000000,1f904ab2f4e..59336a300cd
mode 000000,100644..100644
--- a/apps/desktop/e2e/core/no-idle-reap.spec.ts
+++ b/apps/desktop/e2e/core/no-idle-reap.spec.ts
@@@ -1,0 -1,66 +1,74 @@@
+ /**
- * Support f502bc6f: a "This device" profile's local `hermes serve` child was SIGTERM'd by the pool
- * idle reaper (60 min with nothing streamed), leaving "This device · Backend offline". A local
- * child hosts its profile's cron jobs and bot chats with nobody watching, so it is never retired
- * for being idle. The idle windows are pinned to their 60s floor so two reaper ticks fit the test.
++ * Support f502bc6f: a "This device" profile's local backend was SIGTERM'd by the Desktop pool idle
++ * reaper (60 min with nothing streamed), leaving "This device · Backend offline". A local profile's
++ * backend hosts its cron jobs and bot chats with nobody watching, so it is never torn down for being
++ * idle while the app runs.
++ *
++ * Desktop no longer owns per-profile backend children: every local profile attaches to the one host
++ * gateway (`hermes gateway ensure`). The invariant here: an attached, idle secondary profile keeps
++ * the same gateway process(es) and the same endpoint past the retired reaper's 60s idle floor plus
++ * two of its 60s ticks, and re-dialing it attaches instead of spawning.
+ */
+
+ import * as path from 'node:path'
+
-import { expect, test } from '@playwright/test'
++import { expect, type Page, test } from '@playwright/test'
+
+ import {
+ backendProcesses,
+ coreAppEnv,
+ createCoreSandbox,
+ launchCoreApp,
+ waitForInteractive,
+ writeProviderHome
+ } from './harness'
+ import { startScriptedProvider } from './provider'
+
-const IDLE_MS = 60_000
++// The retired pool's idle floor (60s) plus two reaper ticks (60s each) and slack.
++const OLD_IDLE_WINDOW_MS = 60_000 + 2 * 60_000 + 5_000
+
-test('a local profile backend is never idle-reaped', async () => {
- test.setTimeout(300_000)
++function dialReviewer(page: Page) {
++ return page.evaluate(async () => {
++ const conn = await (window as any).hermesDesktop.getConnectionFor({ connectionId: 'local', profile: 'reviewer' })
++
++ return { baseUrl: String(conn?.baseUrl ?? ''), mode: String(conn?.mode ?? ''), profile: String(conn?.profile ?? '') }
++ })
++}
++
++const gatewayPids = (box: ReturnType<typeof createCoreSandbox>) =>
++ backendProcesses(box)
++ .map(p => p.pid)
++ .sort((a, b) => a - b)
++
++test('an idle local profile stays attached to its gateway', async () => {
++ test.setTimeout(360_000)
+ const provider = await startScriptedProvider()
+ const box = createCoreSandbox('no-idle-reap')
+ writeProviderHome(box.hermesHome, provider.url)
+ writeProviderHome(path.join(box.hermesHome, 'profiles', 'reviewer'), provider.url)
+
- const { app, page } = await launchCoreApp(
- coreAppEnv(box, {
- HERMES_DESKTOP_POOL_IDLE_MS: String(IDLE_MS),
- HERMES_DESKTOP_POOL_PINNED_IDLE_MS: String(IDLE_MS),
- // One process per profile: the pooled child the reaper used to kill.
- HERMES_DESKTOP_ISOLATED_BACKEND: '1'
- })
- )
++ const { app, page } = await launchCoreApp(coreAppEnv(box))
+
+ try {
+ await waitForInteractive(app, page)
- const before = new Set(backendProcesses(box).map(p => p.pid))
+
- await page.evaluate(() =>
- (window as any).hermesDesktop.getConnectionFor({
- connectionId: 'local',
- profile: 'reviewer',
- priority: 'foreground'
- })
- )
++ const attached = await dialReviewer(page)
++ expect(attached.mode, 'reviewer dials the local gateway').toBe('local')
++ expect(attached.baseUrl, 'reviewer has a gateway endpoint').toMatch(/^http:\/\/127\.0\.0\.1:\d+/)
++
++ const before = gatewayPids(box)
++ expect(before.length, 'a local gateway is running').toBeGreaterThan(0)
+
- const child = backendProcesses(box).find(p => !before.has(p.pid))
- expect(child, 'a pooled backend for reviewer').toBeDefined()
++ // Nothing touches or streams on reviewer for longer than any idle window the old pool used.
++ await page.waitForTimeout(OLD_IDLE_WINDOW_MS)
+
- // Two reaper ticks past both idle windows, with nothing touching or streaming.
- await page.waitForTimeout(IDLE_MS + 2 * 60_000 + 5_000)
++ expect(gatewayPids(box), 'the same gateway process(es) still run').toEqual(before)
+
- expect(
- backendProcesses(box).map(p => p.pid),
- 'reviewer backend still running'
- ).toContain(child!.pid)
++ const redial = await dialReviewer(page)
++ expect(redial, 'reviewer is still attached to the same endpoint').toEqual(attached)
++ expect(gatewayPids(box), 're-dial attaches, never spawns').toEqual(before)
+ } finally {
+ await app.close().catch(() => undefined)
+ await provider.close()
+ }
+ })
diff --cc gateway/run_turn_prepare.py
index ba76040bfdc,00000000000..955dde7f2d9
mode 100644,000000..100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@@ -1,731 -1,0 +1,731 @@@
+"""Gateway turn prepare phases; inherited by GatewayTurnMixin."""
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+import asyncio
+import dataclasses
+import inspect
+import json
+import os
+import queue
+import threading
+import time
+from agent.i18n import t
+from agent.session_activity import format_iteration_progress
+from contextlib import nullcontext, suppress
+from contextvars import copy_context
+from gateway.config import Platform
+from gateway.media_repair import repair_explicit_computer_use_media_paths
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.platforms.event import MessageEvent
+from gateway.session import (
+ SessionSource, _session_key_namespace, build_channel_continuity_note,
+ build_session_context,
+)
+from gateway.session_transcript import TranscriptReadError
+from gateway.turn_context import TurnContext
+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError
+from hermes_constants import get_hermes_home_override
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional, Tuple
+from utils import base_url_hostname
+
+if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
+ from gateway.run import GatewayRunner # noqa: F401
+ from gateway.run_turn_runner import TurnRunner # noqa: F401
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:
+ """``_resolve_session_agent_runtime`` for a session bound to a launch policy: the route's FROZEN
+ config and launch credential, walking its own fallback chain on an AuthError. Module-level so
+ tests that bind the method onto bare namespaces still reach it."""
+ from gateway.run import _runtime_agent_kwargs
+ from gateway.session_policy import launch_key
+ from hermes_cli.runtime_provider import frozen_runtime_config, resolve_runtime_with_fallback
+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
+ frozen = policy.config(authority)
+ key = launch_key(authority, policy)
+ launch_url = json.loads(policy.request_json).get('base_url')
+ # Every rung reads the session's FROZEN config, never live config.yaml: a later
+ # ``model.base_url`` edit must not carry this route's frozen credential to the new host
+ # (R2-M2). The auth-store pool is not config, so refresh/rotation still applies.
+ with frozen_runtime_config(frozen):
+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,
+ explicit_api_key=key, explicit_base_url=launch_url,
+ target_model=policy.model, config=frozen)
+ if runtime is None:
+ # Only a bound launch key is explicit: the frozen ``model.api_key`` is config, which the
+ # resolver already reads from the frozen scope, so a URL-matched credential pool still
+ # serves (and rotates on) the frozen endpoint.
+ # Same resolution-time walker the in-process one-shot used (#81209): an AuthError
+ # from the frozen primary (expired token, Portal down, exhausted pool) tries the
+ # route's own ``fallback_providers`` before the turn is refused. Only a launch URL is
+ # explicit (classic one-shot parity): the frozen ``model.base_url`` is resolved by
+ # the provider chain, which keeps the credential pool an explicit URL would drop.
+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,
+ explicit_api_key=key, explicit_base_url=launch_url, target_model=policy.model)
+ else:
+ fallback_entry = None
+ if fallback_entry is not None:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ runner._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ policy.provider or '', policy.model or '',
+ runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
+ fallback_entry.get('model') or 'default')
+ return fallback_entry['model'], _runtime_agent_kwargs(runtime)
+ return policy.model, _runtime_agent_kwargs(runtime)
+
+
+def _recover_or_remember_model(runner, skey, model):
+ """Last step of ``_resolve_session_agent_runtime``: remember a good model, recover an empty one."""
+ # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and
+ # the session goes silent — reuse the last model resolved for this session, else process-wide.
+ if not model:
+ _lr_state = runner._peek_session_state(skey) if skey else None
+ _lr_star = runner._peek_session_state("*")
+ _recovered = (
+ (_lr_state.conversation.last_resolved_model if _lr_state else "")
+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")
+ )
+ if _recovered:
+ logger.warning(
+ "Empty model resolved for session=%s — recovering "
+ "last-known-good model %s (config read likely returned "
+ "empty; see #35314)", skey or "", _recovered,
+ )
+ model = _recovered
+ else:
+ # Cache the good resolution for future recovery turns.
+ if skey:
+ runner._session_state(skey).conversation.last_resolved_model = model
+ runner._session_state("*").conversation.last_resolved_model = model
+ return model
+
+
+class GatewayTurnPrepareMixin:
+ def _resolve_session_agent_runtime(
+ self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,
+ user_config: Optional[dict] = None,
+ ) -> tuple[str, dict]:
+ """Resolve model/runtime for a session.
+
+ Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env
+ (``_resolve_gateway_model(user_config)`` and default provider resolution)."""
+ from gateway.run import (
+ _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,
+ _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,
+ )
+ from gateway.session_policy import policy_for_source
+ # Every exit path starts clean: a stale notice must never attach to another session's next
+ # turn (#74349). Set again below only when THIS resolution fell back.
+ self._pre_agent_fallback_notice = None
+ policy = policy_for_source(self, source) if source is not None else None
+ if policy is not None:
+ return _resolve_policy_agent_runtime(self, policy)
+ skey = self._resolve_session_key_or_none(source, session_key)
+ model = _resolve_gateway_model(user_config)
+ if skey:
+ self._rehydrate_session_model_override(skey)
+ _override_state = self._peek_session_state(skey) if skey else None
+ override = _override_state.conversation.model_override if _override_state else None
+ if override:
+ override_model = override.get("model", model)
+ override_runtime = {
+ k: override.get(k) for k in (
+ "provider", "requested_provider", "api_key", "base_url", "api_mode",
+ "max_tokens", "credential_pool", "request_overrides", "capabilities",
+ )
+ }
+ override_runtime["capabilities"] = dict(override_runtime["capabilities"] or {})
+ if override_runtime.get("api_key"):
+ if override_runtime.get("credential_pool") is None:
+ override_runtime["credential_pool"] = _credential_pool_for_provider(override.get("provider"))
+ logger.debug(
+ "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",
+ skey or "", model, override_model, override_runtime.get("provider"),
+ )
+ return override_model, override_runtime
+ # No api_key on the override (credentials failed to re-resolve at rehydrate): resolve them
+ # for the override's own provider below, never layer it over the default provider's runtime.
+ logger.debug(
+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",
+ skey or "", model, override_model,
+ )
+ elif logger.isEnabledFor(logging.DEBUG):
+ # The override_keys scan walks every session; only pay for it when DEBUG is on.
+ logger.debug(
+ "No session model override: session=%s config_model=%s override_keys=%s",
+ skey or "", model,
+ [
+ _key for _key, _st in list(self._sessions_map().items())
+ if _st.conversation.model_override is not None
+ ][:5] or "[]",
+ )
+
+ runtime_kwargs, unavailable_override = None, None
+ if override and override.get("provider"):
+ try:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(
+ override["provider"], target_model=override.get("model") or None)
+ except Exception as exc:
+ # Layering the override on the default runtime sent its model to the default provider's
+ # endpoint (openai-codex on the Nous URL). Run this turn on the whole default route and say
+ # so; the persisted override is kept, so the next turn retries it.
+ logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc,
+ exc_info=True)
+ unavailable_override, override = override, None
+ if runtime_kwargs is None:
+ runtime_kwargs = _resolve_runtime_agent_kwargs()
+ # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn
+ # runner surfaces it through the agent's one-shot fallback notice (#74349).
+ self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)
+ runtime_model = runtime_kwargs.pop("model", None)
+ if runtime_model:
+ logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)
+ model = runtime_model
+ if unavailable_override and not self._pre_agent_fallback_notice:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ unavailable_override["provider"], unavailable_override.get("model"), runtime_kwargs.get("provider"), model)
+
+ cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners
+ if cfg and source is not None:
+ ch = _get_channel_override(
+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",
+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,
+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,
+ )
+ if ch:
+ if ch.model:
+ model = ch.model
+ if ch.provider:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)
+ ch_runtime_model = runtime_kwargs.pop("model", None)
+ # Adopt the provider's bundled model only when the override named none.
+ if ch_runtime_model and not ch.model:
+ model = ch_runtime_model
+
+ if override and skey:
+ model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)
+
+ # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the
+ # provider's first catalog model.
+ if not model and runtime_kwargs.get("provider"):
+ with suppress(Exception):
+ from hermes_cli.models import get_default_model_for_provider
+ model = get_default_model_for_provider(runtime_kwargs["provider"])
+ if model:
+ logger.info(
+ "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],
+ )
+
+ return _recover_or_remember_model(self, skey, model), runtime_kwargs
+
+ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:
+ """Effective model/runtime config for one turn. With `/fast` priority on, fast-mode
+ ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""
+ from gateway.run import _deep_merge_request_overrides
+ from agent.fast_mode import STATIC_TIERS
+ from hermes_cli.models import resolve_fast_mode_overrides
+ # Tests bind this method onto bare namespaces, so no class-level tables here.
+ runtime = {
+ k: runtime_kwargs.get(k) for k in (
+ "api_key", "base_url", "provider", "requested_provider", "api_mode", "command", "args",
+ "credential_pool", "max_tokens", "capabilities",
+ )
+ }
+ runtime["args"] = list(runtime["args"] or [])
+ runtime["capabilities"] = dict(runtime["capabilities"] or {})
+ base_request_overrides = dict(runtime_kwargs.get("request_overrides") or {})
+ route = {
+ "model": model,
+ "runtime": runtime,
+ "signature": (
+ model, runtime["provider"], runtime["requested_provider"], runtime["base_url"],
+ runtime["api_mode"], runtime["command"], tuple(runtime["args"]),
+ ),
+ }
+ tier = getattr(self, "_service_tier", None)
+ if tier not in STATIC_TIERS:
+ # None / auto / cold: the bounded window is applied per request by agent.fast_mode.
+ route["request_overrides"] = base_request_overrides
+ return route
+ try:
+ overrides = resolve_fast_mode_overrides(
+ route["model"], provider=runtime["provider"], base_url=runtime["base_url"], tier=tier,
+ )
+ except Exception:
+ overrides = None
+ # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.
+ route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})
+ return route
+
+ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:
+ """Persist the runtime model/provider a gateway turn actually used (provider fallback can
+ switch them after the row was created). Runs in the ``run_sync`` executor thread, so it
+ uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""
+ if not session_id or agent is None or self._session_db is None:
+ return
+ model = getattr(agent, "model", None)
+ if not model:
+ return
+ runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}
+ runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))
+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}
+ try:
+ db = self._session_db._db
+ row = db.get_session(session_id)
+ if not row:
+ return
+ # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed
+ # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity
+ # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact
+ # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without
+ # this, every Bot Chat that already exists in the field stays pinned to its stale stored
+ # provider until the user deletes it — the exact live-report shape (#89497 / #94818).
+ raw_config = row.get("model_config")
+ config = {}
+ with suppress(Exception):
+ config = json.loads(raw_config) if raw_config else {}
+ if not isinstance(config, dict):
+ config = {}
+ gateway_runtime = dict(config.get("gateway_runtime") or {})
+ if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):
+ return
+ config["gateway_runtime"] = runtime
+ db.update_session_meta(session_id, json.dumps(config), model=model)
+ except Exception:
+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)
+
+ async def _hmwa_resolve_session(self, event, source):
+ """Resolve ``source`` to its session entry (topic recovery, internal-route guards, Telegram
+ topic-binding heal). Returns ``(source, session_entry, session_key)`` or ``None`` to drop
+ the event."""
+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a
+ # cross-topic Reply doesn't fragment the conversation.
+ event_metadata = getattr(event, "metadata", None) or {}
+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()
+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ if not expected_session_key else None)
+ if recovered is not None:
+ logger.info(
+ "telegram topic recovery: chat=%s user=%s %r -> %s",
+ source.chat_id, source.user_id, source.thread_id, recovered,
+ )
+ source = dataclasses.replace(source, thread_id=recovered)
+ with suppress(Exception):
+ event.source = source
+
+ if expected_session_key:
+ derived_session_key = self._session_key_for_source(source)
+ if derived_session_key != expected_session_key:
+ logger.warning(
+ "Dropping internally routed event after route recovery: expected session=%s derived=%s",
+ expected_session_key, derived_session_key,
+ )
+ return
+
+ strict_session = bool(event_metadata.get("gateway_session_strict"))
+ pinned_session_id = str(event_metadata.get("gateway_session_id") or "").strip()
+ if strict_session:
+ session_entry = await self.async_session_store.lookup_by_session_key(expected_session_key)
+ if session_entry is None or not pinned_session_id or session_entry.session_id != pinned_session_id:
+ logger.warning(
+ "Dropping internally routed event: expected session id=%s is no longer current for key=%s",
+ pinned_session_id or "missing", expected_session_key or "missing",
+ )
+ return
+ else:
+ # Internal wakes observe reset policy without counting as user activity, or periodic
+ # notifications keep the routing key alive across every daily/idle boundary.
+ session_entry = await self.async_session_store.get_or_create_session(
+ source, touch_activity=not bool(getattr(event, "internal", False)),
+ )
+ session_key = session_entry.session_key
+ if not strict_session and pinned_session_id:
+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id)
+ if resolved_entry is None:
+ return
+ session_entry = resolved_entry
+ self._cache_session_source(session_key, source)
+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):
+ session_entry = await self._hmwa_heal_telegram_topic_binding(source, session_entry, session_key)
+ from gateway.run_heartbeat_acceptance import resolve_heartbeat_owner
+ if not await resolve_heartbeat_owner(self, event, session_entry):
+ return
+ return source, session_entry, session_key
+
+ async def _hmwa_heal_telegram_topic_binding(self, source, session_entry, session_key):
+ """Follow the (chat_id, thread_id) topic binding — healed to its compression tip — or record
+ a fresh one. Returns the (possibly switched) session entry."""
+ binding = None
+ try:
+ if self._session_db:
+ binding = await self._session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),
+ profile_name=self._telegram_topic_profile_name(source),
+ )
+ except Exception:
+ logger.debug("Failed to read Telegram topic binding", exc_info=True)
+ if not binding:
+ try:
+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)
+ except Exception:
+ logger.debug("Failed to record Telegram topic binding", exc_info=True)
+ return session_entry
+ stored_session_id = str(binding.get("session_id") or "")
+ bound_session_id = stored_session_id
+ # A binding pointing at a pre-compression parent is walked forward to the tip so the next
+ # message resumes the compressed child instead of reloading the oversized parent.
+ # Returns the input unchanged when the session isn't a compression parent, so this is cheap and
+ # safe. See #20470, #29712, #33414.
+ if bound_session_id and self._session_db is not None:
+ try:
+ canonical_session_id = await self._session_db.get_compression_tip(bound_session_id)
+ except Exception:
+ logger.debug("compression-tip lookup failed for %s", bound_session_id, exc_info=True)
+ canonical_session_id = bound_session_id
+ if canonical_session_id and canonical_session_id != bound_session_id:
+ bound_session_id = canonical_session_id
+ if bound_session_id and bound_session_id != session_entry.session_id:
+ # Route through SessionStore so the key → id mapping persists and the previous lane
+ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB
+ # awaits above are a window for /new or /resume to move the route; the CAS on the
+ # snapshot id lets that win instead of being clobbered by a stale binding.
+ switched = await self.async_session_store.switch_session(
+ session_key, bound_session_id, expected_session_id=session_entry.session_id,
+ )
+ if switched is not None:
+ session_entry = switched
+ if bound_session_id and bound_session_id != stored_session_id:
+ # The stored binding pointed at a parent: rewrite it to the canonical descendant.
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-tip-walk",
+ )
+ return session_entry
+
+ async def _hmwa_open_session(self, session_entry, session_key, source):
+ """Consume auto-reset / fresh-reset flags and emit ``session:start`` for new sessions.
+ Returns ``(_was_auto_reset, _is_new_session)``."""
+ # Capture and immediately consume was_auto_reset so it does not re-fire on subsequent messages —
+ # preventing the cleanup from wiping model/reasoning overrides set between turns (Closes #48031).
+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)
+ if _was_auto_reset:
+ # Conversation boundary: the funnel clears every conversation-scoped dict; evict the cached
+ # agent so context_compressor._previous_summary cannot leak into new summaries.
+ # Treat auto-reset as a full conversation boundary — clear every conversation-scoped per-session
+ # dict in one funnel call so the fresh session does not inherit the previous conversation's
+ # model/reasoning overrides, a queued "/model switched" note, or a stale resolved-model cache
+ # (#48031, #58403). See _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(session_key, reason="auto_reset")
+ self._evict_cached_agent(session_key)
+ session_entry.was_auto_reset = False
+
+ _is_fresh_reset = getattr(session_entry, "is_fresh_reset", False)
+ _is_new_session = session_entry.created_at == session_entry.updated_at or _was_auto_reset or _is_fresh_reset
+ # Consume is_fresh_reset so it doesn't leak onto later messages in the same session.
+ if _is_fresh_reset:
+ # See #6508.
+ session_entry.is_fresh_reset = False
+ if _is_new_session:
+ await self.hooks.emit("session:start", {
+ "platform": source.platform.value if source.platform else "",
+ "user_id": source.user_id,
+ "session_id": session_entry.session_id,
+ "session_key": session_key,
+ })
+ return _was_auto_reset, _is_new_session
+
+ async def _hmwa_deliver_auto_reset_notice(self, session_entry, source, turn_sidecar_notes):
+ """Stage the auto-reset sidecar note for the agent and notify the user (policy-gated)."""
+ from gateway.run import _AUTO_RESET_CONTEXT_NOTES
+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'suspended'
+ context_note = _AUTO_RESET_CONTEXT_NOTES.get(reset_reason, _AUTO_RESET_CONTEXT_NOTES["suspended"])
+ # Long-lived channels: point the agent at the prior same-channel session for session_search.
+ try:
+ # Returns None (appends nothing) for other platforms or when there's no prior activity to
+ # recall. Deterministic — no extra API/DB calls (#36220).
+ continuity_note = build_channel_continuity_note(session_entry, source)
+ except Exception:
+ continuity_note = None
+ if continuity_note:
+ context_note = context_note + "\n\n" + continuity_note
+ turn_sidecar_notes.append(context_note)
+
+ try:
+ should_notify = reset_reason == "suspended"
+ adapter = self._delivery_adapter_for(source) if should_notify else None
+ if adapter:
+ notice = t("gateway.session.auto_reset_notice")
+ with suppress(Exception):
+ session_info = await asyncio.to_thread(self._reset_notice_session_info, source)
+ if session_info:
+ notice = f"{notice}\n\n{session_info}"
+ await adapter.send(source.chat_id, notice, metadata=self._thread_metadata_for_source(source))
+ except Exception as e:
+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)
+
+ # was_auto_reset was consumed in _hmwa_open_session; only the reason needs clearing.
+ session_entry.auto_reset_reason = None
+
+ def _hmwa_auto_load_skills(self, event, _auto, _quick_key, session_key):
+ """Prepend topic/channel-bound skill payload(s) to ``event.text`` on a new session."""
+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)
+ try:
+ from agent.skill_commands import _load_skill_payload, _build_skill_message
+ _combined_parts: list[str] = []
+ _loaded_names: list[str] = []
+ for _sname in _skill_names:
+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)
+ if not _loaded:
+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)
+ continue
+ _loaded_skill, _skill_dir, _display_name = _loaded
+ _part = _build_skill_message(
+ _loaded_skill, _skill_dir,
+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '
+ f"Follow its instructions for this session.]",
+ )
+ if _part:
+ _combined_parts.append(_part)
+ _loaded_names.append(_sname)
+ if _combined_parts:
+ _combined_parts.append(event.text) # user's original text after the payloads
+ event.text = "\n\n".join(_combined_parts)
+ logger.info("[Gateway] Auto-loaded skill(s) %s for session %s", _loaded_names, session_key)
+ except Exception as e:
+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)
+
+ async def _hmwa_acquire_turn_lease(self, _quick_key, run_generation, session_entry, _session_env_tokens):
+ """Serialize [load history → run → flush] per resolved SESSION_ID so another routing key on
+ the same session waits for the prior flush. Fail-closed on timeout (outer dispatch returns
+ a resend notice). Released in _handle_message's finally, granted per (routing key, run
+ generation) so a stale unwind can't release a newer turn's."""
+ from gateway.run import _float_env
+ _lease_registry = getattr(self, "_turn_leases", None)
+ if _lease_registry is None:
+ return
+ try:
+ _lease_token = await _lease_registry.acquire(
+ session_entry.session_id, owner_key=_quick_key, generation=run_generation,
+ timeout=_float_env("HERMES_TURN_LEASE_TIMEOUT", DEFAULT_LEASE_WAIT),
+ )
+ except TurnLeaseTimeoutError:
+ # The cleanup finally starts later; restore the tokens here or this exit leaks identity.
+ self._clear_session_env(_session_env_tokens)
+ raise
+ if _lease_token is not None:
+ self._session_state(_quick_key).turn.lease_tokens[run_generation] = _lease_token
+
+ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes, message, internal=False):
+ """First-ever-message onboarding note + one-time 'no home channel' prompt (both only when
+ the session has no history). Delivered on the user message (sidecar), NOT the ephemeral
+ system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed prompt diff + rebuild."""
+ from gateway.run import _gateway_config_home, _home_target_env_var, _load_gateway_config
+ if history or internal: # internal = plugin/system turn: no human made first contact
+ return
+ # LOCAL sessions (one-shot, chat -q, ACP, TUI attach) are the classic in-process CLI's
+ # surfaces: it never appended this note, and mark_seen would rewrite config.yaml under
+ # an ordinary launch that promises to leave the profile's files untouched.
+ human_platform = bool(source.platform) and source.platform not in (Platform.LOCAL, Platform.WEBHOOK)
+ if human_platform and source.chat_type == "dm" and not await self.async_session_store.has_any_sessions():
+ # Same branch logic as the TUI (offer once when "ask", else plain intro);
+ # first_contact_turn_note already falls back to the plain intro on error.
+ from agent.onboarding import first_contact_turn_note, setup_command
+ note = first_contact_turn_note(
+ _load_gateway_config(), _gateway_config_home() / "config.yaml",
+ session_history_empty=True, install_has_prior_sessions=False, message=message,
+ command=setup_command(source.platform.value))
+ if note:
+ turn_sidecar_notes.append(note)
+
+ # One-time prompt if no home channel is set (webhooks deliver to configured targets instead).
+ if not human_platform:
+ return
+ platform_name = source.platform.value
+ env_key = _home_target_env_var(platform_name)
+ # Multiplex: the home channel may live only in the profile secret scope, not os.environ.
+ home_env = ""
+ if env_key:
+ # A secondary with no home channel must not borrow the default profile's from
+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.
+ from agent.secret_scope import UnscopedSecretError, get_secret
+ try:
+ home_env = (get_secret(env_key) or "").strip()
+ except UnscopedSecretError:
+ home_env = (os.getenv(env_key) or "").strip()
+ except Exception:
+ logger.debug("Home-channel secret %s unreadable; treating it as unset", env_key, exc_info=True)
+ home_env = ""
+ # Also honor in-memory / yaml home_channel on this platform.
+ with suppress(Exception):
+ if not home_env and self.config.get_home_channel(source.platform):
+ home_env = "set"
+ # Secondary-profile platforms may only exist under that profile's config — re-read in scope.
+ if not home_env:
+ with suppress(Exception):
+ from gateway.config import load_gateway_config as _lgc
+ prof = (getattr(source, "profile", None) or "").strip()
+ if prof and prof != "default" and _lgc().get_home_channel(source.platform):
+ home_env = "set"
+ if not home_env:
+ # Slack routes every command through the parent `/hermes`; bare `/sethome` would fail.
+ sethome_cmd = "/hermes sethome" if source.platform == Platform.SLACK else "/sethome"
+ await self._deliver_platform_notice(
+ source, t("gateway.notify.no_home_channel", platform=platform_name.title(), sethome_cmd=sethome_cmd),
+ )
+
+ def _hmwa_apply_message_timestamp(self, event, message_text):
+ """Capture the platform event time as message metadata and keep the persisted transcript
+ clean — strip any leading timestamp prefix and the Discord triggering-message note (a
+ model instruction, not authored text) — regardless of the toggle; only the in-context
+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""
+ from gateway.run import _load_gateway_config, _message_timestamps_enabled
+ from gateway.run_inbound import strip_discord_triggering_note
+ persist_user_message = None
+ persist_user_timestamp = None
+ try:
+ from hermes_time import get_timezone as _get_evt_tz
+ from gateway.message_timestamps import (
+ coerce_message_timestamp as _coerce_msg_ts,
+ render_user_content_with_timestamp as _render_msg_ts,
+ strip_leading_message_timestamps as _strip_msg_ts,
+ )
+ _evt_tz = _get_evt_tz()
+ if message_text and isinstance(message_text, str):
+ _clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)
+ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)
+ _event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)
+ persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_ts
+ if _message_timestamps_enabled(_load_gateway_config()):
+ message_text = _render_msg_ts(_clean_message_text, persist_user_timestamp, tz=_evt_tz)
+ else:
+ # Toggle off: the model sees the clean message; timestamp stored for later opt-in.
+ message_text = _clean_message_text
+ except Exception as _ts_err:
+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)
+ return message_text, persist_user_message, persist_user_timestamp
+
+ @dataclasses.dataclass
+ class _PreparedTurn:
+ """Inputs to the agent run assembled by ``_hmwa_prepare_turn``."""
+
+ history: Any
+ context_prompt: str
+ message_text: Any
+ persist_user_message: Any
+ persist_user_timestamp: Any
+ persist_user_display_kind: Optional[str]
+ persistence_session_id: Optional[str] = None
+ persistence_owner: Optional[str] = None
+ title_user_message: Optional[str] = None
+
+ async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):
+ """Everything between session resolution and the agent run: session open, task-local env,
+ context prompt, sidecar notes, turn lease, transcript load + hygiene, inbound text. Returns
+ ``(_PreparedTurn, env_tokens)``; a ``str`` first element is a reply to send instead of
+ running (history unreadable); ``None`` drops the turn (inbound text rejected)."""
+ from gateway.run import _load_gateway_config
++ from tools.approval_yolo import restore_session_yolo
+ _was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)
- self._restore_session_yolo(session_key, session_entry)
++ restore_session_yolo(session_key, session_entry.yolo is True) # a restarted gateway's set starts empty
+ context = build_session_context(source, self.config, session_entry)
+ # Session context variables for tools (task-local, concurrency-safe)
+ _session_env_tokens = self._set_session_env(context)
- # Self-injected turns (MessageEvent(internal=True)) persist with a DB-only display_kind so
- # UIs render timeline notices, not user bubbles; role/content untouched.
++ # Self-injected turns (internal=True) persist with a DB-only display_kind: timeline notices, not user bubbles.
+ from gateway.response_filters import display_kind_for_event
+ persist_user_display_kind = display_kind_for_event(event)
+ _redact_pii = False # privacy.redact_pii, re-read per message
+ with suppress(Exception):
+ _redact_pii = bool((_load_gateway_config().get("privacy") or {}).get("redact_pii", False))
+
+ # The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so
+ # the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.
+ # A LOCAL session (CLI one-shot, ACP, cron run-now, TUI attach) is the operator's own machine:
+ # the messaging block ("Source: Local", connected platforms, cron delivery targets) was never
+ # part of the classic in-process prompt, and the TUI gateway still builds that prompt in-process.
+ # Rendering it here would make every surface hop of one durable session a system-prompt
+ # (and prompt-cache) break.
+ if source.platform != Platform.LOCAL and event.internal and session_key:
+ await self._rehydrate_prompt_pins(session_key, session_entry.session_id)
+ context_prompt = "" if source.platform == Platform.LOCAL else \
+ self._pinned_session_context_prompt(context, _redact_pii, session_key, internal=event.internal)
+
+ # Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
+ # (appending to the ephemeral system prompt forced a full agent rebuild).
+ turn_sidecar_notes: List[str] = []
+ if _was_auto_reset:
+ await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)
+
+ # Keep human text separate from skills, sender metadata, and other model context.
+ # With no text (e.g. voice-only), retain the existing enriched-message title fallback.
+ title_user_message = event.text or None
+
+ # Auto-load bound skill(s) only on NEW sessions; ongoing ones carry the content in history.
+ _auto = getattr(event, "auto_skill", None)
+ if _is_new_session and _auto:
+ self._hmwa_auto_load_skills(event, _auto, _quick_key, session_key)
+
+ await self._hmwa_acquire_turn_lease(_quick_key, run_generation, session_entry, _session_env_tokens)
+
+ # A turn becomes durable recovery work only after it owns the per-session lease; marking
+ # earlier would falsely recover a message that never began processing.
+ await self._mark_durable_active_turn(event, session_entry.session_key)
+
+ # An unreadable store is not an empty conversation: stop before the agent invents continuity
+ # from []. Restore task-local context here (before the broad cleanup finally).
+ try:
+ history = await self.async_session_store.load_transcript(session_entry.session_id)
+ history = await self._hmwa_run_session_hygiene(
+ event, source, session_entry, session_key, history, _quick_key, run_generation,
+ )
+ except TranscriptReadError:
+ self._clear_session_env(_session_env_tokens)
+ from gateway.session_results import record_unexecuted_failure
+ return record_unexecuted_failure(t("gateway.errors.history_unavailable")), _session_env_tokens
+
+ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, event.text, internal=event.internal)
+
+ # Voice channel state rides the user message ONLY when changed (in the system prompt it
+ # forced a rebuild + prompt-cache re-key per message).
+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)
+ if _vc_note:
+ turn_sidecar_notes.append(_vc_note)
+
+ # Auto-analyze user images so the model gets a description plus the local path.
+ message_text = await self._prepare_profile_scoped_inbound_message_text(
+ event=event, source=source, history=history, session_key=session_key,
+ )
+ if message_text is None:
+ return None, _session_env_tokens
+
+ message_text, persist_user_message, persist_user_timestamp = (
+ self._hmwa_apply_message_timestamp(event, message_text)
+ )
+
+ # Stage the notes (one-shot; consumed in run_sync) AFTER the early-out so an aborted turn
+ # cannot leak them into the next turn.
+ if turn_sidecar_notes and session_key:
+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)
+
+ # Bind this run generation to the adapter so deferred post-delivery callbacks are released
+ # by the run that registered them.
+ self._bind_adapter_run_generation(self._delivery_adapter_for(source), session_key, run_generation)
+ # Delivery IDs are only unique in their transport namespace. Keyless turns
+ # need their own identity, even when another process writes to this session.
+ import uuid
+ namespace = [source.platform.value, source.profile, source.scope_id,
+ source.chat_id, source.thread_id, str(event.message_id)]
+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))
+ if event.message_id else str(uuid.uuid4()))
+ return self._PreparedTurn(
+ history, context_prompt, message_text, persist_user_message, persist_user_timestamp,
+ persist_user_display_kind, session_entry.session_id, owner,
+ title_user_message=title_user_message,
+ ), _session_env_tokens
diff --cc gateway/run_turn_runner.py
index c84203e2231,f8e8d09e257..7e79b53f53c
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@@ -1082,19 -1902,9 +1082,19 @@@ class TurnRunner(GatewayTurnProgressMix
# session via contextvars (set_current_session_key / session context), and only the TUI slash-worker
# *subprocess* exports HERMES_SESSION_KEY (from its own --session-key argv, a separate process) — so
# removing this in-process gateway write does not affect any of them.
- platform_key = "cli" if ctx.source.platform == Platform.LOCAL else ctx.source.platform.value
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(runner, ctx.source)
+ if policy and policy.yolo and ctx.session_key:
- from tools.approval import apply_launch_yolo
++ from tools.approval_yolo import apply_launch_yolo
+ apply_launch_yolo(ctx.session_key)
+ platform_key = policy.platform if policy else ("cli" if ctx.source.platform == Platform.LOCAL else ctx.source.platform.value)
combined_ephemeral = self._combined_ephemeral_prompt()
- max_iterations = _current_max_iterations()
+ max_iterations = policy.max_turns if policy else _current_max_iterations()
+ from gateway.hosted_room_execution_policy import current_room_execution_policy
+ room = current_room_execution_policy()
+ if room is not None:
+ max_iterations = room.max_iterations
+ ctx.enabled_toolsets = list(room.enabled_toolsets)
try:
model, runtime_kwargs = runner._resolve_session_agent_runtime(
source=ctx.source, session_key=ctx.session_key, user_config=ctx.user_config,
diff --cc gateway/session_busy_controls.py
index e39fc938216,00000000000..f979d206b1e
mode 100644,000000..100644
--- a/gateway/session_busy_controls.py
+++ b/gateway/session_busy_controls.py
@@@ -1,127 -1,0 +1,132 @@@
+"""Session-scoped busy preferences and controls of the existing execution only."""
++import asyncio
+from functools import partial
+from pathlib import Path
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+def handlers(connection):
+ return {
+ 'config.get': partial(busy_config, connection),
+ 'config.set': partial(busy_config, connection, write=True),
+ 'session.steer': partial(correct, connection, verb='steer'),
+ 'session.redirect': partial(correct, connection, verb='redirect'),
+ }
+
+
+def authorize(connection, ref, params, capability):
+ connection.authority.authorize(connection.actor, ref, capability)
+ if 'profile' in params:
+ from hermes_cli.profiles import profile_matches_home
+ profile = params['profile']
+ if not isinstance(profile, str):
+ raise RuntimeStoreError('invalid_params')
+ if profile and not profile_matches_home(profile, Path(connection.authority.profile_id)):
+ raise RuntimeStoreError('profile_mismatch')
+
+
+async def busy_config(connection, ref, params, *, write=False):
+ allowed = {'session_id', 'profile', 'key'} | ({'value'} if write else set())
+ if params.get('key') == 'verbose' and not set(params) - allowed and ref.session_id:
+ return verbose_config(connection, ref, params, write)
+ if params.get('key') == 'yolo' and not set(params) - allowed and ref.session_id:
+ return await yolo_config(connection, ref, params, write)
+ if (set(params) - allowed or not ref.session_id or params.get('key') != 'busy'
+ or (write and params.get('value') not in ('interrupt', 'steer', 'queue'))):
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ authority = connection.authority
+ live = authority.sessions[ref.session_id]
+ if write:
+ # UI negotiation is not a settings write and must not rebuild frozen
+ # launch policy, toolsets, history, or the retained AIAgent.
+ live.busy_input_mode = params['value']
+ value = getattr(live, 'busy_input_mode', None)
+ if value is None:
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(authority.runner, live.source)
+ value = (policy.config().get('display', {}).get('busy_input_mode', 'interrupt') if policy else
+ authority.runner._effective_busy_input_mode(live.source))
+ if value not in ('interrupt', 'steer', 'queue'):
+ value = 'interrupt'
+ return {'key': 'busy', 'value': value, 'scope': 'session'}
+
+
+_VERBOSE_CYCLE = ('off', 'new', 'all', 'verbose')
+
+
+def verbose_config(connection, ref, params, write):
+ """Session-scoped /verbose: the tool-progress mode the next tool events of
+ this session render with (read by TurnRunner), like busy never a settings write."""
+ value = params.get('value')
+ if write and value not in (*_VERBOSE_CYCLE, 'cycle'):
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ live = connection.authority.sessions[ref.session_id]
+ current = getattr(live, 'tool_progress_mode', None) or 'all'
+ if write:
+ live.tool_progress_mode = current = (
+ _VERBOSE_CYCLE[(_VERBOSE_CYCLE.index(current) + 1) % 4] if value == 'cycle' else value)
+ return {'key': 'verbose', 'value': current, 'scope': 'session'}
+
+
+_YOLO_WORDS = {'1': True, 'on': True, 'true': True, '0': False, 'off': False, 'false': False}
+
+
+async def yolo_config(connection, ref, params, write):
+ """Session-scoped /yolo (TUI slash + Shift+Tab, Desktop toggle): this session's approval bypass,
+ never HERMES_YOLO_MODE or approvals.mode. A ``--yolo`` launch is seeded first, so revoking it
- here is not re-enabled by the next turn's launch seeding. The route's persisted copy
- (``SessionEntry.yolo``, re-armed every turn by ``_restore_session_yolo``) is written before the
- live flag, like the messaging ``/yolo``, so an OFF here is not revived by the next turn."""
++ here is not re-enabled by the next turn's launch seeding. The write goes through the shared
++ ``tools.approval_yolo.toggle_session_yolo`` contract on the route's persisted copy
++ (``SessionEntry.yolo``, re-armed every turn by ``restore_session_yolo``), like the messaging
++ ``/yolo``: persisted before the live flip, so an OFF here is not revived by the next turn."""
+ value = params.get('value')
+ if write and value is not None and str(value).strip().lower() not in _YOLO_WORDS:
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control' if write else 'session:read')
+ from gateway.session_policy import policy_for_source
- from tools.approval import apply_launch_yolo, disable_session_yolo, enable_session_yolo, is_session_yolo_enabled
++ from tools.approval import is_session_yolo_enabled
++ from tools.approval_yolo import apply_launch_yolo, toggle_session_yolo
+ live = connection.authority.sessions[ref.session_id]
+ runner = connection.authority.runner
+ policy = policy_for_source(runner, live.source)
+ if policy is not None and policy.yolo:
+ apply_launch_yolo(live.route)
- store = runner.async_session_store if getattr(runner, 'session_store', None) is not None else None
- entry = await store.lookup_by_session_key(live.route) if store is not None else None
++ store = getattr(runner, 'session_store', None)
++ entry = await runner.async_session_store.lookup_by_session_key(live.route) if store is not None else None
+ # After a restart only the persisted copy is set until the next turn re-arms it: still ON.
- enabled = is_session_yolo_enabled(live.route) or getattr(entry, 'yolo', False) is True
++ persisted = getattr(entry, 'yolo', False) is True
++ enabled = is_session_yolo_enabled(live.route) or persisted
+ if write:
- enabled = not enabled if value is None else _YOLO_WORDS[str(value).strip().lower()]
- if store is not None:
- await store.set_session_yolo(live.route, enabled)
- (enable_session_yolo if enabled else disable_session_yolo)(live.route)
++ persist = (lambda on: store.set_session_yolo(live.route, on)) if store is not None else None
++ # Off the loop: the persist is a routing-store write (thread-safe), as in the messaging /yolo.
++ enabled = await asyncio.to_thread(
++ toggle_session_yolo, live.route, None if value is None else _YOLO_WORDS[str(value).strip().lower()],
++ persisted=persisted, persist=persist)
+ return {'key': 'yolo', 'value': '1' if enabled else '0', 'scope': 'session'}
+
+
+async def correct(connection, ref, params, *, verb):
+ if (set(params) - {'session_id', 'profile', 'text', 'execution_generation'}
+ or not isinstance(params.get('text'), str) or not params['text'].strip()
+ or type(params.get('execution_generation')) is not int):
+ raise RuntimeStoreError('invalid_params')
+ authorize(connection, ref, params, 'session:control')
+ authority = connection.authority
+ generation = params['execution_generation']
+ live = authority.sessions[ref.session_id]
+ with live.event_stream.lock:
+ authority.check_approval_generation(ref.session_id, generation)
+ # Managed workers have a separate control channel, not a cached owner
+ # agent. Refuse explicitly instead of acknowledging undeliverable text.
+ if ref.session_id in getattr(authority, '_managed_workers', {}):
+ raise RuntimeStoreError('unsupported_control')
+ agent = authority.agent(ref)
+ method = getattr(agent, verb, None)
+ if not callable(method):
+ raise RuntimeStoreError('execution_not_ready')
+ accepted = method(params['text'])
+ return {'status': ({'steer': 'queued', 'redirect': 'redirected'}[verb] if accepted else 'rejected'),
+ 'text': params['text'], 'execution_generation': generation,
+ 'authority_epoch': authority.epoch}
diff --cc gateway/session_managed_worker.py
index 75b7dcb86b6,00000000000..81102f6f72d
mode 100644,000000..100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@@ -1,372 -1,0 +1,372 @@@
+"""Admission-owned production exec; observers never own the worker lifetime."""
+import asyncio
+from contextlib import contextmanager
+from dataclasses import asdict, replace
+import json
+import queue
+import threading
+from types import SimpleNamespace
+from pathlib import Path
+import subprocess
+import sys
+
+from agent.managed_worker import accept_result, encode_frame, read_frame
+from gateway.session_worker_reservation import reserve_admission_worker
+from hermes_state_runtime import RuntimeStoreError
+
+# The interpreter only imports psutil before it introduces itself; a child silent this long
+# is wedged (loader/stdio stall), not slow.
+HELLO_SECONDS = 60
+# After Stop the child interrupts its agent and emits its result; the owner terminates a
+# child that has not acknowledged within this window instead of waiting on the pipe forever.
+STOP_ACK_SECONDS = 30
+
+
+def managed_policy(authority, ref):
+ """Bypass (safe / config-only) sessions always execute out of process; other local
+ sessions only under the explicit custom-provider opt-in.
+
+ The frozen creation snapshot, not current profile config, chooses execution.
+ """
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)
+ if policy is None:
+ return None
+ if policy.ignore_user_config or policy.kanban_json is not None:
+ return policy
+ if policy.config().get('gateway', {}).get('managed_workers') is not True:
+ return None
+ request = json.loads(policy.request_json)
+ if policy.source != 'cli' or request.get('provider') != 'custom' or not request.get('base_url'):
+ raise RuntimeStoreError('unsupported_managed_policy')
+ return policy
+
+
+def _bootstrap(authority, ref, row, policy, scope):
+ from gateway.session_ingress import row_turn_author
+ from gateway.session_policy import launch_key
+ from gateway.session_policy_credentials import recover_config_secrets
+ terminal = json.loads(policy.terminal_json)
+ if policy.config_secret_ref:
+ for path, value in recover_config_secrets(authority, policy).items():
+ if path[0] is None:
+ terminal[path[1]] = value
+ live = authority.sessions[ref.session_id]
+ # This turn's facts ride the per-turn hydrated request (the bootstrap field set is closed):
+ # the admission's one-shot flags and the route's YOLO as of now, never the frozen launch flag.
+ request = dict(json.loads(policy.request_json), turn_v1={
+ 'finite': row['payload'].get('finite', False), 'unattended': row['payload'].get('unattended') is True,
+ 'yolo': _session_yolo(authority, live.route, policy)})
+ hydrated = replace(policy, config_json=json.dumps(policy.config(authority)), request_json=json.dumps(request),
+ terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)
+ return {'version': 1, 'home': authority.profile_id, 'scope': scope,
+ 'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),
+ 'text': row['payload']['text'], 'route': live.route,
+ **({'attachments_v1': row['payload']['attachments_v1']} if 'attachments_v1' in row['payload'] else {}),
+ 'user_id': live.source.user_id, 'chat_id': live.source.chat_id,
+ 'turn_author': row_turn_author(policy, row),
+ 'safe_mode': policy.safe_mode, 'ignore_user_config': policy.ignore_user_config}
+
+
+def _session_yolo(authority, route, policy):
+ """The route's bypass as the in-process turn arms it on the owner, the one place a revocation
+ is recorded: a ``--yolo`` launch seeded once per boundary, then the persisted ``/yolo`` copy."""
- from gateway.run_agent_cache import GatewayAgentCacheMixin
- from tools.approval import apply_launch_yolo, is_session_yolo_enabled
++ from tools.approval import is_session_yolo_enabled
++ from tools.approval_yolo import apply_launch_yolo, restore_session_yolo
+ if policy.yolo:
+ apply_launch_yolo(route)
+ store = getattr(authority.runner, 'session_store', None)
+ if store is not None:
- GatewayAgentCacheMixin._restore_session_yolo(route, store.lookup_by_session_key(route))
++ restore_session_yolo(route, getattr(store.lookup_by_session_key(route), 'yolo', False) is True)
+ return is_session_yolo_enabled(route)
+
+
+@contextmanager
+def worker_turn_scope(frame):
+ """Child side of ``turn_v1``: bind what the in-process turn binds on the owner
+ (execute_finite_admission, the route's YOLO), so ``chat -q``/``-z`` never park a prompt and
+ the session's current YOLO governs this child. Frames without it bind nothing."""
+ from gateway.session_finite import finite_turn_scope
+ turn = json.loads(frame['policy'].get('request_json') or '{}').get('turn_v1')
+ if turn is None:
+ yield
+ return
+ if (not isinstance(turn, dict) or set(turn) != {'finite', 'unattended', 'yolo'}
+ or any(type(v) is not bool for v in turn.values()) or (turn['unattended'] and not turn['finite'])):
+ raise ValueError('invalid_managed_worker_bootstrap')
+ if turn['yolo']:
+ from tools.approval import enable_session_yolo
+ enable_session_yolo(frame['route'])
+ with finite_turn_scope(turn['finite'], turn['unattended']):
+ yield
+
+
+class ManagedWorker:
+ def __init__(self, process):
+ self.process = process
+ # Verified interpreter behind the handle (a launcher trampoline may sit between).
+ self.worker = None
+ self.write_lock = threading.Lock()
+ self.commands = queue.Queue(maxsize=16)
+ self.closed = threading.Event()
+ # Latched the moment Stop is admitted, before any pipe write: the owner's read loop
+ # supervises it even while the child has not yet said hello or read its bootstrap.
+ self.stop = asyncio.Event()
+ self.writer = threading.Thread(target=self._write_controls, name='managed-control-writer', daemon=True)
+
+ def _write_controls(self):
+ try:
+ while not self.closed.is_set():
+ try:
+ frame = self.commands.get(timeout=.5)
+ except queue.Empty:
+ continue
+ self.send(frame)
+ except (OSError, ValueError):
+ self.closed.set()
+
+ def control(self, frame):
+ if self.closed.is_set():
+ raise RuntimeStoreError('managed_worker_lost')
+ if frame == {'type': 'stop'}:
+ self.stop.set()
+ try:
+ self.commands.put_nowait(frame)
+ except queue.Full as exc:
+ raise RuntimeStoreError('worker_control_backpressure') from exc
+
+ async def next_frame(self, timeout, ack):
+ """Read one frame. A requested Stop bounds the wait to ``ack`` seconds (zero before the
+ child can receive controls) and, unanswered, escalates instead of leaving the turn
+ started behind a silent-but-alive child."""
+ reader = asyncio.ensure_future(asyncio.to_thread(read_frame, self.process.stdout))
+ stopper = asyncio.ensure_future(self.stop.wait())
+ try:
+ done, _ = await asyncio.wait({reader, stopper}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
+ if reader not in done and stopper in done and ack:
+ done, _ = await asyncio.wait({reader}, timeout=ack)
+ if reader in done:
+ return reader.result()
+ raise RuntimeStoreError('managed_worker_stopped' if self.stop.is_set() else 'managed_worker_hello_timeout')
+ finally:
+ stopper.cancel()
+ reader.cancel()
+
+ def interrupt(self):
+ self.control({'type': 'stop'})
+
+ def respond(self, kind, prompt_id, value):
+ self.control({'type': kind, 'prompt_id': prompt_id, 'value': value})
+
+ def send(self, frame):
+ with self.write_lock:
+ self.process.stdin.write(encode_frame(frame))
+ self.process.stdin.flush()
+
+ def _signal_worker(self, kill):
+ """Signal the verified interpreter, not only the handle: a launcher that exec-chained
+ or exited leaves the real worker outside the Popen's reach."""
+ import psutil
+ if self.worker is None or self.worker[0] == self.process.pid:
+ return
+ try:
+ proc = psutil.Process(self.worker[0])
+ if proc.create_time() == self.worker[1]:
+ (proc.kill if kill else proc.terminate)()
+ except psutil.Error:
+ pass
+
+ def close(self):
+ self.closed.set()
+ if self.process.poll() is None:
+ self._signal_worker(kill=False)
+ self.process.terminate()
+ try:
+ self.process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ self._signal_worker(kill=True)
+ self.process.kill()
+ self.process.wait(timeout=5)
+ else:
+ self._signal_worker(kill=True)
+ if self.writer.ident is not None:
+ self.writer.join(timeout=5)
+ self.process.stdin.close()
+ self.process.stdout.close()
+
+
+def interrupt_managed(authority, actor, ref, generation):
+ worker = getattr(authority, '_managed_workers', {}).get(ref.session_id)
+ if worker is None:
+ return False
+ authority.authorize(actor, ref, 'session:control')
+ authority.check_approval_generation(ref.session_id, generation)
+ worker.control({'type': 'stop'})
+ return True
+
+
+def _prompt_frame(authority, ref, row, worker, frame):
+ live = authority.sessions[ref.session_id]
+ controls = live.controls
+ kind = frame.get('type')
+ if kind == 'prompt_settled' and set(frame) == {'type', 'prompt_id'}:
+ prompt_id = frame['prompt_id']
+ controls.remote_responders.pop(prompt_id, None)
+ saved = controls.pending.pop(prompt_id, None)
+ if saved:
+ live.event_stream.publish(ref.session_id, {'prompt_id': prompt_id,
+ 'execution_generation': row['generation']}, event_type=saved[1]['kind'] + '.settled')
+ return True
+ if kind not in {'approval', 'clarify'}:
+ return False
+ if len(controls.remote_responders) >= 16:
+ raise RuntimeStoreError('worker_control_backpressure')
+ if kind == 'approval':
+ fields = {'request_id', 'command', 'description', 'allow_session', 'allow_permanent', 'smart_denied', 'edit'}
+ data = frame.get('data')
+ if set(frame) != {'type', 'data'} or not isinstance(data, dict) or set(data) - fields:
+ raise RuntimeStoreError('invalid_worker_frame')
+ prompt_id = data.get('request_id')
+ else:
+ if (set(frame) != {'type', 'prompt_id', 'question', 'choices', 'multi_select'}
+ or not isinstance(frame['question'], str) or not isinstance(frame['choices'], list)
+ or any(not isinstance(c, str) for c in frame['choices']) or type(frame['multi_select']) is not bool):
+ raise RuntimeStoreError('invalid_worker_frame')
+ prompt_id = frame['prompt_id']
+ if not isinstance(prompt_id, str) or not prompt_id or prompt_id in controls.pending:
+ raise RuntimeStoreError('invalid_worker_frame')
+ controls.remote_responders[prompt_id] = worker.respond
+ if kind == 'approval':
+ authority.register_approval(ref.session_id, row['generation'], live.route, data)
+ else:
+ entry = SimpleNamespace(clarify_id=prompt_id, question=frame['question'], choices=frame['choices'],
+ multi_select=frame['multi_select'], event=threading.Event())
+ authority.register_clarify(ref.session_id, row['generation'], entry)
+ return True
+
+
+def _worker_env(authority):
+ """Child env for the OWNING profile under multiplex: its HERMES_HOME plus its ``.env``
+ secrets over a scrubbed base, never the launch profile's process environment (the same
+ rule MCP stdio children and shell hooks follow). Single-profile gateways inherit the
+ process env byte-for-byte, exactly as before."""
+ from pathlib import Path
+ from agent.secret_scope import is_multiplex_active
+ from tools.environments.local import _is_routed_home
+ home = Path(str(authority.profile_id))
+ if not home.is_absolute():
+ return None
+ # Keyed on the worker's OWNING profile, not only the process-wide multiplex flag: a worker for
+ # another profile must never inherit the launch environ even when that flag reads False.
+ routed = _is_routed_home(home)
+ if not routed and not is_multiplex_active():
+ return None
+ from agent.secret_scope import build_profile_secret_scope
+ from tools.environments.local import _scrub_credentials, build_subprocess_env, strip_launch_profile_env
+ # The scrub removes credentials, not settings: the launch profile's TERMINAL_* policy and
+ # its ``.env`` settings would otherwise reach the secondary's worker (cron/kanban rule).
+ env = strip_launch_profile_env(build_subprocess_env(scrub_secrets=True), home)
+ if routed:
+ # Same rule as served_profile_child_env: env_passthrough / first-party carve-outs must not
+ # forward launch-process provider credentials that no .env or source snapshot recorded.
+ _scrub_credentials(env, inherit_credentials=False)
+ env.update({k: v for k, v in build_profile_secret_scope(home).items() if v is not None})
+ env['HERMES_HOME'] = str(home)
+ from hermes_constants import apply_subprocess_home_env
+ apply_subprocess_home_env(env)
+ return env
+
+
+async def execute_managed(authority, ref, row, policy):
+ from gateway.run_turn_progress import publish_worker_tool_event
+ env = await asyncio.to_thread(_worker_env, authority)
+ cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]
+ process = await asyncio.to_thread(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],
+ cwd=cwd, stdin=subprocess.PIPE, env=env,
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=True)
+ worker = ManagedWorker(process)
+ workers = getattr(authority, '_managed_workers', None)
+ if workers is None:
+ workers = authority._managed_workers = {}
+ workers[ref.session_id] = worker
+ # A Stop acknowledged during the env/spawn awaits found no worker and was latched for this
+ # generation; consume it in the same step that makes the worker reachable to interrupt_managed.
+ authority.adopt_agent(ref.session_id, row['generation'], worker)
+ accepted = usage = None
+ scope = None
+ try:
+ # The interpreter behind the handle introduces itself first; the owner verifies that
+ # identity (alive, same birth, descends from the handle) before reserving for it.
+ hello = await worker.next_frame(HELLO_SECONDS, ack=0)
+ if worker.stop.is_set():
+ # Stopped before the child could receive controls: hello raced the latch; never bootstrap.
+ raise RuntimeStoreError('managed_worker_stopped')
+ scope = reserve_admission_worker(authority, admission_id=row['admission_id'],
+ process=process, principal_id=row['principal_id'], hello=hello)
+ worker.worker = (scope['pid'], scope['birth'])
+ # The child reads nothing else until the exact reservation has committed.
+ frame = await asyncio.to_thread(_bootstrap, authority, ref, row, policy, scope)
+ await asyncio.to_thread(worker.send, frame)
+ worker.writer.start()
+ while True:
+ frame = await worker.next_frame(None, ack=STOP_ACK_SECONDS)
+ authority.check_approval_generation(ref.session_id, row['generation'])
+ with authority.sessions[ref.session_id].event_stream.lock:
+ if _prompt_frame(authority, ref, row, worker, frame):
+ continue
+ if frame == {'type': 'error', 'reason': 'managed_worker_failed'}:
+ raise RuntimeStoreError('managed_worker_failed')
+ kind = frame.get('type')
+ if kind == 'ready' and set(frame) == {'type', 'pid'} and frame['pid'] == scope['pid']:
+ continue
+ if kind == 'delta' and set(frame) == {'type', 'text'} and isinstance(frame['text'], str):
+ authority.publish_execution(ref.session_id, row['generation'], 'message.delta', {'text': frame['text']})
+ continue
+ if publish_worker_tool_event(authority, ref.session_id, row['generation'], frame):
+ continue
+ if kind == 'result' and set(frame) == {'type', 'result'} and accepted is None:
+ try:
+ accepted, usage = accept_result(frame['result'])
+ except ValueError as exc:
+ raise RuntimeStoreError('invalid_worker_result') from exc
+ authority.sessions[ref.session_id].controls.snapshot(ref.session_id, None)
+ await asyncio.to_thread(worker.send, {'type': 'finish'})
+ continue
+ if frame == {'type': 'finished'} and accepted is not None:
+ code = await asyncio.to_thread(process.wait, 10)
+ if code != 0:
+ raise RuntimeStoreError('managed_worker_lost')
+ # Like in-process execution, settlement belongs to the drain's stream lock.
+ # The worker must acknowledge its durable finish before that boundary.
+ authority.pending_results[row['admission_id']] = {'result': accepted, 'usage': usage}
+ return accepted['final_response']
+ raise RuntimeStoreError('invalid_worker_frame')
+ except (Exception, asyncio.CancelledError) as exc:
+ import logging
+ logging.getLogger(__name__).warning('Managed worker lost: %s',
+ exc.reason if isinstance(exc, RuntimeStoreError) else type(exc).__name__)
+ if scope is None:
+ if isinstance(exc, RuntimeStoreError) and exc.reason == 'managed_worker_stopped':
+ # Stopped before the child ever received its bootstrap: nothing executed, so
+ # this settles like an ordinary interrupted turn (the finally kills the child).
+ authority.pending_results[row['admission_id']] = {
+ 'result': {'final_response': '', 'interrupted': True}, 'usage': {}}
+ return ''
+ raise
+ from gateway.session_worker_reservation import lose_admission_worker
+ lose_admission_worker(authority, row, scope)
+ live = authority.sessions[ref.session_id]
+ with live.event_stream.lock:
+ live.controls.snapshot(ref.session_id, None)
+ authority._publish_pending(ref)
+ live.event_stream.publish(ref.session_id, {'text': 'Worker execution is unknown.',
+ 'content': 'Worker execution is unknown.', 'admission_id': row['admission_id'], 'outcome': 'unknown'})
+ waiter = authority.waiters.pop(row['admission_id'], None)
+ if waiter is not None and not waiter.done():
+ waiter.set_result('Worker execution is unknown.')
+ # Stop this drain without its ordinary Exception→failed settlement. The
+ # committed unknown row deliberately pauses every accepted follower.
+ raise asyncio.CancelledError('managed_worker_unknown') from exc
+ finally:
+ workers.pop(ref.session_id, None)
+ await asyncio.to_thread(worker.close)
diff --cc tests/gateway/test_yolo_command.py
index 04cf1a57290,583caf3427e..726c509ed6e
--- a/tests/gateway/test_yolo_command.py
+++ b/tests/gateway/test_yolo_command.py
@@@ -120,30 -88,5 +121,31 @@@ async def test_yolo_survives_gateway_re
second._clear_session_boundary_security_state(key)
assert is_session_yolo_enabled(key) is False
third = _runner()
- third._restore_session_yolo(key, third.session_store.get_or_create_session(event.source))
+ restore_session_yolo(key, third.session_store.get_or_create_session(event.source).yolo)
assert is_session_yolo_enabled(key) is False
+
+
+async def test_owner_yolo_off_is_not_revived_by_the_persisted_restore(tmp_path):
+ """The owner's `config.set key=yolo` (TUI/Desktop/`hermes chat` /yolo) writes the route's persisted
+ copy too: switching off a persisted /yolo must not be re-armed by the next turn's restore."""
+ from types import SimpleNamespace
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_busy_controls import busy_config
++ from tools.approval_yolo import restore_session_yolo
+
+ runner = _make_runner()
+ runner.session_store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())
+ runner.session_store._db = None
+ event = _make_event("chat-a")
+ key = runner._session_key_for_source(event.source)
+ await runner._handle_yolo_command(event)
+ authority = SimpleNamespace(authorize=lambda *_a: None, profile_id=str(tmp_path), runner=runner,
+ sessions={"sid": SimpleNamespace(route=key, source=event.source)})
+ connection, ref = SimpleNamespace(actor="a", authority=authority), SimpleNamespace(session_id="sid")
+
+ off = await busy_config(connection, ref, {"session_id": "sid", "key": "yolo", "value": "0"}, write=True)
+ assert off["value"] == "0" and is_session_yolo_enabled(key) is False
- runner._restore_session_yolo(key, runner.session_store.get_or_create_session(event.source))
++ restore_session_yolo(key, runner.session_store.get_or_create_session(event.source).yolo)
+ assert is_session_yolo_enabled(key) is False
diff --cc tools/approval.py
index b5f08c7a0f1,6d4402db744..fa77254451a
--- a/tools/approval.py
+++ b/tools/approval.py
@@@ -52,9 -52,6 +52,9 @@@ _lock = threading.Lock(
_pending: dict[str, dict] = {}
_session_approved: dict[str, set] = {}
_session_yolo: set[str] = set()
- # Session keys whose frozen launch YOLO (`hermes chat --yolo`) was already applied: the launch flag seeds
- # the bypass once, so a later `/yolo` off is not silently re-enabled by the next turn.
++# Session keys whose launch YOLO (`hermes chat --yolo` session policy) was already seeded by
++# ``tools.approval_yolo.apply_launch_yolo``: once per boundary, so a later `/yolo` off sticks.
+_launch_yolo_applied: set[str] = set()
_permanent_approved: set = set()
# Routed multiplex profiles: one permanent allowlist per profile home (see ``_permanent_set``).
_permanent_approved_by_home: dict[str, set] = {}
diff --cc tools/approval_yolo.py
index 00000000000,6de44ee0848..995e0fff27f
mode 000000,100644..100644
--- a/tools/approval_yolo.py
+++ b/tools/approval_yolo.py
@@@ -1,0 -1,72 +1,88 @@@
+ """Session ``/yolo``: the one toggle / restore / carry contract every surface calls.
+
+ The bypass itself is ``tools.approval``'s in-memory per-key set, so every process starts with it empty.
+ Each surface persists it where its session identity lives: CLI, TUI and Desktop on the session row
+ (``model_config.yolo_mode``), the messaging gateway on the routing entry, whose key outlives compression
-rotations. The surface hands its writer in as ``persist(enabled)``; everything else is decided here, so
-the CLI ``/yolo``, the TUI Shift+Tab, the Desktop zap and a Telegram ``/yolo`` behave the same.
++rotations; sessions the gateway owns for CLI/TUI/Desktop clients (``config.set key=yolo``) and their managed
++workers use that same routing entry. The surface hands its writer in as ``persist(enabled)``; everything else
++is decided here, so the CLI ``/yolo``, the TUI Shift+Tab, the Desktop zap and a Telegram ``/yolo`` behave the same.
+ """
+
+ import logging
+ from typing import Any, Callable, Optional
+
+ from tools import approval
+
+ logger = logging.getLogger(__name__)
+
+ Persist = Optional[Callable[[bool], Any]]
+
+
+ def _persist(persist: Persist, enabled: bool, session_key: str) -> None:
+ # Best-effort: the live flag is authoritative for this process; a failed write only costs the restore.
+ if persist is None:
+ return
+ try:
+ persist(enabled)
+ except Exception:
+ logger.warning("failed to persist session yolo=%s for %s", enabled, session_key, exc_info=True)
+
+
+ def toggle_session_yolo(session_key: str, enabled: Optional[bool] = None, *, persisted: bool = False,
+ persist: Persist = None) -> bool:
+ """Flip (``enabled=None``) or set the bypass for *session_key*; returns the new state.
+
+ *persisted* is the stored flag: after a restart only it is set and the user still sees ON, so a toggle
+ turns it OFF. The write runs BEFORE the live flip, so a turn restoring in between never revives a
+ bypass that is being switched off.
+ """
+ if enabled is None:
+ enabled = not (persisted or approval.is_session_yolo_enabled(session_key))
+ _persist(persist, enabled, session_key)
+ (approval.enable_session_yolo if enabled else approval.disable_session_yolo)(session_key)
+ return enabled
+
+
+ def restore_session_yolo(session_key: str, persisted: bool) -> bool:
+ """Re-arm a persisted bypass in a fresh process; True when this call turned it on.
+
+ Key it on the id approvals are checked under (the stored session id / routing key), never a
+ transport-local id. Skipped under the frozen process ``--yolo``, which already bypasses everything.
+ """
+ if (not session_key or not persisted or approval._YOLO_MODE_FROZEN
+ or approval.is_session_yolo_enabled(session_key)):
+ return False
+ approval.enable_session_yolo(session_key)
+ return True
+
+
++def apply_launch_yolo(session_key: str) -> None:
++ """Seed a gateway-owned session's launch ``--yolo`` policy once per session boundary.
++
++ Called every turn of such a route; only the first call (or the first after ``clear_session``) arms it,
++ so a later ``/yolo`` off sticks instead of lasting one turn. Skipped under the frozen process ``--yolo``.
++ """
++ if not session_key or approval._YOLO_MODE_FROZEN:
++ return
++ with approval._lock:
++ if session_key in approval._launch_yolo_applied:
++ return
++ approval._launch_yolo_applied.add(session_key)
++ approval.enable_session_yolo(session_key)
++
++
+ def transfer_session_yolo(old_key: str, new_key: str) -> None:
+ """Move the live bypass when the conversation continues under a new id (compression rotation, /branch).
+ The new row records it at creation (``with_session_yolo``), so nothing is written here."""
+ if not old_key or not new_key or old_key == new_key or not approval.is_session_yolo_enabled(old_key):
+ return
+ approval.enable_session_yolo(new_key)
+ approval.disable_session_yolo(old_key)
+
+
+ def with_session_yolo(model_config: Optional[dict], session_key: str) -> Optional[dict]:
+ """``model_config`` for a session row being created, carrying a live bypass. Rows are created lazily on
+ the first turn, so this is where a toggle made before the row existed gets recorded."""
+ if not approval.is_session_yolo_enabled(session_key):
+ return model_config
+ return {**(model_config or {}), "yolo_mode": True}