========== YENİ KOMUT | 21.09.2026 16:34:40 ==========
81-_PARSE_FAILURE_FALLBACK_MSG = {
82- "last-known-good": (
83- "Keeping the previously loaded config for this process — "
84- "edits to config.yaml are being IGNORED until the YAML is fixed."),
85- "refuse-write": (
86- "REFUSING to write config.yaml so the existing file is preserved. "
87- "Fix the YAML (hermes config edit) and retry.")}
88-_PARSE_FAILURE_DEFAULTS_MSG = (
89: "Falling back to default config — every user override (auxiliary providers, fallback chain, "
90- "model settings) is being IGNORED. Fix the YAML and restart.")
91-
92-
93-def _warn_config_parse_failure(
94- config_path: Path, exc: Exception, *, fallback: str = "defaults") -> None:
95- """Surface a config.yaml parse failure to log and stderr (once per file signature).
96: Silent fallback to ``DEFAULT_CONFIG`` drops every user override, so this must be loud.
97-
98- ``fallback`` selects the message wording: ``"defaults"`` (fresh process, nothing else to serve) or
99- ``"last-known-good"`` (in-process retention of the previously loaded config — see the codex#31188 port
100- in ``_load_config_impl``).
101- """
102- try:
103- st = config_path.stat()
104- key = (str(config_path), st.st_mtime_ns, st.st_size)
--
202-_LAST_EXPANDED_CONFIG_BY_PATH: Dict[str, Any] = {}
203-# path -> (user_mtime_ns, user_size, managed_mtime_ns, managed_size, merged, env_ref_snapshot).
204-# load_config() returns a deepcopy of the cached value while the signature matches (skips
205-# safe_load + merge + normalize + expand, ~13 ms). Writers use atomic_yaml_write (fresh inode
206-# -> new mtime_ns) so no explicit invalidation is needed. The managed-file signature is folded
207-# in so editing the managed-scope config.yaml invalidates, and the env snapshot invalidates
208-# when a referenced ${VAR} changes value (late .env load, in-process rotation).
209-# (path, mtime_ns, size) -> cached expanded config dict. load_config() returns a deepcopy of the cached
210:# value when the file hasn't changed since the last load, skipping yaml.safe_load + _deep_merge +
211-# _normalize_* + _expand_env_vars (~13 ms/call). save_config() + migrate_config() write via
212-# atomic_yaml_write which produces a fresh inode, so stat() sees a new mtime_ns and the next load
213-# repopulates automatically — no explicit invalidation hook. See #58514.
214-_LOAD_CONFIG_CACHE: Dict[str, Tuple[int, int, int, int, Dict[str, Any], Dict[str, Optional[str]]]] = {}
215-# path -> (mtime_ns, size, raw yaml dict) for read_raw_config() (no defaults merged in).
216-_RAW_CONFIG_CACHE: Dict[str, Tuple[int, int, Dict[str, Any]]] = {}
217-
218-# Env var names written to .env that aren't in OPTIONAL_ENV_VARS (managed by setup/provider
--
658- if key in _HERMES_HOME_ENSURED and home.is_dir():
659- return
660- from hermes_cli.config_home import initialize_home
661- initialize_home(home, _HERMES_HOME_SUBDIRS, _HERMES_HOME_ENSURED)
662-
663-
664-# ---- Config loading/saving ----
665-
666:from hermes_cli.config_defaults import DEFAULT_CONFIG, OPTIONAL_ENV_VARS # noqa: E402,F401
667-from hermes_cli.config_providers import ( # noqa: E402,F401 (re-exported; callers/tests use hermes_cli.config.<name>)
668- _API_MODE_ALIASES, _CAMEL_ALIASES, _KNOWN_PROVIDER_KEYS, _PROVIDER_NORMALIZE_WARNED,
669- _canonical_api_mode, _coerce_ssl_verify, _custom_provider_entry_to_provider_config,
670- _entries_for_route, _normalize_custom_provider_entry, _normalize_provider_models,
671- _pick_provider_base_url, _route_model_cfg, _warn_once_per_provider,
672- apply_custom_provider_extra_headers_to_client_kwargs,
673- apply_custom_provider_tls_to_client_kwargs, coerce_provider_id, find_provider_entry,
674- get_compatible_custom_providers, get_custom_provider_context_length,
--
965- continue
966- full_key = key if not prefix else f"{prefix}.{key}"
967- if key not in current:
968- missing.append({"key": full_key, "default": default_value,
969- "description": f"New config option: {full_key}"})
970- elif isinstance(default_value, dict) and isinstance(current.get(key), dict):
971- _check(default_value, current[key], full_key)
972-
973: _check(DEFAULT_CONFIG, load_config())
974- return missing
975-
976-
977-def get_missing_skill_config_vars() -> List[Dict[str, Any]]:
978- """Return skill-declared config vars (``skills.config.<key>``) that are missing or empty."""
979- try:
980- from agent.skill_utils import discover_all_skill_config_vars, SKILL_CONFIG_PREFIX
981- except Exception:
--
1009-def check_config_version(*, raise_on_parse_error: bool = False) -> Tuple[int, int]:
1010- """Return ``(current_version, latest_version)`` from the raw on-disk config.
1011- Reads the raw file rather than ``load_config()``: the deep-merge would make a file lacking
1012- ``_config_version`` inherit the latest version, hiding that the schema was never migrated.
1013- Invalid YAML gets a parse warning, not an automatic schema rewrite. Tolerant runtime status
1014- callers keep the historical latest/latest fallback for malformed YAML; mutation and explicit
1015- validation paths set ``raise_on_parse_error`` so a parse failure or a non-mapping root cannot
1016- be mistaken for an up-to-date config."""
1017: latest = _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1
1018- config_path = get_config_path()
1019- if not config_path.exists():
1020- return latest, latest
1021-
1022- try:
1023- with open(config_path, encoding="utf-8") as f:
1024- config = fast_safe_load(f)
1025- except Exception as e:
--
1041- f"a mapping, got {type(config).__name__}"
1042- )
1043- config = {}
1044- return _coerce_config_version(config.get("_config_version")), latest
1045-
1046-
1047-# ---- Config structure validation ----
1048-
1049:# DEFAULT_CONFIG is the single source of truth for documented roots; the set is derived so new
1050-# defaults are accepted automatically. These optional/legacy roots are valid on disk but
1051:# intentionally absent from DEFAULT_CONFIG (omitted when unused / alternate schema forms).
1052-_EXTRA_KNOWN_ROOT_KEYS = {
1053- "custom_providers", # legacy list form; modern equivalent is providers: {}
1054- "fallback_model", # optional single dict or chain list; omitted when disabled
1055- "mcp_servers", # MCP server definitions written by setup/tools flows
1056- "image_gen", # agent/image_gen_registry.py
1057- "video_gen", # agent/video_gen_registry.py
1058- "plugins", # plugin enable/disable lists (hermes_cli/plugins_cmd.py)
1059- "smart_model_routing", # written by the setup wizard
--
1063- "tool_gateway_declined_tools", # per-tool Tool Gateway offer declines
1064- # Top-level forms read/bridged by gateway/config.py:
1065- "group_sessions_per_user", "thread_sessions_per_user",
1066- "stt_echo_transcripts", "reset_triggers", "always_log_local", "filter_silence_narration",
1067- "multiplex_profiles", "profile_routes", "platforms", "require_mention",
1068- "unauthorized_dm_behavior", "signal",
1069- "timeouts", # unified timeout resolution section (agent/deadline.py)
1070-}
1071:_KNOWN_ROOT_KEYS = frozenset(DEFAULT_CONFIG.keys()) | _EXTRA_KNOWN_ROOT_KEYS
1072-
1073-# Valid fields inside a custom_providers list entry (key_env is read at runtime by
1074:# runtime_provider.py and auxiliary_client.py).
1075-_VALID_CUSTOM_PROVIDER_FIELDS = {
1076- "name", "base_url", "api_key", "api_mode", "model", "models",
1077- "context_length", "rate_limit_delay", "extra_body",
1078- "ssl_ca_cert", "ssl_verify", "key_env"}
1079-
1080-# Fields that look like they should be inside custom_providers, not at root
1081-_CUSTOM_PROVIDER_LIKE_FIELDS = {"base_url", "api_key", "rate_limit_delay", "api_mode"}
1082-
--
1317- fixes = sanitize_env_file()
1318- if fixes and not quiet:
1319- print(f" ✓ Normalized .env line formatting ({fixes} line(s) changed)")
1320- except Exception:
1321- pass # best-effort; never block migration on sanitize failure
1322-
1323- # Auto-migration support floor (v12): an EXPLICIT on-disk ``_config_version`` below the
1324- # floor is NOT migrated and NOT rewritten — surface a message and leave the file untouched
1325: # (deep-merge supplies defaults at read time). A config with NO version key is a fresh
1326- # minimal config, not an ancient install: it gets the normal ladder and a version stamp.
1327- # Missing/unparseable files never trip the floor gate.
1328- # Imported lazily because the steps call back into this module.
1329- from hermes_cli.config_migrations import (
1330- SUPPORT_FLOOR_VERSION, run_migrations, support_floor_message)
1331-
1332- try:
1333- has_explicit_version = "_config_version" in read_user_config_raw()
--
1363- print(f" Get your key at: {var['url']}")
1364- if not _prompt_and_save_env(var["name"], var, f" {var['prompt']}: ", results):
1365- results["warnings"].append(f"Skipped {var['name']} - some features may not work")
1366- print()
1367-
1368- if interactive and not quiet:
1369- _offer_new_optional_env_vars(current_ver, latest_ver, results)
1370-
1371: # New default keys are NOT materialised to disk (load_config() deep-merges DEFAULT_CONFIG at
1372- # read time); this list only feeds the "N new config option(s)" display.
1373- results["config_added"].extend(field["key"] for field in get_missing_config_fields())
1374-
1375- if current_ver < latest_ver and not floor_refused:
1376- config = read_raw_config()
1377- config["_config_version"] = latest_ver
1378- _persist_migration(config)
1379-
--
1498- Omitted top-level sections are preserved; shared dict sections deep-merge so one nested key
1499- can change without dropping siblings on disk. Key REMOVALS are not supported here —
1500- migrations go through ``_persist_migration`` with a full ``read_raw_config()`` dict."""
1501- result = copy.deepcopy(override)
1502- for key, value in raw.items():
1503- if key not in result:
1504- result[key] = copy.deepcopy(value)
1505- elif isinstance(result.get(key), dict) and isinstance(value, dict):
1506: result[key] = _deep_merge(value, result[key])
1507- return result
1508-
1509-
1510:def _deep_merge(base: dict, override: dict) -> dict:
1511- """Recursively merge *override* into *base*: dict-over-dict recurses (so overriding one leaf
1512- keeps sibling defaults), and ``None`` over a dict section is ignored.
1513-
1514- An empty section key in config.yaml (``terminal:`` with no value) parses as YAML ``None``; treating that
1515- as an override would replace the entire default dict with ``None`` and crash every downstream consumer
1516- that expects a mapping (#58277).
1517- """
1518- result = base.copy()
1519- for key, value in override.items():
1520- over_dict = isinstance(result.get(key), dict)
1521- if over_dict and isinstance(value, dict):
1522: result[key] = _deep_merge(result[key], value)
1523- elif not (over_dict and value is None):
1524- result[key] = value
1525- return result
1526-
1527-
1528-def _strip_dotted_keys(cfg: dict, dotted_keys: set) -> Tuple[dict, set]:
1529- """Remove dotted leaf keys from *cfg* in place -> ``(cfg, keys_actually_present)``.
1530- ``save_config`` drops managed-scope leaves this way so a bulk write never persists a user
--
1704- elif path:
1705- paths.add(path)
1706-
1707- _walk(config, ())
1708- return paths
1709-
1710-
1711-def _strip_default_values(
1712: config: Dict[str, Any], defaults: Dict[str, Any] = DEFAULT_CONFIG,
1713- preserve_keys: Optional[Set[Tuple[str, ...]]] = None) -> Dict[str, Any]:
1714- """Return *config* without keys whose values match *defaults*.
1715- Paths in *preserve_keys* (explicitly present in the user's raw config) are always kept even
1716- when equal to the default. Dicts whose every child is stripped are removed entirely so
1717- default-only subtrees never bloat ``config.yaml``."""
1718- preserve_keys = {("_config_version",)} | set(preserve_keys or ())
1719-
1720- def _strip(value: Any, default: Any, path: Tuple[str, ...]) -> Any:
--
1983-
1984-
1985-def atomic_config_write(config_path: Path, data: Any, **kwargs: Any) -> None:
1986- """Fail-closed atomic write for ``config.yaml`` (``require_readable_config_before_write`` first)."""
1987- require_readable_config_before_write(config_path)
1988- atomic_yaml_write(config_path, data, **kwargs)
1989-
1990-
1991:def load_config() -> Dict[str, Any]:
1992: """Load the merged configuration (DEFAULT_CONFIG + config.yaml + managed scope, env-expanded).
1993- Cached on the file signature; returns a deepcopy since most call sites mutate the result.
1994- Read-only hot paths should use ``load_config_readonly()`` to skip the deepcopy."""
1995- return _load_config_impl(want_deepcopy=True)
1996-
1997-
1998:def load_config_readonly() -> Dict[str, Any]:
1999- """``load_config()`` without the defensive deepcopy (~half of the 265us cache-hit cost).
2000- **Mutating the returned dict (or any nested structure) corrupts the in-process cache for
2001- every subsequent caller** — only for code paths that never write to the result."""
2002- return _load_config_impl(want_deepcopy=False)
2003-
2004-
2005-def _ensure_dict(parent: Dict[str, Any], key: str) -> Dict[str, Any]:
2006- """Return ``parent[key]`` as a dict, replacing a missing or non-dict value with ``{}``."""
--
2086- should_override = file_has_terminal_config if override is None else override
2087-
2088- cfg = config if config is not None else load_config_readonly()
2089- terminal_cfg = cfg.get("terminal", {}) if isinstance(cfg, dict) else {}
2090- if not isinstance(terminal_cfg, dict):
2091- return target
2092-
2093- # A caller-supplied config is its own source of explicit keys; otherwise only keys present
2094: # in raw config.yaml may override existing env values (DEFAULT_CONFIG keys are backfill-only).
2095- explicit_keys = terminal_cfg.keys() if config is not None else raw_terminal_cfg.keys()
2096- backend_sources = (terminal_cfg.get("backend"), target.get("TERMINAL_ENV"))
2097- if not (config is not None or "backend" in raw_terminal_cfg):
2098- backend_sources = backend_sources[::-1] # env wins when the file did not set backend
2099- terminal_backend = str(backend_sources[0] or backend_sources[1] or "")
2100-
2101- for cfg_key, env_var in TERMINAL_CONFIG_ENV_MAP.items():
2102- if cfg_key not in terminal_cfg:
--
2133- return user_sig, (*(user_sig or (0, 0)), *managed_sig)
2134-
2135-
2136-def _last_known_good_fallback(config_path: Path, path_key: str, cache_sig, exc: Exception) -> Optional[Dict[str, Any]]:
2137- """Warn about a parse failure and return the last-known-good config, or None (-> defaults).
2138- A parse failure must not silently replace the effective config with defaults — that drops
2139- EVERY user override, including security-critical ``approvals.deny`` rules, when a gateway
2140- user mid-edits config.yaml into broken YAML. Keep serving the last good config until fixed."""
2141: # Falling through to DEFAULT_CONFIG here drops EVERY user override — including security-critical
2142- # ``approvals.deny`` rules, which are supposed to block commands even under yolo. Within a running
2143- # process we still have the last successfully loaded config — keep serving it until the file is fixed.
2144- # See #31188.
2145- lkg = _LAST_EXPANDED_CONFIG_BY_PATH.get(path_key)
2146- _warn_config_parse_failure(
2147- config_path, exc, fallback="last-known-good" if lkg is not None else "defaults")
2148- if lkg is None:
2149- return None
--
2153- if cache_sig is not None:
2154- # Cache under the corrupt file's signature (empty env snapshot: always valid) so repeated
2155- # loads don't re-parse; fixing the file changes the signature and reloads normally.
2156- _LOAD_CONFIG_CACHE[path_key] = (*cache_sig, lkg_copy, {})
2157- return lkg_copy
2158-
2159-
2160-def _merge_managed_overlay(expanded: Dict[str, Any]) -> Tuple[Dict[str, Any], Any]:
2161: """Apply the managed-scope overlay; returns ``(merged, managed_config_or_falsy)``.
2162- Managed wins at the leaf and is applied AFTER user expansion so a user ``${VAR}`` cannot shadow
2163- a managed literal: managed values expand only against the process environment. This
2164- deliberately inverts the usual env-over-config precedence for the keys the managed layer pins
2165- (docs/design/managed-scope.md §4.1)."""
2166- managed_config = managed_scope.load_managed_config()
2167- if not managed_config:
2168- return expanded, managed_config
2169- # Same canonicalization as the user config BEFORE merging (parity with
2170- # managed_scope.apply_managed_overlay) so the merged result never exposes a nested dict.
2171- managed_normalized = _normalize_root_model_keys(managed_config)
2172- if isinstance(managed_normalized.get("model"), str):
2173- managed_normalized = dict(managed_normalized)
2174- managed_normalized["model"] = {"default": managed_normalized["model"]}
2175: return _deep_merge(expanded, _expand_env_vars(managed_normalized)), managed_config
2176-
2177-
2178-def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
2179- with _CONFIG_LOCK:
2180- ensure_hermes_home()
2181- config_path = get_config_path()
2182- path_key = str(config_path)
2183-
2184- user_sig, cache_sig = _load_config_cache_sig(config_path)
2185-
root@213-238-170-219:/home/hermes/.hermes/hermes-agent#