Skip to content

The agent that grows with you

fix(gateway): a follow-profile session resolves each turn from one profile read

Teknium7a1874ecf2b7
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index bea5119ed27..8ca7e00944c 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -1018,7 +1018,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
platform_key = policy.platform if policy else _platform_config_key(source.platform)
enabled_toolsets, disabled_toolsets = self._resolve_turn_toolsets(user_config, source, platform_key)
if policy:
- enabled_toolsets = list(policy.toolsets)
+ enabled_toolsets = list(policy.current_toolsets(user_config))
adapter = self._delivery_adapter_for(source)
# Tool preview length (0 = no limit) and friendly tool labels (default on), per-platform.
for _setter, _setting, _default, _cast in (
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index a0e7460c051..35228e0814e 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -49,9 +49,9 @@ def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:
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)
- # A follow_profile_config session's route is the profile's current one (frozen == live sections).
- model, provider = policy.current_model(authority), (frozen.get('model') or {}).get('provider')
+ # A follow_profile_config session's route is the profile's current one, model and endpoint from one read.
+ frozen, model = policy.effective(authority)
+ provider = (frozen.get('model') or {}).get('provider')
key = launch_key(authority, policy)
launch_url = json.loads(policy.request_json).get('base_url')
if launch_url:
diff --git a/gateway/session_local.py b/gateway/session_local.py
index 5faed74bde3..83911d0ea1e 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -242,9 +242,10 @@ def _lazy_model(authority, policy):
return GUEST_MODEL if free_tier_route() else model
-def _reasoning_fields(agent, policy, model):
- """Main's session-info effort/tier fields, from the built agent or (lazy) the frozen policy: a
- resumed Desktop slice holds its reasoning pill pending until ``reasoning_effort`` arrives."""
+def _reasoning_fields(agent, policy, model, authority=None):
+ """Main's session-info effort/tier fields, from the built agent or (lazy) what the policy's next turn
+ resolves (a following session's current profile): a resumed Desktop slice holds its reasoning pill
+ pending until ``reasoning_effort`` arrives."""
from agent.fast_mode import STATIC_TIERS, parse_service_tier
from agent.reasoning_effort import clamp_effort, route_supported_efforts
from agent.voice_turn_route import session_runtime_view
@@ -252,11 +253,16 @@ def _reasoning_fields(agent, policy, model):
if agent is None and policy is None:
return {}
view = session_runtime_view(agent) if agent is not None else None
- config = getattr(view, 'reasoning_config', None) if view is not None else policy.reasoning_config
+ if view is None:
+ from hermes_constants import resolve_reasoning_config
+ effective, next_model = policy.effective(authority, secrets=False)
+ route = effective.get('model') or {}
+ config = (getattr(view, 'reasoning_config', None) if view is not None
+ else resolve_reasoning_config(effective, next_model or ''))
tier = (getattr(view, 'service_tier', None) if view is not None
- else parse_service_tier((policy.config().get('agent') or {}).get('service_tier'))) or ''
- provider = getattr(view, 'provider', None) if view is not None else policy.provider
- base_url = getattr(view, 'base_url', None) if view is not None else policy.base_url
+ else parse_service_tier((effective.get('agent') or {}).get('service_tier'))) or ''
+ provider = getattr(view, 'provider', None) if view is not None else route.get('provider')
+ base_url = getattr(view, 'base_url', None) if view is not None else route.get('base_url')
effort = ''
if isinstance(config, dict):
effort = 'none' if config.get('enabled') is False else str(config.get('effort') or '')
@@ -286,7 +292,7 @@ def local_session_info(authority, ref):
# Main's TUI labels a named profile's composer (``alpha ❯``) from this field.
'profile_name': served_profile_name(authority.profile_id),
**({'cwd': policy.cwd} if policy else {})}
- info.update(_reasoning_fields(agent, policy, info['model']))
+ info.update(_reasoning_fields(agent, policy, info['model'], authority))
if policy:
# The creation request the route was frozen with (secrets already extracted), so a
# resuming client can tell "same flags again" from a real override attempt.
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index c1854d8e251..08c3d23a301 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -14,10 +14,15 @@ CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',
'service_tier', 'cwd_explicit'})
# Sections a ``follow_profile_config`` session re-reads from the owning profile's CURRENT config each
# turn (main's Bot Chat row), credentials included: a frozen key never crosses a profile route change.
-FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases')
-FOLLOW_AGENT_KEYS = ('reasoning_effort', 'reasoning_overrides', 'service_tier')
+FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases',
+ 'platform_toolsets')
+FOLLOW_AGENT_KEYS = ('reasoning_effort', 'reasoning_overrides', 'service_tier', 'disabled_toolsets')
+# What a pick (create-time ``model`` / committed ``/model``) owns of the ``model:`` block.
+SELECTION_KEYS = ('default', 'provider', 'base_url', 'api_mode', 'selection_profile', 'api_key_from', 'key_env',
+ 'api_key_env')
BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')
_ACTIVE_POLICY: ContextVar = ContextVar('local_session_policy', default=None)
+_TURN_PROFILE: ContextVar = ContextVar('follow_profile_read', default=None) # (policy, live) for a turn
# Creation label -> agent surface. ``tool`` (third-party integrations, ``hermes chat --source tool``) and
# ``oneshot`` (finite ``chat -q`` / ``-z`` runs) run as the CLI but keep their own stored label, so human
# pickers hide them (INTERNAL_LISTING_SOURCES).
@@ -46,13 +51,19 @@ class LocalSessionPolicy:
# ephemeral prompt never re-reads the skill files, like the CLI's startup preload.
skills_prompt: str | None = None
- def config(self, authority=None):
+ def config(self, authority=None, *, secrets=True):
+ return self.effective(authority, secrets=secrets)[0]
+
+ def effective(self, authority=None, *, secrets=True):
+ """``(config, model)`` the next turn runs, both from ONE read of the owning profile when following
+ (the turn's policy scope holds that read): a route never pairs one profile's model with another's
+ endpoint. Explicit choices (create-time reasoning / tier / toolsets, a pick that still holds) are
+ applied over the followed defaults; frozen secrets of followed sections are never recovered."""
config = present_sections(json.loads(self.config_json))
- live = self._live_profile(authority, config)
- if self.config_secret_ref is not None and authority is not None:
+ live = self.read_profile(authority)
+ if self.config_secret_ref is not None and authority is not None and secrets:
from gateway.session_policy_credentials import recover_config_secrets
- secrets = recover_config_secrets(authority, self, skip=FOLLOW_SECTIONS if live is not None else ())
- for path, value in secrets.items():
+ for path, value in recover_config_secrets(authority, self).items():
if path[0] is None: # private terminal projection, not config
continue
target = config
@@ -60,40 +71,65 @@ class LocalSessionPolicy:
# An alias entry added after creation is absent from the frozen tree.
target = target.setdefault(key, {}) if isinstance(target, dict) else target[key]
target[path[-1]] = value
- model = config.get('model')
- # ``/model <alias>`` with a literal key: the receipt points at the alias entry's secret.
- if isinstance(model, dict) and model.get('api_key_from') and 'api_key' in model:
- model['api_key'] = secrets.get(tuple(model['api_key_from']))
- if live is not None:
+ model = self.model
+ if live:
+ frozen, request = config.get('model') or {}, json.loads(self.request_json)
+ pick = frozen.get('selection_profile')
+ held = pick is not None and pick == list(profile_target(live))
+ pinned = {'platform_toolsets', 'disabled_toolsets'} if 'toolsets' in request else set()
+ pinned |= {'reasoning_effort', 'reasoning_overrides'} if 'reasoning' in request else set()
+ pinned |= {'service_tier'} if 'service_tier' in request else set()
for key in FOLLOW_SECTIONS:
+ if key in pinned:
+ continue
if key in live:
config[key] = live[key]
else:
config.pop(key, None)
+ if held:
+ config['model'] = _held_pick(frozen, config.get('model') or {})
+ else:
+ from gateway.run import _resolve_gateway_model
+ model = _resolve_gateway_model(live) or self.model
agent, live_agent = config.setdefault('agent', {}), live.get('agent') or {}
for key in FOLLOW_AGENT_KEYS:
+ if key in pinned:
+ continue
if key in live_agent:
agent[key] = live_agent[key]
else:
agent.pop(key, None)
- return config
+ source = (config.get('model') or {}).get('api_key_from') if isinstance(config.get('model'), dict) else None
+ if source:
+ # ``/model <alias>`` with a literal key: the receipt points at the alias entry's secret.
+ value = config
+ for part in source:
+ value = value.get(part) if isinstance(value, dict) else None
+ config['model']['api_key'] = value
+ return config, model
@property
def follows_profile(self):
return json.loads(self.request_json).get('follow_profile_config') is True
- def _live_profile(self, authority, frozen):
- """The owning profile's current config for a following session, or None when the frozen route
- applies: not following, or an explicit pick (create-time model / committed /model) made while
- the profile still targets what it targeted then (main's ``composer_override_profile``)."""
+ def read_profile(self, authority):
+ """The owning profile's current config for a following session, else None; inside this policy's
+ turn scope, the turn's one read."""
if authority is None or not self.follows_profile:
return None
+ held = _TURN_PROFILE.get()
+ if held is not None and held[0] == self:
+ return held[1]
from gateway.run import _load_gateway_config
- live = present_sections(_load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml'))
- pick = (frozen.get('model') or {}).get('selection_profile')
- if not live or (pick is not None and pick == list(profile_target(live))):
- return None
- return live
+ return present_sections(_load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml'))
+
+ def current_toolsets(self, config):
+ """The next turn's toolsets from its resolved *config*: a following session without an explicit
+ toolset pick runs the profile's current selection (main #124211), else the frozen launch set."""
+ if (not self.follows_profile or self.source not in SURFACES or self.editor_mcp_json is not None
+ or 'toolsets' in json.loads(self.request_json)):
+ return self.toolsets
+ return tuple(sorted(_resolve_toolsets({}, config, self.source, self.safe_mode)))
def current_reasoning_config(self, runner):
"""The next turn's reasoning: the profile's current effort when following, else the frozen one."""
@@ -101,8 +137,8 @@ class LocalSessionPolicy:
return self.reasoning_config
from gateway.session_authorities import active_authority
from hermes_constants import resolve_reasoning_config
- authority = active_authority(runner)
- return resolve_reasoning_config(self.config(authority), self.current_model(authority) or '')
+ config, model = self.effective(active_authority(runner), secrets=False)
+ return resolve_reasoning_config(config, model or '')
def current_service_tier(self, runner, session_key):
"""The next turn's tier: a typed session /fast, else the policy's (frozen, or the profile's when following)."""
@@ -112,15 +148,12 @@ class LocalSessionPolicy:
state = runner._peek_session_state(session_key) if session_key else None
if state is not None and state.conversation.service_tier_override is not SERVICE_TIER_UNSET:
return state.conversation.service_tier_override
- return parse_service_tier((self.config(active_authority(runner)).get('agent') or {}).get('service_tier'))
+ config = self.config(active_authority(runner), secrets=False)
+ return parse_service_tier((config.get('agent') or {}).get('service_tier'))
def current_model(self, authority):
"""The model this session's next turn runs: the profile's current default when following."""
- live = self._live_profile(authority, present_sections(json.loads(self.config_json)))
- if live is None:
- return self.model
- from gateway.run import _resolve_gateway_model
- return _resolve_gateway_model(live) or self.model
+ return self.effective(authority, secrets=False)[1]
@property
def provider(self):
@@ -172,6 +205,19 @@ def profile_target(config):
return (model.strip() if isinstance(model, str) else ''), ''
+def _held_pick(frozen, live):
+ """A pick that still holds keeps its selection; on the profile's own endpoint the rest of the
+ ``model:`` block (a rotated key included) is the profile's. Another endpoint never gets it."""
+ from hermes_cli.route_identity import normalize_route_base_url
+
+ def route(block):
+ return str(block.get('provider') or '').strip().lower(), normalize_route_base_url(block.get('base_url'))
+ if route(frozen) != route(live):
+ return frozen
+ return {**{k: v for k, v in live.items() if k not in SELECTION_KEYS},
+ **{k: frozen[k] for k in SELECTION_KEYS if k in frozen}}
+
+
def present_sections(config):
"""A bare ``gateway:`` key parses as YAML null; like load_config's merge (#58277), treat it as absent so
``cfg.get('gateway', {}).get(...)`` reads the default instead of crashing a fresh install's first turn."""
@@ -419,7 +465,9 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=No
config_secrets = dict(config_secrets or {})
policy = bind_editor_mcp(authority, session_id, policy, config_secrets.pop(PRIVATE_KEY, None))
if api_key is None and not config_secrets:
- return policy
+ # Nothing private remains (a followed section's secret, or a cleared key): a stale reference
+ # would no longer match the re-fingerprinted policy identity.
+ return replace(policy, credential_ref=None, config_secret_ref=None)
keys = getattr(authority, '_local_launch_keys', None)
if keys is None:
keys = authority._local_launch_keys = {}
@@ -582,9 +630,15 @@ def policy_scope(policy, *, authority=None):
for path, value in recover_config_secrets(authority, policy).items():
if path[0] is None:
terminal[path[1]] = value
+ # A following session's turn reads its profile once; every resolution in the turn uses that read.
+ profile_token = _TURN_PROFILE.set((policy, policy.read_profile(authority)))
+ active = policy
+ if policy.follows_profile:
+ from dataclasses import replace
+ active = replace(policy, toolsets=policy.current_toolsets(policy.config(authority, secrets=False)))
cwd_token = set_session_cwd(policy.cwd)
terminal_token = set_terminal_scope(terminal)
- policy_token = _ACTIVE_POLICY.set(policy)
+ policy_token = _ACTIVE_POLICY.set(active)
from gateway.session_local_editor import editor_scope
try:
from gateway.session_local_mcp import editor_mcp_scope
@@ -594,6 +648,7 @@ def policy_scope(policy, *, authority=None):
_ACTIVE_POLICY.reset(policy_token)
reset_terminal_scope(terminal_token)
cwd_token.var.reset(cwd_token)
+ _TURN_PROFILE.reset(profile_token)
def active_policy():
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index 986e1784935..902e95d00d7 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -32,10 +32,13 @@ def config_reference(authority, session_id, policy, secrets):
sort_keys=True)
-def recover_config_secrets(authority, policy, skip=()):
- """The frozen config secrets; entries under a *skip* section are neither re-read nor checked (a
- following session overwrites those sections from the live profile, so a key rotation there is not
- a revoked launch credential)."""
+def recover_config_secrets(authority, policy, skip=None):
+ """The frozen config secrets; entries under a *skip* section are neither re-read nor checked. Every
+ caller of a following session skips its followed sections: the live profile supplies them, so a key
+ rotation there is not a revoked launch credential."""
+ if skip is None:
+ from gateway.session_policy import FOLLOW_SECTIONS
+ skip = FOLLOW_SECTIONS if policy.follows_profile else ()
ref = policy.config_secret_ref
if not ref.startswith(PREFIX):
values = getattr(authority, '_local_config_secrets', {}).get(ref)
@@ -52,11 +55,10 @@ def recover_config_secrets(authority, policy, skip=()):
if cached is not None:
return {path: value for path, value in cached.items() if path[0] not in skip}
from gateway.run import _load_gateway_config
- config = _load_gateway_config(home / 'config.yaml')
+ entries = [entry for entry in source['entries'] if entry[0][0] not in skip]
+ config = _load_gateway_config(home / 'config.yaml') if any(path[0] is not None for path, _ in entries) else {}
values = {}
- for path, fingerprint in source['entries']:
- if path[0] in skip:
- continue
+ for path, fingerprint in entries:
value = config
lookup = path
if path[0] is None:
diff --git a/tests/gateway/test_follow_profile_followups.py b/tests/gateway/test_follow_profile_followups.py
new file mode 100644
index 00000000000..f38795ac5e4
--- /dev/null
+++ b/tests/gateway/test_follow_profile_followups.py
@@ -0,0 +1,133 @@
+"""follow_profile_config follow-ups (andrexibiza C14-C18, C03): one profile read per turn, explicit
+create-time choices over followed defaults, a held pick still follows the rotated key, followed secrets
+are never recovered from the frozen receipt, and the profile's toolsets are followed. Real SessionStore /
+SessionAuthority and a real config.yaml; ``_load_gateway_config`` is only wrapped, never replaced."""
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from tests.gateway.test_session_follow_profile_config import _create, _owner, _route
+
+
+async def _create_bot_chat(owner, authority, home, request_id, **extra):
+ """Desktop's Bot Chat create: no toolsets param (the surface's own selection)."""
+ response = await owner.dispatch({'id': request_id, 'method': 'session.create', 'params': dict(
+ request_id=request_id, source='gui', cwd=str(home), follow_profile_config=True, **extra)})
+ assert 'result' in response, response
+ return authority.sessions[response['result']['session_id']]
+
+
+def _profile(home, model, port, key, **extra):
+ (home / 'config.yaml').write_text(json.dumps({'model': {
+ 'provider': 'custom', 'base_url': f'http://127.0.0.1:{port}/v1', 'default': model, 'api_key': key}, **extra}))
+
+
+def home(monkeypatch):
+ from gateway import run
+ from hermes_constants import get_hermes_home
+ home = get_hermes_home()
+ home.mkdir(parents=True, exist_ok=True)
+ monkeypatch.setattr(run, '_hermes_home', home)
+ return home
+
+
+async def test_rotated_key_reaches_follow_and_held_pick_on_a_fresh_owner_and_routes_are_never_mixed(home, monkeypatch):
+ from gateway import run
+ from gateway.session_policy import policy_for_source, policy_scope
+ _profile(home, 'old', 1, 'k-old')
+ store, runner, authority, owner = _owner(home)
+ runner._peek_session_state = lambda key: None
+ try:
+ follow = await _create(owner, authority, home, 'follow')
+ pick = await _create(owner, authority, home, 'pick', model='picked')
+ _profile(home, 'old', 1, 'k-new') # rotate only the key
+ assert _route(runner, follow) == ('old', 'http://127.0.0.1:1/v1', 'k-new')
+ # C15: the pick keeps its model and follows the rotated key, like the no-pick control.
+ assert _route(runner, pick) == ('picked', 'http://127.0.0.1:1/v1', 'k-new')
+ # C14: a fresh owner (no in-memory config secrets) enters both sessions' scopes and resolves.
+ authority._local_config_secrets = {}
+ for live in (follow, pick):
+ with policy_scope(policy_for_source(runner, live.source), authority=authority):
+ assert _route(runner, live)[2] == 'k-new'
+ # C18: the profile moves A -> B between two reads of one resolution (the file the credential pool
+ # reads stays A): the route is whole A or whole B, never B's model on A's endpoint and key.
+ _profile(home, 'a', 3, 'key-a')
+ real, reads = run._load_gateway_config, []
+ def moved_after_first_read(path=None):
+ reads.append(path)
+ if len(reads) == 1:
+ return real(path)
+ return {'model': {'provider': 'custom', 'base_url': 'http://127.0.0.1:4/v1', 'default': 'b', 'api_key': 'key-b'}}
+ monkeypatch.setattr(run, '_load_gateway_config', moved_after_first_read)
+ assert _route(runner, follow) in {('a', 'http://127.0.0.1:3/v1', 'key-a'), ('b', 'http://127.0.0.1:4/v1', 'key-b')}
+ monkeypatch.setattr(run, '_load_gateway_config', real)
+ # Inside a turn every resolution uses the turn's one read, whatever the file says meanwhile.
+ _profile(home, 'a', 5, 'key-a')
+ with policy_scope(policy_for_source(runner, follow.source), authority=authority):
+ _profile(home, 'b', 6, 'key-b')
+ assert _route(runner, follow) == ('a', 'http://127.0.0.1:5/v1', 'key-a')
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+
+
+async def test_explicit_create_choices_win_and_session_info_reports_the_next_turn(home):
+ from gateway.session_local import local_session_info
+ from gateway.session_policy import policy_for_source
+ _profile(home, 'old', 1, 'k', agent={'reasoning_effort': 'low'})
+ store, runner, authority, owner = _owner(home)
+ runner._peek_session_state = lambda key: None
+ try:
+ plain = await _create(owner, authority, home, 'plain')
+ explicit = await _create(owner, authority, home, 'explicit', reasoning='high', service_tier='priority')
+ _profile(home, 'old', 1, 'k', agent={'reasoning_effort': 'minimal', 'service_tier': 'normal'})
+ # C16: explicit create-time reasoning/tier are applied after the followed defaults.
+ policy = policy_for_source(runner, explicit.source)
+ assert policy.current_reasoning_config(runner)['effort'] == 'high'
+ assert policy.current_service_tier(runner, None) == 'priority'
+ # C17: lazy session.info reports what the next turn resolves, for both sessions.
+ for live, effort, tier in ((explicit, 'high', 'priority'), (plain, 'minimal', '')):
+ policy = policy_for_source(runner, live.source)
+ info = local_session_info(authority, _ref(authority, live))
+ assert (info['reasoning_effort'], info['service_tier']) == (effort, tier)
+ assert policy.current_reasoning_config(runner)['effort'] == effort
+ assert (policy.current_service_tier(runner, None) or '') == tier
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
+
+
+def _ref(authority, live):
+ sid = next(sid for sid, entry in authority.sessions.items() if entry is live)
+ return SimpleNamespace(session_id=sid)
+
+
+async def test_follow_session_runs_the_profiles_current_toolsets_and_a_frozen_one_does_not(home):
+ """C03 (main #124211): ``hermes tools disable`` reaches a following Bot Chat's next turn."""
+ from gateway.session_policy import active_policy, policy_for_source, policy_scope
+ _profile(home, 'old', 1, 'k')
+ store, runner, authority, owner = _owner(home)
+ try:
+ follow = await _create_bot_chat(owner, authority, home, 'follow-tools')
+ pinned = await _create_bot_chat(owner, authority, home, 'pinned-tools', toolsets=['web'])
+ before = {}
+ for name, live in (('follow', follow), ('pinned', pinned)):
+ with policy_scope(policy_for_source(runner, live.source), authority=authority):
+ before[name] = set(active_policy().toolsets)
+ assert 'web' in before['follow']
+ _profile(home, 'old', 1, 'k', agent={'disabled_toolsets': ['web']})
+ policy = policy_for_source(runner, follow.source)
+ with policy_scope(policy, authority=authority):
+ assert set(active_policy().toolsets) == before['follow'] - {'web'}
+ # The toolsets the turn's agent is built with (``_run_agent_display_settings``).
+ assert set(policy.current_toolsets(policy.config(authority))) == before['follow'] - {'web'}
+ with policy_scope(policy_for_source(runner, pinned.source), authority=authority):
+ assert set(active_policy().toolsets) == before['pinned'] == {'web'}
+ finally:
+ await owner.close()
+ store.close_all_db_handles()