Skip to content

The agent that grows with you

refactor(hermes_cli): codex_runtime_switch synonym table + _migration_lines; context_switch_guard/credential_lifecycle defensive collapse + doc compaction; config_defaults drop key-restating section comments (values byte-identical)

Tekniume3d78021f3b6
diff --git a/hermes_cli/codex_runtime_switch.py b/hermes_cli/codex_runtime_switch.py
index 18f5224b80f..c511c6cf385 100644
--- a/hermes_cli/codex_runtime_switch.py
+++ b/hermes_cli/codex_runtime_switch.py
@@ -1,8 +1,4 @@
-"""Shared logic for the /codex-runtime slash command.
-
-Both CLI (cli.py) and gateway (gateway/run.py) call into this module so the behavior stays identical
-across surfaces.
-"""
+"""Shared logic for the /codex-runtime slash command (CLI and gateway call into this module)."""
from __future__ import annotations
@@ -16,11 +12,26 @@ logger = logging.getLogger(__name__)
VALID_RUNTIMES = ("auto", "codex_app_server")
+# Human-friendly synonyms accepted by parse_args.
+_ARG_SYNONYMS = {
+ "on": "codex_app_server", "codex": "codex_app_server", "enable": "codex_app_server",
+ "off": "auto", "default": "auto", "disable": "auto", "hermes": "auto",
+}
+
+_HERMES_TOOLS_CALLBACK_NOTE = (
+ "Hermes tool callback registered: codex can now use "
+ "web_search, web_extract, browser_*, vision_analyze, "
+ "image_generate, skill_view, skills_list, text_to_speech, "
+ "kanban_* (worker + orchestrator) via MCP.",
+ " (delegate_task, memory, session_search, todo run "
+ "only on the default Hermes runtime — they need the "
+ "agent loop context.)",
+)
+
@dataclass
class CodexRuntimeStatus:
- """Result of a /codex-runtime invocation. Callers render this however
- suits their surface (CLI uses Rich panels, gateway sends a text message)."""
+ """Result of a /codex-runtime invocation; callers render it per surface (Rich panel / text)."""
success: bool
new_value: Optional[str] = None
@@ -30,47 +41,34 @@ class CodexRuntimeStatus:
def parse_args(arg_string: str) -> tuple[Optional[str], list[str]]:
- """Parse the slash-command argument string. Returns (value, errors).
+ """Parse the slash-command argument string into ``(value, errors)``.
- No args returns the current state (value=None); ``auto``/``codex_app_server``/``on``/``off``
- return that value; anything else is an error.
+ No args → ``(None, [])`` (show current state); a runtime name or synonym → that runtime.
"""
raw = (arg_string or "").strip().lower()
if not raw:
return None, []
- # Accept human-friendly synonyms
- if raw in {"on", "codex", "enable"}:
- return "codex_app_server", []
- if raw in {"off", "default", "disable", "hermes"}:
- return "auto", []
- if raw in VALID_RUNTIMES:
- return raw, []
- return None, [
- f"Unknown runtime {raw!r}. Use one of: auto, codex_app_server, on, off"
- ]
+ value = _ARG_SYNONYMS.get(raw, raw)
+ if value in VALID_RUNTIMES:
+ return value, []
+ return None, [f"Unknown runtime {raw!r}. Use one of: auto, codex_app_server, on, off"]
def get_current_runtime(config: dict) -> str:
- """Read the current `model.openai_runtime` value from a config dict.
- Returns 'auto' for unset / empty / unrecognized values."""
+ """Current ``model.openai_runtime``; 'auto' for unset / empty / unrecognized values."""
if not isinstance(config, dict):
return "auto"
model_cfg = config.get("model") or {}
if not isinstance(model_cfg, dict):
return "auto"
value = str(model_cfg.get("openai_runtime") or "").strip().lower()
- if value in VALID_RUNTIMES:
- return value
- return "auto"
+ return value if value in VALID_RUNTIMES else "auto"
def set_runtime(config: dict, new_value: str) -> str:
- """Mutate the config dict in place to persist the new runtime value.
- Returns the previous value for callers that want to report a delta."""
+ """Persist *new_value* into the config dict in place; returns the previous value."""
if new_value not in VALID_RUNTIMES:
- raise ValueError(
- f"invalid runtime {new_value!r}; must be one of {VALID_RUNTIMES}"
- )
+ raise ValueError(f"invalid runtime {new_value!r}; must be one of {VALID_RUNTIMES}")
old = get_current_runtime(config)
if not isinstance(config.get("model"), dict):
config["model"] = {}
@@ -79,8 +77,7 @@ def set_runtime(config: dict, new_value: str) -> str:
def check_codex_binary_ok() -> tuple[bool, Optional[str]]:
- """Best-effort verification that codex CLI is installed at acceptable
- version. Returns (ok, version_or_message)."""
+ """Best-effort codex CLI install/version check → ``(ok, version_or_message)``."""
try:
from agent.transports.codex_app_server import check_codex_binary
@@ -89,6 +86,38 @@ def check_codex_binary_ok() -> tuple[bool, Optional[str]]:
return False, f"codex check failed: {exc}"
+def _migration_lines(config: dict) -> list[str]:
+ """Run the ~/.codex/config.toml migration and describe it; failures are non-fatal."""
+ lines: list[str] = []
+ try:
+ from hermes_cli.codex_runtime_plugin_migration import migrate
+ mig_report = migrate(config)
+ # The hermes-tools callback is internal plumbing — surfaced separately below.
+ user_servers = [s for s in mig_report.migrated if s != "hermes-tools"]
+ if user_servers:
+ lines.append(f"Migrated {len(user_servers)} MCP server(s): {', '.join(user_servers)}")
+ if mig_report.migrated_plugins:
+ lines.append(
+ f"Migrated {len(mig_report.migrated_plugins)} native "
+ f"Codex plugin(s): {', '.join(mig_report.migrated_plugins)}"
+ )
+ elif mig_report.plugin_query_error:
+ lines.append(f"Codex plugin discovery skipped: {mig_report.plugin_query_error}")
+ if mig_report.wrote_permissions_default:
+ lines.append(
+ f"Default sandbox: {mig_report.wrote_permissions_default} "
+ f"(no approval prompt on every write)"
+ )
+ if "hermes-tools" in mig_report.migrated:
+ lines.extend(_HERMES_TOOLS_CALLBACK_NOTE)
+ lines.append(f" (config: {mig_report.target_path})")
+ for err in mig_report.errors:
+ lines.append(f"⚠ MCP migration: {err}")
+ except Exception as exc:
+ lines.append(f"⚠ MCP migration skipped: {exc}")
+ return lines
+
+
def apply(
config: dict,
new_value: Optional[str],
@@ -97,58 +126,41 @@ def apply(
) -> CodexRuntimeStatus:
"""Top-level entry point used by both CLI and gateway handlers.
- ``config`` is mutated in place when ``new_value`` is set (None means show current state
- only). ``persist_callback`` receives the mutated dict to write it to disk; skipped when None
- (tests).
+ ``config`` is mutated in place when ``new_value`` is set (None means show current state only).
+ ``persist_callback`` receives the mutated dict to write it to disk; skipped when None (tests).
"""
current = get_current_runtime(config)
- # Cache the codex binary check for this apply() call: the enable path
- # would otherwise spawn `codex --version` up to 3 times (state, gate, message).
+ # Cached per apply() call: the enable path would otherwise spawn `codex --version` up to 3x.
_check_binary_cached = functools.cache(check_codex_binary_ok)
- # Read-only call: just report state
if new_value is None:
ok, ver = _check_binary_cached()
msg = (
f"openai_runtime: {current}\n"
f"codex CLI: {'OK ' + ver if ok else 'not available — ' + (ver or 'install with `npm i -g @openai/codex`')}"
)
- return CodexRuntimeStatus(
- success=True,
- new_value=current,
- old_value=current,
- message=msg,
- )
+ return CodexRuntimeStatus(success=True, new_value=current, old_value=current, message=msg)
- # No-config-change paths. For `auto` we return immediately — disabling
- # doesn't touch ~/.codex/. For `codex_app_server`, we fall through to
- # the migration block below: the config value is already correct, but
- # the world state (managed block in ~/.codex/config.toml, hermes-tools
- # MCP callback, plugin discovery) may be stale or missing — common
- # footgun when users pre-set `openai_runtime: codex_app_server` in
- # config.yaml without ever running the slash command. The migration is
- # idempotent by design (it replaces its own managed block in place), so
- # re-running is cheap and safe.
+ # Re-enabling codex_app_server falls through to the migration: the config value is already
+ # correct but the world state (managed block in ~/.codex/config.toml, hermes-tools MCP
+ # callback, plugin discovery) may be stale — a common footgun when users pre-set
+ # `openai_runtime: codex_app_server` by hand. The migration is idempotent so re-running is
+ # cheap and safe. Re-setting `auto` returns immediately (disabling never touches ~/.codex/).
reapplying_enable = new_value == current == "codex_app_server"
if new_value == current and not reapplying_enable:
return CodexRuntimeStatus(
- success=True,
- new_value=current,
- old_value=current,
+ success=True, new_value=current, old_value=current,
message=f"openai_runtime already set to {current}",
)
- # If switching ON, verify codex CLI is installed before persisting —
- # an opt-in toggle that silently fails on the first turn is the
- # worst possible UX. Block here with a clear install hint.
+ # Switching ON: verify codex CLI before persisting — an opt-in toggle that silently fails on
+ # the first turn is the worst possible UX.
if new_value == "codex_app_server":
ok, ver_or_msg = _check_binary_cached()
if not ok:
return CodexRuntimeStatus(
- success=False,
- new_value=None,
- old_value=current,
+ success=False, new_value=None, old_value=current,
message=(
"Cannot enable codex_app_server runtime: "
f"{ver_or_msg or 'codex CLI not available'}\n"
@@ -164,9 +176,7 @@ def apply(
except Exception as exc:
logger.exception("failed to persist openai_runtime change")
return CodexRuntimeStatus(
- success=False,
- new_value=new_value,
- old_value=current,
+ success=False, new_value=new_value, old_value=current,
message=f"updated config in memory but persist failed: {exc}",
)
@@ -179,59 +189,9 @@ def apply(
ok, ver = _check_binary_cached()
if ok:
msg_lines.append(f"codex CLI: {ver}")
- # Auto-migrate Hermes' MCP servers + Codex's installed curated
- # plugins into ~/.codex/config.toml so the spawned codex subprocess
- # sees the same tool surface AND can call back into Hermes for
- # browser/web/delegate_task/vision/memory tools (#7 fix).
- # Failures are non-fatal — the runtime change still proceeds.
- try:
- from hermes_cli.codex_runtime_plugin_migration import migrate
- mig_report = migrate(config)
- # Tools/MCP servers (excluding the hermes-tools callback,
- # which is internal plumbing — surface separately).
- user_servers = [
- s for s in mig_report.migrated if s != "hermes-tools"
- ]
- if user_servers:
- msg_lines.append(
- f"Migrated {len(user_servers)} MCP server(s): "
- f"{', '.join(user_servers)}"
- )
- # Native Codex plugin migration (Linear, GitHub, etc.)
- if mig_report.migrated_plugins:
- msg_lines.append(
- f"Migrated {len(mig_report.migrated_plugins)} native "
- f"Codex plugin(s): {', '.join(mig_report.migrated_plugins)}"
- )
- elif mig_report.plugin_query_error:
- msg_lines.append(
- f"Codex plugin discovery skipped: "
- f"{mig_report.plugin_query_error}"
- )
- # Permissions + Hermes tool callback are always-on production
- # bits the user benefits from knowing about.
- if mig_report.wrote_permissions_default:
- msg_lines.append(
- f"Default sandbox: {mig_report.wrote_permissions_default} "
- f"(no approval prompt on every write)"
- )
- if "hermes-tools" in mig_report.migrated:
- msg_lines.append(
- "Hermes tool callback registered: codex can now use "
- "web_search, web_extract, browser_*, vision_analyze, "
- "image_generate, skill_view, skills_list, text_to_speech, "
- "kanban_* (worker + orchestrator) via MCP."
- )
- msg_lines.append(
- " (delegate_task, memory, session_search, todo run "
- "only on the default Hermes runtime — they need the "
- "agent loop context.)"
- )
- msg_lines.append(f" (config: {mig_report.target_path})")
- for err in mig_report.errors:
- msg_lines.append(f"⚠ MCP migration: {err}")
- except Exception as exc:
- msg_lines.append(f"⚠ MCP migration skipped: {exc}")
+ # Migrate Hermes' MCP servers + Codex's curated plugins into ~/.codex/config.toml so the
+ # spawned codex subprocess sees the same tool surface AND can call back into Hermes.
+ msg_lines.extend(_migration_lines(config))
msg_lines.append(
"OpenAI/Codex turns now run through `codex app-server` "
"(terminal/file ops/patching inside Codex; "
@@ -245,9 +205,6 @@ def apply(
msg_lines.append("OpenAI/Codex turns will use the default Hermes runtime.")
msg_lines.append("Effective on next session.")
return CodexRuntimeStatus(
- success=True,
- new_value=new_value,
- old_value=current,
- message="\n".join(msg_lines),
- requires_new_session=True,
+ success=True, new_value=new_value, old_value=current,
+ message="\n".join(msg_lines), requires_new_session=True,
)
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index d3dbe0d5858..977fc135a90 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1,7 +1,7 @@
-"""Default configuration data for Hermes Agent.
+"""Default configuration data for Hermes Agent: DEFAULT_CONFIG and OPTIONAL_ENV_VARS.
-Pure-data leaf module: DEFAULT_CONFIG and OPTIONAL_ENV_VARS, extracted verbatim from
-hermes_cli/config.py. Must not import from hermes_cli.config.
+Pure-data leaf module — must not import from hermes_cli.config. Comments are the user-facing
+docs of config.yaml.
"""
@@ -911,7 +911,6 @@ DEFAULT_CONFIG = {
},
},
- # Web dashboard settings
"dashboard": {
# Visual theme: "default" | "midnight" | "ember" | "mono" | "cyberpunk" | "rose"
"theme": "default",
@@ -977,7 +976,6 @@ DEFAULT_CONFIG = {
"public_url": "",
},
- # Privacy settings
"privacy": {
"redact_pii": False, # hash user IDs and strip phone numbers from LLM context
},
@@ -1380,7 +1378,6 @@ DEFAULT_CONFIG = {
# IANA timezone (e.g. "Asia/Kolkata", "America/New_York"). Empty = server-local time.
"timezone": "",
- # Slack platform settings (gateway mode)
"slack": {
"require_mention": True, # require @mention to respond in channels
"free_response_channels": "", # comma-separated channel IDs answered without mention
@@ -1393,7 +1390,6 @@ DEFAULT_CONFIG = {
"channel_prompts": {}, # per-channel ephemeral system prompts
},
- # Discord platform settings (gateway mode)
"discord": {
"require_mention": True, # require @mention to respond in server channels
"free_response_channels": "", # comma-separated channel IDs answered without mention
@@ -1468,12 +1464,10 @@ DEFAULT_CONFIG = {
},
},
- # WhatsApp platform settings (gateway mode)
"whatsapp": {
# reply_prefix: None = built-in "⚕ *Hermes Agent*" header; "" disables; \n allowed.
},
- # Telegram platform settings (gateway mode)
"telegram": {
"reactions": False, # add 👀/✅/❌ reactions to messages during processing
# per-chat/topic ephemeral system prompts (topics inherit from parent group)
@@ -1489,7 +1483,6 @@ DEFAULT_CONFIG = {
},
},
- # Mattermost platform settings (gateway mode)
"mattermost": {
"require_mention": True, # require @mention to respond in channels
"free_response_channels": "", # comma-separated channel IDs answered without mention
@@ -1497,7 +1490,6 @@ DEFAULT_CONFIG = {
"channel_prompts": {}, # per-channel ephemeral system prompts
},
- # Matrix platform settings (gateway mode)
"matrix": {
"require_mention": True, # require @mention to respond in rooms
"free_response_rooms": "", # comma-separated room IDs answered without mention
@@ -1839,7 +1831,6 @@ DEFAULT_CONFIG = {
"url": "", # empty = default https://models.dev/api.json
},
- # Network workarounds.
"network": {
# Force IPv4. With broken/unreachable IPv6, Python tries AAAA first and hangs for the
# full TCP timeout before falling back. True skips IPv6 entirely.
@@ -2081,13 +2072,11 @@ DEFAULT_CONFIG = {
},
},
- # ``hermes doctor`` behaviour.
"doctor": {
# Per-probe timeout (seconds) for `hermes doctor --live` real-call probes.
"live_probe_timeout": 10,
},
- # ``hermes update`` behaviour.
"updates": {
# Pre-update backup. quick = snapshot small critical state (pairing JSONs,
# cron jobs, config.yaml, .env, auth.json, profile DBs) into
@@ -2222,7 +2211,6 @@ DEFAULT_CONFIG = {
"paste_collapse_threshold_fallback": 5,
"paste_collapse_char_threshold": 2000,
- # Computer Use (cua-driver) toolset settings.
"computer_use": {
# cua-driver's upstream PostHog telemetry defaults ON; Hermes sets
# CUA_DRIVER_RS_TELEMETRY_ENABLED=0 in every child env unless this is true.
diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.py
index 8bbae187a5c..ffc30e3ddc9 100644
--- a/hermes_cli/config_migrations.py
+++ b/hermes_cli/config_migrations.py
@@ -202,7 +202,9 @@ def _migrate_to_14(results: Dict[str, Any], quiet: bool) -> None:
else:
_place(provider)
config["stt"] = stt
- _commit(config, results, quiet, None, " ✓ Migrated legacy stt.model to provider-specific config")
+ _commit(
+ config, results, quiet, None, " ✓ Migrated legacy stt.model to provider-specific config"
+ )
def _migrate_to_16(results: Dict[str, Any], quiet: bool) -> None:
@@ -249,7 +251,8 @@ def _migrate_to_17(results: Dict[str, Any], quiet: bool) -> None:
if migrated_keys or any(v is not None for v in legacy.values()):
config["compression"] = comp
message = (
- f" ✓ Migrated compression.summary_* → auxiliary.compression: {', '.join(migrated_keys)}"
+ " ✓ Migrated compression.summary_* → auxiliary.compression: "
+ f"{', '.join(migrated_keys)}"
if migrated_keys else " ✓ Removed unused compression.summary_* keys"
)
_commit(config, results, quiet, None, message)
@@ -295,7 +298,8 @@ def _migrate_to_21(results: Dict[str, Any], quiet: bool) -> None:
plugins_cfg["enabled"] = grandfathered
config["plugins"] = plugins_cfg
message = (
- f" ✓ Plugins now opt-in: grandfathered {len(grandfathered)} existing plugin(s) into plugins.enabled"
+ f" ✓ Plugins now opt-in: grandfathered "
+ f"{len(grandfathered)} existing plugin(s) into plugins.enabled"
if grandfathered else
" ✓ Plugins now opt-in: no existing plugins to grandfather. "
"Use `hermes plugins enable <name>` to activate."
@@ -334,7 +338,9 @@ def _migrate_to_23(results: Dict[str, Any], quiet: bool) -> None:
raw_aux = _dict_at(config, "auxiliary")
raw_aux_curator = _dict_at(raw_aux, "curator")
- added_aux = _seed_missing(raw_aux_curator, DEFAULT_CONFIG.get("auxiliary", {}).get("curator", {}))
+ added_aux = _seed_missing(
+ raw_aux_curator, DEFAULT_CONFIG.get("auxiliary", {}).get("curator", {})
+ )
if added_aux:
raw_aux["curator"] = raw_aux_curator
config["auxiliary"] = raw_aux
@@ -362,8 +368,8 @@ def _migrate_to_25(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_29(results: Dict[str, Any], quiet: bool) -> None:
- # 28 → 29: memory/skills tri-state write_mode (on|off|approve) → boolean write_approval. Only
- # "approve" carried gating intent → true; the old "off = block writes" mode is dropped
+ # 28 → 29: memory/skills tri-state write_mode (on|off|approve) → boolean write_approval.
+ # Only "approve" carried gating intent → true; the old "off = block writes" mode is dropped
# (memory_enabled: false disables memory). Only a persisted key is rewritten.
config = read_raw_config()
touched = False
@@ -376,9 +382,14 @@ def _migrate_to_29(results: Dict[str, Any], quiet: bool) -> None:
sub["write_approval"] = (old_norm == "approve")
config[subsystem] = sub
touched = True
- results["config_added"].append(f"{subsystem}.write_mode → write_approval={sub['write_approval']}")
+ results["config_added"].append(
+ f"{subsystem}.write_mode → write_approval={sub['write_approval']}"
+ )
if touched:
- _commit(config, results, quiet, None, " ✓ Renamed write_mode → write_approval (boolean gate)")
+ _commit(
+ config, results, quiet, None,
+ " ✓ Renamed write_mode → write_approval (boolean gate)",
+ )
# 29 → 30 (curator.consolidate defaults to false) is schema-default-only: deep-merge supplies it
@@ -387,7 +398,7 @@ def _migrate_to_29(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_31(results: Dict[str, Any], quiet: bool) -> None:
# 30 → 31: verify_on_stop OFF (one-time). The "auto" sentinel was more noise than signal.
- # Rewrite only when missing or still "auto" — an explicit true/false the user set is preserved.
+ # Rewrite only when missing or still "auto" — an explicit user true/false is preserved.
config = read_raw_config()
raw_agent = _dict_at(config, "agent")
cur = raw_agent.get("verify_on_stop")
@@ -482,7 +493,10 @@ def _migrate_to_34(results: Dict[str, Any], quiet: bool) -> None:
if isinstance(raw_agent, dict):
manual = prompt_text(raw_agent.get("system_prompt", ""))
if manual:
- rendered = {render_personality_prompt(defn) for defn in available_personalities(config).values()}
+ rendered = {
+ render_personality_prompt(defn)
+ for defn in available_personalities(config).values()
+ }
if manual in rendered:
raw_agent["system_prompt"] = ""
config["agent"] = raw_agent
@@ -546,7 +560,7 @@ def _migrate_to_36(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_37(results: Dict[str, Any], quiet: bool) -> None:
- # 36 → 37: delegation concurrency 3 → 10 (10 stays at/below the high-cost warning threshold).
+ # 36 → 37: delegation concurrency 3 → 10 (stays at/below the high-cost warning threshold).
_rewrite_stale_default(
results, quiet, section="delegation", key="max_concurrent_children", old=3, new=10,
added="delegation.max_concurrent_children=10 (was: 3)",
diff --git a/hermes_cli/config_providers.py b/hermes_cli/config_providers.py
index 9edc98b7b05..12b48615059 100644
--- a/hermes_cli/config_providers.py
+++ b/hermes_cli/config_providers.py
@@ -58,7 +58,7 @@ _TRUE_WORDS = frozenset({"true", "1", "yes", "on"})
def _canonical_api_mode(api_mode: str) -> str:
- """Map alias ``api_mode`` spellings to canonical transport names; unknown values pass through."""
+ """Map alias ``api_mode`` spellings to canonical transport names (unknown pass through)."""
cleaned = api_mode.strip()
return _API_MODE_ALIASES.get(cleaned.lower(), cleaned)
@@ -87,7 +87,7 @@ def stringify_provider_map(providers: Any) -> dict:
def find_provider_entry(providers: Any, key: Any) -> Tuple[Any, Optional[Dict[str, Any]]]:
- """Return ``(stored_key, entry)`` matching *key* by string identity (exact hit first, then scan)."""
+ """Return ``(stored_key, entry)`` matching *key* by string identity (exact hit, then scan)."""
if not isinstance(providers, dict):
return None, None
want = coerce_provider_id(key)
@@ -180,7 +180,9 @@ def _normalize_provider_models(models: Any) -> Tuple[Dict[str, Any], bool]:
model_id = item.get("name")
if not isinstance(model_id, str) or not model_id.strip():
continue
- normalized_models[model_id.strip()] = {k: v for k, v in item.items() if k not in {"id", "name"}}
+ normalized_models[model_id.strip()] = {
+ k: v for k, v in item.items() if k not in {"id", "name"}
+ }
return normalized_models, discovered
return {}, discovered
@@ -348,7 +350,7 @@ def providers_dict_to_custom_providers(providers_dict: Any) -> List[Dict[str, An
def get_compatible_custom_providers(
config: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
- """Return a deduplicated list-shaped view over legacy ``custom_providers`` and v12+ ``providers``.
+ """Deduplicated list-shaped view over legacy ``custom_providers`` and v12+ ``providers``.
Runtime and picker flows need one list; the compatibility layer is never materialised back
into config.yaml because it duplicates entries in UIs.
diff --git a/hermes_cli/context_switch_guard.py b/hermes_cli/context_switch_guard.py
index bb2f089511a..50977a6baa5 100644
--- a/hermes_cli/context_switch_guard.py
+++ b/hermes_cli/context_switch_guard.py
@@ -25,9 +25,9 @@ def _estimate_tokens(agent: Any, messages: Optional[List[dict]]) -> Optional[int
return None
if messages is not None:
- protect = int(getattr(cc, "protect_first_n", 3)) + int(
- getattr(cc, "protect_last_n", 20)
- ) + 1
+ protect = (
+ int(getattr(cc, "protect_first_n", 3)) + int(getattr(cc, "protect_last_n", 20)) + 1
+ )
if len(messages) <= protect:
return None
try:
@@ -37,9 +37,7 @@ def _estimate_tokens(agent: Any, messages: Optional[List[dict]]) -> Optional[int
tools = getattr(agent, "tools", None)
return int(
estimate_request_tokens_rough(
- messages,
- system_prompt=system_prompt,
- tools=tools or None,
+ messages, system_prompt=system_prompt, tools=tools or None
)
)
except Exception:
@@ -73,13 +71,14 @@ def merge_preflight_compression_warning(
if cc is None:
return
- # Classic CLI historically omitted custom_providers here while the /model
- # confirmation display threaded agent._custom_providers — so the shrink
- # warning fell through to the hardcoded catalog (e.g. "qwen" → 131072)
- # even when custom_providers[].models.<id>.context_length was 1M.
+ # Fall back to the agent's custom providers: without them the shrink warning used the
+ # hardcoded catalog (e.g. "qwen" → 131072) even when the provider declared 1M.
if custom_providers is None:
custom_providers = getattr(agent, "_custom_providers", None)
+ def _or_agent(value, attr):
+ return value if value is not None else getattr(agent, attr, None)
+
old_ctx = int(getattr(cc, "context_length", 0) or 0)
new_ctx = resolve_display_context_length(
result.new_model,
@@ -89,21 +88,9 @@ def merge_preflight_compression_warning(
model_info=result.model_info,
custom_providers=custom_providers,
config_context_length=config_context_length,
- configured_model=(
- configured_model
- if configured_model is not None
- else getattr(agent, "model", None)
- ),
- configured_provider=(
- configured_provider
- if configured_provider is not None
- else getattr(agent, "provider", None)
- ),
- configured_base_url=(
- configured_base_url
- if configured_base_url is not None
- else getattr(agent, "base_url", None)
- ),
+ configured_model=_or_agent(configured_model, "model"),
+ configured_provider=_or_agent(configured_provider, "provider"),
+ configured_base_url=_or_agent(configured_base_url, "base_url"),
)
if not new_ctx:
return
@@ -112,8 +99,7 @@ def merge_preflight_compression_warning(
if estimate is None:
return
- pct = float(getattr(cc, "threshold_percent", 0.5))
- new_threshold = _threshold_tokens(new_ctx, pct)
+ new_threshold = _threshold_tokens(new_ctx, float(getattr(cc, "threshold_percent", 0.5)))
if estimate < new_threshold:
return
@@ -122,9 +108,7 @@ def merge_preflight_compression_warning(
parts: list[str] = []
if old_ctx and new_ctx < old_ctx:
- parts.append(
- f"Context window shrinks ({old_ctx:,} → {new_ctx:,}). "
- )
+ parts.append(f"Context window shrinks ({old_ctx:,} → {new_ctx:,}). ")
parts.append(
f"Session is ~{estimate:,} tokens; "
f"{result.new_model} allows {new_ctx:,} "
diff --git a/hermes_cli/credential_lifecycle.py b/hermes_cli/credential_lifecycle.py
index 6fecb79f40d..c5225598c8c 100644
--- a/hermes_cli/credential_lifecycle.py
+++ b/hermes_cli/credential_lifecycle.py
@@ -1,12 +1,10 @@
"""Unified provider-credential lifecycle across every store Hermes reads.
-* #51071 / #59761 — deleting a key removes it from ``.env`` but the stale ``credential_pool`` entry
-(and ``provider_models_cache.json`` row) survives, so the provider keeps appearing in the model
-picker, even across restarts (the pool loader is additive-only).
-
-This module is the single choke point: every surface that saves or removes a provider credential
-should route through :func:`save_provider_env_credential` / :func:`remove_provider_env_credential`
-so all three stores stay consistent.
+Deleting a key from ``.env`` alone leaves the stale ``credential_pool`` entry (and the
+``provider_models_cache.json`` row) behind, so the provider keeps appearing in the model picker
+even across restarts (the pool loader is additive-only). Every surface that saves or removes a
+provider credential should route through :func:`save_provider_env_credential` /
+:func:`remove_provider_env_credential` so all stores stay consistent.
"""
from __future__ import annotations
@@ -50,12 +48,11 @@ def _for_each_provider(providers: List[str], import_path: str, *args: Any) -> No
def _prune_env_pool_entries(env_var: str) -> List[str]:
- """Drop ``credential_pool`` entries seeded from ``env:<env_var>``.
+ """Drop ``credential_pool`` entries seeded from ``env:<env_var>``; return providers pruned.
Operates across ALL providers: the source names the env var unambiguously and shared vars like
GITHUB_TOKEN may seed more than one provider. Entries with any other source (OAuth,
device-code, manual, borrowed-CLI) and ``providers.<id>`` blocks are preserved verbatim.
- Returns the provider ids that had entries pruned.
"""
from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
@@ -66,48 +63,36 @@ def _prune_env_pool_entries(env_var: str) -> List[str]:
pool = auth_store.get("credential_pool")
if not isinstance(pool, dict):
return pruned
- changed = False
for provider in list(pool.keys()):
entries = pool[provider]
if not isinstance(entries, list):
continue
- kept = [
- entry
- for entry in entries
- if not (isinstance(entry, dict) and entry.get("source") == source)
- ]
+ kept = [e for e in entries if not (isinstance(e, dict) and e.get("source") == source)]
if len(kept) == len(entries):
continue
- changed = True
pruned.append(provider)
if kept:
pool[provider] = kept
else:
del pool[provider]
- if changed:
+ if pruned:
_save_auth_store(auth_store)
return pruned
def _scrub_config_yaml_mirrors(old_value: str, new_value: str | None) -> List[str]:
- """Reconcile config.yaml api_key mirrors that hold ``old_value``.
-
- Value-matched on purpose: we only touch a config entry when it provably holds the SAME
- credential that just changed in ``.env`` — an independent key the user configured for a
- different endpoint is left alone.
+ """Reconcile config.yaml api_key mirrors holding ``old_value``; return the dotted paths touched.
- ``new_value=None`` removes the mirror field; a string replaces it. Operates on the RAW user
- config (never the defaults-merged view) so the write doesn't bake defaults into the user's file.
- Returns the dotted paths that were updated (names only — never values).
+ Value-matched on purpose: only an entry that provably holds the SAME credential that just
+ changed in ``.env`` is touched — an independent key for a different endpoint is left alone.
+ ``new_value=None`` removes the field; a string replaces it. Operates on the RAW user config so
+ the write doesn't bake defaults into the user's file. Paths only — never values.
"""
if not old_value:
return []
from utils import atomic_yaml_write, fast_safe_load
- from hermes_cli.config import (
- get_config_path,
- require_readable_config_before_write,
- )
+ from hermes_cli.config import get_config_path, require_readable_config_before_write
config_path = get_config_path()
if not config_path.exists():
@@ -122,17 +107,12 @@ def _scrub_config_yaml_mirrors(old_value: str, new_value: str | None) -> List[st
touched: List[str] = []
- def _fix(
- section: Any,
- key_path: str,
- fields: tuple[str, ...] = ("api_key", "api"),
- ) -> None:
+ def _fix(section: Any, key_path: str, fields: tuple[str, ...] = ("api_key", "api")) -> None:
+ # "api" is the legacy alias for model.api_key in older configs. In the keyed ``providers``
+ # schema ``api`` means the base_url, not a credential, so that section passes
+ # ``fields=("api_key",)``.
if not isinstance(section, dict):
return
- # "api" is the legacy alias for model.api_key kept by older configs.
- # NOTE: in the keyed ``providers`` schema ``api`` means the base_url,
- # not a credential (see ``get_compatible_custom_providers``), so that
- # section passes ``fields=("api_key",)`` to avoid touching a base_url.
for field in fields:
current = section.get(field)
if isinstance(current, str) and current == old_value:
@@ -157,13 +137,10 @@ def _scrub_config_yaml_mirrors(old_value: str, new_value: str | None) -> List[st
for name, entry in custom.items():
_fix(entry, f"custom_providers.{name}")
- # The keyed ``providers`` schema (v12+) is where the dashboard/desktop
- # write custom-endpoint credentials — ``providers.<id>.api_key``. It is a
- # real inline secret and higher-precedence than the env var, so a stale
- # copy left here shadows a rotation (persistent 401 with a key the UI no
- # longer shows, #62269) and survives a removal that promised to clear the
- # credential from EVERY store. Scrub only ``api_key``; ``api`` here is the
- # base_url alias, not a credential.
+ # ``providers.<id>.api_key`` (v12+) is where dashboard/desktop write custom-endpoint
+ # credentials. It is a real inline secret with higher precedence than the env var, so a stale
+ # copy shadows a rotation (persistent 401 with a key the UI no longer shows) and survives a
+ # removal that promised to clear EVERY store.
keyed_providers = user_config.get("providers")
if isinstance(keyed_providers, dict):
for provider_id, entry in keyed_providers.items():
@@ -180,20 +157,17 @@ def purge_env_credential_references(
) -> Dict[str, Any]:
"""Remove non-.env references to an env-var credential.
- Prunes env-seeded pool entries and (optionally) the affected rows in
- ``provider_models_cache.json`` so the model picker stops advertising a provider whose key is
- gone.
+ Prunes env-seeded pool entries and (optionally) the affected ``provider_models_cache.json`` rows
+ so the model picker stops advertising a provider whose key is gone.
"""
pruned = _prune_env_pool_entries(env_var)
providers = sorted(set(pruned) | set(_providers_for_env_var(env_var)))
- # Make the removal sticky the same way `hermes auth remove` does: a
- # lingering shell export (or another live process's os.environ) would
- # otherwise re-seed the pool entry on the next load_pool(). The matching
- # save path lifts the suppression on an explicit re-add.
+ # Make the removal sticky the same way `hermes auth remove` does: a lingering shell export (or
+ # another live process's os.environ) would otherwise re-seed the pool entry on the next
+ # load_pool(). The save path lifts the suppression on an explicit re-add.
_for_each_provider(providers, "hermes_cli.auth.suppress_credential_source", f"env:{env_var}")
if clear_models_cache and providers:
- # Cache cleanup is best-effort — a failure here must not block
- # the credential removal itself.
+ # Best-effort — a cache failure must not block the credential removal itself.
_for_each_provider(providers, "hermes_cli.models.clear_provider_models_cache")
return {"pool_pruned": pruned, "providers": providers}
@@ -201,16 +175,12 @@ def purge_env_credential_references(
def save_provider_env_credential(env_var: str, value: str) -> Dict[str, Any]:
"""Save/update a credential in ``.env`` and reconcile every mirror.
- After the ``.env`` write, any config.yaml mirror that held the PREVIOUS value of this var
- (``model.api_key`` etc.) is updated to the new value so a stale higher-precedence copy cannot
- shadow the rotation (#62269).
-
- The save also forces an immediate ``load_pool()`` for every provider registered against this env
- var so the env-seeded ``credential_pool`` entry is materialized to ``auth.json`` right now — the
- live runtime reads from the pool, and before #96058 the Desktop "Save" action only touched
- ``.env`` while ``auth.json``'s mtime stayed unchanged, so an OpenCode Go (or any other env-
- backed provider) request kept 401'ing until the user ran ``hermes auth add <provider> --type
- api-key`` separately.
+ Any config.yaml mirror that held the PREVIOUS value (``model.api_key`` etc.) is updated so a
+ stale higher-precedence copy cannot shadow the rotation. The save also forces an immediate
+ ``load_pool()`` for every provider registered against this env var so the env-seeded
+ ``credential_pool`` entry is materialized to ``auth.json`` now — the live runtime reads from
+ the pool, and a ``.env``-only write left env-backed providers 401'ing until the user ran
+ ``hermes auth add`` separately.
"""
from hermes_cli.config import load_env, save_env_value
@@ -221,17 +191,12 @@ def save_provider_env_credential(env_var: str, value: str) -> Dict[str, Any]:
if value and old_value and old_value != value:
config_updates = _scrub_config_yaml_mirrors(old_value, value)
- # A prior UI/CLI removal may have suppressed this env source; a fresh
- # save is an explicit re-add, so lift the suppression for every provider
- # that reads this var.
+ # A prior removal may have suppressed this env source; a fresh save is an explicit re-add.
providers = _providers_for_env_var(env_var)
_for_each_provider(providers, "hermes_cli.auth.unsuppress_credential_source", f"env:{env_var}")
- # Materialize the env-seeded credential_pool entry to auth.json NOW so the
- # next request authenticates against the just-saved key. ``load_pool`` is
- # idempotent and additive-only for env sources (#9331), so re-running it
- # is safe even when the pool already had this entry. Best-effort: a
- # failure here must not mask the successful .env write above.
+ # ``load_pool`` is idempotent and additive-only for env sources, so re-running is safe even when
+ # the pool already had this entry. Best-effort: never masks the successful .env write above.
_for_each_provider(providers, "agent.credential_pool.load_pool")
return {"ok": True, "key": env_var, "config_updates": config_updates}
@@ -242,7 +207,7 @@ def remove_provider_env_credential(env_var: str) -> Dict[str, Any]:
Clears the ``.env`` entry (and process env), prunes env-seeded ``credential_pool`` entries,
drops the affected providers' model-cache rows, and removes any config.yaml mirror holding the
- same value. OAuth/device-code/manual credentials are preserved (see module docstring).
+ same value. OAuth/device-code/manual credentials are preserved.
"""
from hermes_cli.config import load_env, remove_env_value