Skip to content

The agent that grows with you

fix(gateway): make routing-entry yolo tri-state so untoggled entries follow the launch policy

Teknium65f03b0c1946
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index c1471d9e875..cf7a31eb72a 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -437,11 +437,13 @@ class GatewayAgentCacheMixin:
clear(session_key)
except Exception as e:
logger.debug("Failed to clear %s state for session boundary %s: %s", what, session_key, e)
- # The persisted /yolo copy dies with the in-memory one, or the next turn's restore revives it.
+ # The persisted /yolo copy dies with the in-memory one, or the next turn's restore revives it. None, not
+ # False: the next conversation follows its launch policy again (seeded once per boundary), and a
+ # toggle-less chat stays off.
store = getattr(self, "session_store", None)
if store is not None:
try:
- store.set_session_yolo(session_key, False)
+ store.set_session_yolo(session_key, None)
except Exception:
# Never fails the boundary itself, but a surviving ON would come back after a restart.
logger.warning("Failed to clear persisted yolo for session boundary %s", session_key, exc_info=True)
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index 881c14efa2b..bcdf5c1b0aa 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -634,7 +634,7 @@ class GatewayTurnPrepareMixin:
from gateway.run import _load_gateway_config
from tools.approval_yolo import restore_gateway_yolo
_was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)
- restore_gateway_yolo(session_key, session_entry.yolo is True)
+ restore_gateway_yolo(session_key, session_entry.yolo) # None: TurnRunner seeds the launch policy
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)
diff --git a/gateway/session.py b/gateway/session.py
index e4d43246425..66194428332 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -540,15 +540,17 @@ class SessionEntry:
# older positional construction of transport_profile keeps its meaning.
prompt_pin: Optional[Dict[str, Any]] = None
# Gateway ``/yolo`` bypass for this lane, mirrored from ``tools.approval``'s in-memory set so a restart
- # keeps it; cleared with it at every conversation boundary (``_clear_session_boundary_security_state``).
- yolo: bool = False
+ # keeps it. Tri-state: True/False is an explicit toggle (an OFF stays off, even over a ``--yolo`` launch);
+ # None means nobody toggled it (new, branched, reset, migrated, cron entries, and every conversation
+ # boundary, ``_clear_session_boundary_security_state``), so the session's launch policy applies.
+ yolo: Optional[bool] = None
# Fields (de)serialized verbatim, in wire order (``from_dict`` reads them with
# ``data.get(name, <dataclass default>)``), split around the three ISO-datetime/token keys.
_PLAIN_FIELDS = (
"input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens",
"total_tokens", "last_prompt_tokens", "estimated_cost_usd", "cost_status",
- "expiry_finalized", "suspended", "resume_pending", "resume_reason", "yolo",
+ "expiry_finalized", "suspended", "resume_pending", "resume_reason",
)
_RESET_FIELDS = (
"is_fresh_reset", "was_auto_reset", "auto_reset_reason", "reset_had_activity",
@@ -564,6 +566,8 @@ class SessionEntry:
"chat_type": self.chat_type, "metadata": self.metadata,
}
result.update((name, getattr(self, name)) for name in self._PLAIN_FIELDS)
+ # ``yolo`` keeps the pre-tri-state meaning (ON only) for older readers; ``yolo_toggle`` is authoritative.
+ result["yolo"], result["yolo_toggle"] = self.yolo is True, self.yolo
result["last_resume_marked_at"] = _iso(self.last_resume_marked_at)
result["active_turn_token"] = self.active_turn_token
result["active_turn_started_at"] = _iso(self.active_turn_started_at)
@@ -607,6 +611,9 @@ class SessionEntry:
defaults = {f.name: f.default for f in fields(cls)}
plain = {n: data.get(n, defaults[n]) for n in cls._PLAIN_FIELDS + cls._RESET_FIELDS}
plain["expiry_finalized"] = data.get("expiry_finalized", data.get("memory_flushed", False))
+ # Rows written before the tri-state stored a bare ``yolo`` bool where False also meant "never
+ # toggled": only their ON is a real toggle; False follows the launch policy, as it did then.
+ plain["yolo"] = data["yolo_toggle"] if "yolo_toggle" in data else (True if data.get("yolo") is True else None)
transport_profile = data.get("transport_profile")
return cls(
session_key=session_key, session_id=session_id,
@@ -1111,8 +1118,9 @@ class SessionStore(
self._persist_routing_data(data, generation)
entry.model_override = cleaned
- def set_session_yolo(self, session_key: str, enabled: bool) -> bool:
- """Persist the lane's ``/yolo`` bypass; False when the key has no entry yet or it is unchanged."""
+ def set_session_yolo(self, session_key: str, enabled: Optional[bool]) -> bool:
+ """Persist the lane's ``/yolo`` bypass (None: back to the launch policy); False when the key has no
+ entry yet or it is unchanged."""
def _apply(entry: SessionEntry):
if entry.yolo is enabled:
return False
diff --git a/gateway/session_busy_controls.py b/gateway/session_busy_controls.py
index eb0973f202b..8bec5e197c2 100644
--- a/gateway/session_busy_controls.py
+++ b/gateway/session_busy_controls.py
@@ -87,17 +87,13 @@ async def yolo_config(connection, ref, params, write):
authorize(connection, ref, params, 'session:control' if write else 'session:read')
from gateway.session_policy import policy_for_source
from tools.approval import is_session_yolo_enabled
- from tools.approval_yolo import apply_launch_yolo, toggle_session_yolo
+ from tools.approval_yolo import restore_gateway_yolo, toggle_session_yolo
live = connection.authority.sessions[ref.session_id]
runner = connection.authority.runner
policy = policy_for_source(runner, live.source)
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
- if entry is not None:
- from tools.approval_yolo import restore_gateway_yolo
- restore_gateway_yolo(live.route, entry.yolo is True)
- elif policy is not None and policy.yolo:
- apply_launch_yolo(live.route)
+ restore_gateway_yolo(live.route, getattr(entry, 'yolo', None), launch=bool(policy is not None and policy.yolo))
# After a restart only the persisted copy is set until the next turn re-arms it: still ON.
persisted = getattr(entry, 'yolo', False) is True
enabled = is_session_yolo_enabled(live.route) or persisted
diff --git a/gateway/session_local.py b/gateway/session_local.py
index 27454044021..f96a885e19b 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -167,7 +167,7 @@ def create_local_session(authority, actor, params, *, trusted_policy=None, trust
# Same clock as every other routing entry: the recovery sweeps compare against a
# naive cutoff, and one aware entry aborts the whole iteration.
now = _now()
- entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL, yolo=policy.yolo)
+ entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
commit_local_session(authority.db, epoch=authority.epoch, receipt={
'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)})
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 6b378bdfc1b..f5cd2949ac5 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -76,13 +76,10 @@ 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 tools.approval import is_session_yolo_enabled
- from tools.approval_yolo import apply_launch_yolo, restore_gateway_yolo
+ from tools.approval_yolo import restore_gateway_yolo
store = getattr(authority.runner, 'session_store', None)
entry = store.lookup_by_session_key(route) if store is not None else None
- if entry is not None:
- restore_gateway_yolo(route, entry.yolo is True)
- elif policy.yolo:
- apply_launch_yolo(route)
+ restore_gateway_yolo(route, getattr(entry, 'yolo', None), launch=bool(policy.yolo))
return is_session_yolo_enabled(route)
diff --git a/tests/gateway/test_yolo_launch_tristate.py b/tests/gateway/test_yolo_launch_tristate.py
new file mode 100644
index 00000000000..223562e2acd
--- /dev/null
+++ b/tests/gateway/test_yolo_launch_tristate.py
@@ -0,0 +1,67 @@
+"""Routing entries nobody toggled follow the ``--yolo`` launch policy; only an explicit OFF revokes it."""
+import subprocess
+import sys
+from types import SimpleNamespace
+
+_RESTARTED_OWNER = '''
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+from gateway.config import GatewayConfig
+from gateway.session import SessionStore
+from gateway.session_managed_worker import _session_yolo
+store = SessionStore(sessions_dir=Path(sys.argv[1]), config=GatewayConfig())
+store._db = None
+print('ENABLED', _session_yolo(SimpleNamespace(runner=SimpleNamespace(session_store=store)),
+ sys.argv[2], SimpleNamespace(yolo=True)))
+'''
+
+
+def _store(tmp_path):
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ store = SessionStore(sessions_dir=tmp_path, config=GatewayConfig())
+ store._db = None
+ return store
+
+
+def test_untoggled_entry_keeps_launch_yolo_after_restart_but_explicit_off_stays_off(tmp_path):
+ from gateway.config import Platform
+ from gateway.session import SessionSource
+ store = _store(tmp_path)
+ # Branch/reset/migration/cron/new-session entries are written without a toggle.
+ untouched = store.get_or_create_session(SessionSource(platform=Platform.LOCAL, chat_id='branched', user_id='h'))
+ revoked = store.get_or_create_session(SessionSource(platform=Platform.LOCAL, chat_id='revoked', user_id='h'))
+ store.set_session_yolo(revoked.session_key, False)
+
+ def restarted(key):
+ result = subprocess.run([sys.executable, '-c', _RESTARTED_OWNER, str(tmp_path), key],
+ capture_output=True, text=True, timeout=30)
+ assert result.returncode == 0, result.stderr
+ return result.stdout.strip()
+ assert restarted(untouched.session_key) == 'ENABLED True', 'launch --yolo lost for an entry nobody revoked'
+ assert restarted(revoked.session_key) == 'ENABLED False', 'owner /yolo OFF revived by the launch policy'
+
+
+def test_launch_yolo_reseeds_after_a_session_boundary(tmp_path):
+ """``apply_launch_yolo``: seeded once per session boundary; /new clears the toggle, not the launch."""
+ import gateway.run as gateway_run
+ from gateway.config import Platform
+ from gateway.session import SessionSource
+ from gateway.session_managed_worker import _session_yolo
+ from tools.approval import clear_session
+ store = _store(tmp_path)
+ entry = store.get_or_create_session(SessionSource(platform=Platform.LOCAL, chat_id='bnd', user_id='h'))
+ authority = SimpleNamespace(runner=SimpleNamespace(session_store=store))
+ runner = object.__new__(gateway_run.GatewayRunner)
+ runner.session_store = store
+ launch = SimpleNamespace(yolo=True)
+ try:
+ assert _session_yolo(authority, entry.session_key, launch) is True
+ store.set_session_yolo(entry.session_key, False) # owner /yolo off, then /new
+ clear_session(entry.session_key)
+ assert _session_yolo(authority, entry.session_key, launch) is False
+ runner._clear_session_boundary_security_state(entry.session_key)
+ assert _session_yolo(authority, entry.session_key, launch) is True, 'launch --yolo not re-seeded after /new'
+ finally:
+ clear_session(entry.session_key)
diff --git a/tools/approval_yolo.py b/tools/approval_yolo.py
index cfcdbec4274..948c3d92642 100644
--- a/tools/approval_yolo.py
+++ b/tools/approval_yolo.py
@@ -71,10 +71,18 @@ def apply_launch_yolo(session_key: str) -> None:
approval.enable_session_yolo(session_key)
-def restore_gateway_yolo(session_key: str, persisted: bool) -> None:
- """Restore the authoritative routing value, including OFF, before frozen launch seeding."""
+def restore_gateway_yolo(session_key: str, persisted: Optional[bool], *, launch: bool = False) -> None:
+ """Restore the authoritative routing value, including OFF, before frozen launch seeding.
+
+ ``persisted`` None means nobody toggled this route: the ``--yolo`` launch policy (*launch*) is seeded
+ once per boundary instead, so an untouched entry never reads as a revocation.
+ """
if not session_key:
return
+ if persisted is None:
+ if launch:
+ apply_launch_yolo(session_key)
+ return
with approval._lock:
if session_key in approval._launch_yolo_applied:
return # after restoration, the live toggle remains authoritative in this process