Skip to content

The agent that grows with you

fix(codex): send the app-server service tier Hermes requests, only when it changes

kshitijk4poor9cc737019bfa
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py
index 6e0604c2854..bd73a839f44 100644
--- a/agent/codex_runtime.py
+++ b/agent/codex_runtime.py
@@ -575,6 +575,14 @@ def _codex_turn_effort(agent, model: str | None) -> str | None:
return effort
+def _codex_turn_service_tier(agent) -> str | None:
+ """``turn/start.serviceTier``: the tier Hermes' own Responses path would request this turn (a static
+ ``/fast`` tier pinned in request_overrides, or an open ``auto``/``cold`` window), in codex's words: the
+ OpenAI ``priority`` tier is codex's ``fast``. A tier codex has no word for (``ultrafast``) is not sent."""
+ from agent.fast_mode import effective_request_overrides
+ return {"priority": "fast"}.get(effective_request_overrides(agent).get("service_tier"))
+
+
def _ensure_codex_session(agent, messages: List[Dict[str, Any]] | None = None) -> None:
"""Lazily spawn one CodexAppServerSession per AIAgent (reused across turns, closed by the _cleanup hook).
A live session whose thread was started with a different prompt composition (TUI/Desktop ``/personality``
@@ -712,14 +720,7 @@ def run_codex_app_server_turn(agent, *, user_message: str, original_user_message
model_provider = getattr(agent, "_codex_session_model_provider", None)
wire_model = _codex_wire_model(agent, model_provider)
reasoning_effort = _codex_turn_effort(agent, wire_model)
- service_tier = getattr(agent, "service_tier", None)
- if service_tier == "priority":
- # Hermes uses the OpenAI API name; Codex app-server calls this tier fast.
- service_tier = "fast"
- elif service_tier in {None, "", "normal", "default"}:
- # Send null rather than omitting the field so `/fast off` clears a tier
- # selected by an earlier turn in the same Codex thread.
- service_tier = None
+ service_tier = _codex_turn_service_tier(agent)
try:
_start_codex_thread(agent)
turn = agent._codex_session.run_turn(
diff --git a/agent/transports/codex_app_server_session.py b/agent/transports/codex_app_server_session.py
index 2c15cdb5e6a..b6190292db0 100644
--- a/agent/transports/codex_app_server_session.py
+++ b/agent/transports/codex_app_server_session.py
@@ -29,7 +29,7 @@ logger = logging.getLogger(__name__)
_STDERR_TAIL_LINES = 12 # stderr tail on generic errors: legible, yet enough for a config/auth diagnostic
-_UNSET = object()
+_TIER_UNKNOWN = object() # thread resumed: the tier it carries is not known
# Hermes' tools.terminal.security_mode -> Codex permissions profile id.
# Missing config -> workspace-write (Codex's own default).
@@ -231,6 +231,8 @@ class CodexAppServerSession:
# reads base_url/env_key itself.
self._model = (model or "").strip() or None
self._model_provider = (model_provider or "").strip() or None
+ # The tier this thread last received on turn/start; None = codex's own default, never overridden.
+ self._service_tier_sent: Any = None
# Hermes' composed system prompt (SOUL.md, memory, channel overrides). Sent ONCE per thread as
# ``thread/start.developerInstructions``: codex keeps its own base instructions (tool guidance) and
# inserts this as the first developer message of every model request. ``baseInstructions`` would
@@ -280,6 +282,9 @@ class CodexAppServerSession:
if self._resume_thread_id:
wanted, self._resume_thread_id = self._resume_thread_id, None # one attempt per stored id
thread_id = self._resume_thread(wanted, params)
+ # A resumed thread may carry a tier an earlier process selected (CLI ``/fast`` rebuilds the agent),
+ # so its first turn sends Hermes' tier even when that is a clearing null.
+ self._service_tier_sent = _TIER_UNKNOWN
logger.info("codex app-server thread resumed: id=%s cwd=%s", thread_id[:8], self._cwd)
else:
if self._history_seed:
@@ -291,6 +296,7 @@ class CodexAppServerSession:
raise CodexAppServerError(
code=-32603, message=f"codex thread/start returned no thread id (payload keys: {sorted(result.keys())})",
)
+ self._service_tier_sent = None # a new thread runs codex's own configured tier
logger.info("codex app-server thread started: id=%s profile=%s cwd=%s", thread_id[:8], self._permission_profile, self._cwd)
self._thread_id = thread_id
return thread_id
@@ -447,13 +453,15 @@ class CodexAppServerSession:
def run_turn(
self, user_input: Any, *, model: Optional[str] = None, reasoning_effort: Optional[str] = None,
- service_tier: Any = _UNSET, turn_timeout: float = 600.0,
+ service_tier: Optional[str] = None, turn_timeout: float = 600.0,
notification_poll_timeout: float = 0.25, post_tool_quiet_timeout: float = 90.0,
) -> TurnResult:
"""Send a user message and block until turn/completed, bridging approvals and projecting items.
- model: sent on ``turn/start`` (codex applies it to this and later turns), so an in-place ``/model``
- switch reaches a thread that was started with another model.
+ model / reasoning_effort: sent on ``turn/start`` (codex applies them to this and later turns), so an
+ in-place ``/model`` or effort change reaches a thread that was started with other settings.
+ service_tier: sent only when it differs from what this thread last received, so codex's own configured
+ tier is left alone until Hermes selects one, and ``None`` after a selection clears it.
post_tool_quiet_timeout: if codex emits a tool completion and then goes quiet for this many seconds
without emitting another item or `turn/completed`, log a warning (once per tool result) and keep
@@ -474,11 +482,11 @@ class CodexAppServerSession:
params["model"] = model
if reasoning_effort is not None:
params["effort"] = reasoning_effort
- if service_tier is not _UNSET:
- # An explicit null clears a tier previously selected on this thread.
+ if service_tier != self._service_tier_sent:
params["serviceTier"] = service_tier
ts = self._request_for(result, "turn/start", params, "turn/start")
if ts is not None:
+ self._service_tier_sent = service_tier
self._run_started_turn(result, ts, turn_timeout, notification_poll_timeout, post_tool_quiet_timeout)
self._interrupt_event.clear()
return result
diff --git a/tests/agent/test_codex_app_server_integration.py b/tests/agent/test_codex_app_server_integration.py
index 08ff2d3b176..0f2e8274a26 100644
--- a/tests/agent/test_codex_app_server_integration.py
+++ b/tests/agent/test_codex_app_server_integration.py
@@ -75,7 +75,8 @@ class TestRunConversationCodexPath:
({"enabled": True, "effort": "high"}, "priority", "high", "fast"),
({"enabled": False}, None, "none", None),
# Hermes-only levels are clamped to the route's vocabulary; raw "ultra" fails the turn with 400.
- ({"enabled": True, "effort": "ultra"}, None, "xhigh", None),
+ # A tier codex has no word for is not sent.
+ ({"enabled": True, "effort": "ultra"}, "ultrafast", "xhigh", None),
],
)
def test_effective_runtime_settings_reach_codex_turn(
@@ -102,6 +103,8 @@ class TestRunConversationCodexPath:
model="gpt-5.4",
reasoning_config=reasoning_config,
service_tier=service_tier,
+ # Every surface pins a static /fast tier into request_overrides (resolve_fast_mode_overrides).
+ request_overrides={"service_tier": service_tier} if service_tier else None,
)
with patch.object(agent, "_spawn_background_review", return_value=None):
diff --git a/tests/agent/transports/test_codex_app_server_session.py b/tests/agent/transports/test_codex_app_server_session.py
index e4bdcdd8dbb..d33f8f498c2 100644
--- a/tests/agent/transports/test_codex_app_server_session.py
+++ b/tests/agent/transports/test_codex_app_server_session.py
@@ -417,20 +417,32 @@ class TestRunTurn:
assert params["effort"] == "high"
assert params["serviceTier"] == "fast"
- def test_turn_start_can_clear_service_tier(self):
+ def test_service_tier_is_sent_only_when_it_changes(self):
+ """codex's own configured tier is left alone until Hermes selects one; ``/fast off`` afterwards sends
+ an explicit null to clear it, and an unchanged tier is not re-sent."""
client = FakeClient()
- client.queue_notification(
- "turn/completed",
- threadId="t",
- turn={"id": "tu1", "status": "completed", "error": None},
- )
+ for _ in range(4):
+ client.queue_notification("turn/completed", threadId="t",
+ turn={"id": "turn-fake-001", "status": "completed", "error": None})
s = make_session(client)
-
+ for tier in (None, "fast", "fast", None):
+ s.run_turn("hi", service_tier=tier, turn_timeout=2.0)
+ sent = [p for (m, p) in client.requests if m == "turn/start"]
+ assert ["serviceTier" in p for p in sent] == [False, True, False, True]
+ assert [p.get("serviceTier") for p in sent if "serviceTier" in p] == ["fast", None]
+
+ def test_resumed_thread_receives_the_hermes_tier_even_when_it_is_null(self):
+ """CLI ``/fast`` rebuilds the agent, so ``/fast off`` reaches a resumed thread that may still carry the
+ earlier tier: its first turn sends Hermes' tier, a clearing null included."""
+ client = FakeClient()
+ client.queue_notification("turn/completed", threadId="t",
+ turn={"id": "turn-fake-001", "status": "completed", "error": None})
+ client._request_handler = lambda method, params: (
+ {"thread": {"id": params["threadId"]}} if method == "thread/resume" else {"turn": {"id": "turn-fake-001"}})
+ s = make_session(client, resume_thread_id="stored-1")
s.run_turn("hi", service_tier=None, turn_timeout=2.0)
-
- _, params = next(req for req in client.requests if req[0] == "turn/start")
- assert "serviceTier" in params
- assert params["serviceTier"] is None
+ (_, params), = [r for r in client.requests if r[0] == "turn/start"]
+ assert "serviceTier" in params and params["serviceTier"] is None
def test_tool_iteration_counter_ticks(self):
client = FakeClient()