Skip to content

The agent that grows with you

onboarding: bring the Python side under the code-health ratchets

alt-glitch4d99e0a9fd45
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index d759987fb08..7e0c7d14632 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -36,7 +36,7 @@ from agent.surface_switch import (
from agent.turn_context import PreflightCompressionTimedOut, build_turn_context
from hermes_cli.observability.shared_metrics_efficiency import record_cache_break, record_prompt_rebuild
from agent.turn_retry_state import TurnRetryState
-from agent.turn_scripted_prelude import Prelude, run_scripted_prelude
+from agent.turn_scripted_prelude import Prelude, play_prelude
# Phase helpers of the turn loop, bound at import so a source-tree swap cannot load a
# skewed phase mid-turn.
from agent.turn_api_call import handle_api_interrupt, nous_rate_limit_guard, perform_api_call
@@ -1531,6 +1531,24 @@ def _run_api_retry_loop(agent, s: _LoopState) -> Optional[Dict[str, Any]]:
return None
+def _codex_app_server_turn(agent: Any, s: Any) -> Optional[Dict[str, Any]]:
+ """The codex app-server's result for this turn, or None when its failure activated a fallback and the
+ generic loop retries the same user turn."""
+ codex_result = agent._run_codex_app_server_turn(
+ user_message=s.user_message, original_user_message=s.original_user_message,
+ messages=s.messages, effective_task_id=s.effective_task_id,
+ should_review_memory=s._should_review_memory,
+ )
+ from agent.turn_recovery import activate_codex_app_server_fallback
+ if not activate_codex_app_server_fallback(agent, codex_result):
+ return codex_result
+ # Fallback activation rewrote provider/model/api_mode: retry this same user turn on the generic
+ # loop below, keeping codex's projected rows and its failed API call in the turn's accounting.
+ s.api_call_count = int(codex_result.get("api_calls") or 0)
+ s.active_system_prompt = _sync_failover_system_message(agent, None, s.active_system_prompt)
+ return None
+
+
def _run_conversation_turn(
agent,
user_message: Any,
@@ -1622,25 +1640,13 @@ def _run_conversation_turn(
)
# Opt-in runtime: api_mode == codex_app_server hands the whole turn to the codex
# app-server subprocess (see agent/transports/codex_app_server_session.py).
- if agent.api_mode == "codex_app_server":
- codex_result = agent._run_codex_app_server_turn(
- user_message=s.user_message, original_user_message=s.original_user_message,
- messages=s.messages, effective_task_id=s.effective_task_id,
- should_review_memory=s._should_review_memory,
- )
- from agent.turn_recovery import activate_codex_app_server_fallback
- if not activate_codex_app_server_fallback(agent, codex_result):
- return codex_result
- # Fallback activation rewrote provider/model/api_mode: retry this same user turn on the generic
- # loop below, keeping codex's projected rows and its failed API call in the turn's accounting.
- s.api_call_count = int(codex_result.get("api_calls") or 0)
- s.active_system_prompt = _sync_failover_system_message(agent, None, s.active_system_prompt)
-
- _prelude = run_scripted_prelude(agent, s, prelude) if prelude is not None else None
- if _prelude is not None and _prelude.action == "return":
- return _prelude.result
- _prelude_ended_turn = _prelude is not None and _prelude.action == "break"
- while not _prelude_ended_turn and (
+ if agent.api_mode == "codex_app_server" and (codex_result := _codex_app_server_turn(agent, s)) is not None:
+ return codex_result
+
+ _prelude_action, _prelude_result = play_prelude(agent, s, prelude)
+ if _prelude_action == "return":
+ return _prelude_result
+ while _prelude_action != "break" and (
(s.api_call_count < agent.max_iterations and agent.iteration_budget.remaining > 0) or agent._budget_grace_call
):
if _run_phase(begin_iteration, agent, s).action == "break":
diff --git a/agent/turn_scripted_prelude.py b/agent/turn_scripted_prelude.py
index 1e65343834b..af376c9bb9b 100644
--- a/agent/turn_scripted_prelude.py
+++ b/agent/turn_scripted_prelude.py
@@ -45,3 +45,12 @@ def run_scripted_prelude(agent: Any, s: Any, prelude: Prelude) -> Any:
result = tail.get("content") if tail.get("role") == "tool" else None
prelude.close()
return verdict
+
+
+def play_prelude(agent: Any, s: Any, prelude: Optional[Prelude]) -> Tuple[str, Any]:
+ """``("return", result)`` ends the turn now, ``("break", None)`` skips the model call, ``("run", None)`` runs
+ the loop as usual (also when there is no prelude)."""
+ verdict = run_scripted_prelude(agent, s, prelude) if prelude is not None else None
+ if verdict is not None and verdict.action in ("return", "break"):
+ return verdict.action, verdict.result
+ return "run", None
diff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.py
index 1820fee8d7e..ec221165540 100644
--- a/hermes_cli/cli_chat_turn_mixin.py
+++ b/hermes_cli/cli_chat_turn_mixin.py
@@ -250,7 +250,7 @@ class CLIChatTurnMixin:
if note:
prior = getattr(agent, "_gateway_turn_context_notes", "") or ""
agent._gateway_turn_context_notes = f"{prior}\n\n{note}" if prior else note
- except Exception:
+ except Exception: # health: allow BLE001 -- the note is optional; a failure leaves the first turn as it was
logger.debug("first-contact onboarding note failed", exc_info=True)
def _chat_stage_user_message(self, agent, message):
diff --git a/tools/setup_choose_tool.py b/tools/setup_choose_tool.py
index 795c289e3c3..97fc95e4cfe 100644
--- a/tools/setup_choose_tool.py
+++ b/tools/setup_choose_tool.py
@@ -219,8 +219,8 @@ def _connectors_closed() -> Optional[str]:
if load_config().enabled and not current_nous_state() and guest_enabled():
try:
ensure_portal_identity(explicit=True)
- except Exception as exc:
- logger.info("setup_choose: no guest identity for connectors: %s", exc)
+ except Exception: # health: allow BLE001 -- one best-effort mint; on any failure the card says why it is closed
+ logger.info("setup_choose: no guest identity for connectors", exc_info=True)
if connectors_available():
return None
return _NO_CONNECTORS
@@ -273,6 +273,7 @@ def setup_choose_tool(kind: str = "", question: str = "", options=None, multi_se
record_cards(session_id, state)
return json.dumps({**result, **extra}, ensure_ascii=False)
except Exception as exc:
+ logger.exception("setup_choose failed")
return tool_error(f"Failed to get user input: {exc}")
diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.py
index 6f1086e138a..88466bf2699 100644
--- a/tui_gateway/methods_onboarding.py
+++ b/tui_gateway/methods_onboarding.py
@@ -43,6 +43,7 @@ def _(rid, params: dict) -> dict:
finally:
release_or_close(db)
except Exception as e:
+ logger.exception("onboarding.ensure_setup_session failed")
return _err(rid, 5075, str(e))
return _ok(rid, {"profile": setup.name, "session_id": row["id"], "empty": not row["message_count"]})
@@ -80,12 +81,25 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"name": setup.name, "path": str(setup.path), "reset": True})
+# The /initiate-setup slash builtin (methods_tools._SLASH_BUILTINS): the skill plus the facts block as one turn.
+def _cmd_initiate_setup(rid, params, session, name, arg):
+ with _session_profile_runtime_scope(session or {}):
+ enabled, disabled = _session_toolsets(session)
+ tools = _tools_mod("model_tools").get_tool_definitions(
+ enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=True, skip_tool_search_assembly=True)
+ surface = _resolve_agent_platform(_session_source(session))
+ primary = _tools_mod("hermes_cli.setup_profile").primary_profile(_launch_home())
+ message = _tools_mod("agent.initiate_setup_prompt").build_initiate_setup_prompt(
+ surface, [tool["function"]["name"] for tool in tools], primary, (session or {}).get("session_key"))
+ return _ok(rid, {"type": "send", "message": message, "display": "/initiate-setup"})
+
def _onboarding_state_result(rid, change) -> dict:
from hermes_cli.setup_profile import find_setup_profile, onboarding_eligible
try:
state = change()
found = find_setup_profile()
except Exception as e:
+ logger.exception("onboarding state update failed")
return _err(rid, 5076, str(e))
return _ok(rid, {"eligible": onboarding_eligible(), "profile": found[0] if found else None, **state})
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 1ad2e7d8e19..d19dfcf7590 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -785,18 +785,6 @@ def _cmd_init(rid, params, session, name, arg):
extra=arg, cwd=cwd, session_key=skey)})
-def _cmd_initiate_setup(rid, params, session, name, arg):
- with _session_profile_runtime_scope(session or {}):
- enabled, disabled = _session_toolsets(session)
- tools = _tools_mod("model_tools").get_tool_definitions(
- enabled_toolsets=enabled, disabled_toolsets=disabled, quiet_mode=True, skip_tool_search_assembly=True)
- surface = _resolve_agent_platform(_session_source(session))
- primary = _tools_mod("hermes_cli.setup_profile").primary_profile(_launch_home())
- message = _tools_mod("agent.initiate_setup_prompt").build_initiate_setup_prompt(
- surface, [tool["function"]["name"] for tool in tools], primary, (session or {}).get("session_key"))
- return _ok(rid, {"type": "send", "message": message, "display": "/initiate-setup"})
-
-
def _cmd_moa(rid, params, session, name, arg):
# One prompt through the default MoA preset, then restore the prior model (whole-session
# switching goes through the model picker).
@@ -1097,10 +1085,9 @@ def _cmd_skills(rid, params, session, name, arg):
_SLASH_BUILTINS = {
"queue": _cmd_queue, "q": _cmd_queue, "learn": _cmd_learn, "plan": _cmd_plan, "init": _cmd_init,
- "initiate-setup": _cmd_initiate_setup,
"moa": _cmd_moa, "focus": _cmd_focus, "retry": _cmd_retry, "steer": _cmd_steer, "goal": _cmd_goal,
"loop": _cmd_loop, "undo": _cmd_undo, "snapshot": _cmd_snapshot, "snap": _cmd_snapshot,
- "compress": _cmd_compress, "compact": _cmd_compress,
+ "compress": _cmd_compress, "compact": _cmd_compress, "initiate-setup": lambda *a: _cmd_initiate_setup(*a),
"memory": _cmd_memory, "skills": _cmd_skills}
@method("command.dispatch")