The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(config): config set refuses a wrong-shaped value for a list/mapping key
teknium10972b4819a1a
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 2bce6b8ddc0..79ea3181c31 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -3413,20 +3413,59 @@ def _coerce_config_set_value(key: str, value: str) -> Any:return valuetry:parsed = yaml.safe_load(value)- except yaml.YAMLError:- print(- f"Warning: value for '{key}' looks like a list/mapping but is "- f"not valid YAML/JSON; storing as string. Most isinstance-gated "- f"readers will ignore a string here.", file=sys.stderr)- return value+ except yaml.YAMLError as exc:+ # Storing the text as a string here used to be a warning; every isinstance-gated reader+ # then ignored the value while `config get` echoed it back (#114471). Refuse instead.+ detail = str(getattr(exc, "problem", None) or exc).splitlines()[0]+ _exit_invalid(+ f"✗ Value for '{key}' looks like a list/mapping but is not valid YAML/JSON "+ f"({detail}) — nothing was written.\n"+ " Fix the literal, or quote it (e.g. \"'[text'\") to store a plain string.")if isinstance(parsed, (list, dict)):return parsed- print(- f"Warning: value for '{key}' looks like a list/mapping but "- f"parsed as {type(parsed).__name__}; storing as string.", file=sys.stderr)+ # A quoted literal ("'[text'") parses to a scalar: that is the deliberate way to store one.return value+# Legacy roots absent from DEFAULT_CONFIG whose container type is nonetheless fixed.+_LEGACY_CONTAINER_TYPES = {"custom_providers": "list"}+++def _expected_container_type(key: str, user_config: Dict[str, Any]) -> Optional[str]:+ """``"list"`` / ``"mapping"`` when the schema (``DEFAULT_CONFIG``, the legacy-root table, or+ the value already on disk) fixes *key* to a container; ``None`` for scalars and open paths.+ Single-segment keys skip the schema lookup: replacing a whole section is+ ``_guard_section_overwrite``'s call (``--force``, the bare ``model`` shorthand)."""+ parts = _split_key_path(key)+ schema_node = cfg_get(DEFAULT_CONFIG, *parts) if len(parts) > 1 else None+ existing = _get_nested(user_config, key)+ for node in (schema_node, _LEGACY_CONTAINER_TYPES.get(key), existing):+ if isinstance(node, dict):+ return "mapping"+ if isinstance(node, list) or node == "list":+ return "list"+ return None+++def _refuse_container_type_mismatch(key: str, value: Any, user_config: Dict[str, Any], force: bool) -> None:+ """Hard guardrail: never store a value of the wrong shape where the schema wants a list or a+ mapping — every reader would ignore it while ``config get`` echoed it back. ``--force`` keeps+ its documented meaning (replace a whole mapping section); a non-list in a list slot is never+ readable, so it has no override."""+ expected = _expected_container_type(key, user_config)+ if expected is None:+ return+ ok = isinstance(value, list) if expected == "list" else isinstance(value, dict)+ if ok or (expected == "mapping" and force):+ return+ got = type(value).__name__ if not isinstance(value, str) else "string"+ literal = "[item, ...]" if expected == "list" else "{key: value}"+ _exit_invalid(+ f"✗ Cannot set '{key}': it must be a {expected}, got a {got} — nothing was written.\n"+ f" Pass a YAML/JSON literal, e.g.:\n hermes config set {key} '{literal}'\n"+ " or edit config.yaml directly.")++def _redirect_platform_display_key(key: str) -> tuple[str, Optional[str]]:"""Canonicalize ``platforms.<name>.<display_setting>`` -> ``display.platforms.<name>.<setting>``.The gateway resolves per-platform display settings (streaming, show_reasoning, ...) from@@ -3609,6 +3648,7 @@ def set_config_value(key: str, value: str, force: bool = False):if key.strip().lower().startswith("model.") and isinstance(_model_val, str) and _model_val:user_config["model"] = {"default": _model_val}key = _guard_section_overwrite(key, value, user_config, force)+ _refuse_container_type_mismatch(key, value, user_config, force)try:_set_nested(user_config, key, value)except ValueError as e:diff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.pyindex 88e9a32d30b..bb963026097 100644--- a/tests/hermes_cli/test_set_config_value.py+++ b/tests/hermes_cli/test_set_config_value.py@@ -1029,3 +1029,41 @@ class TestConfigGetRedaction:else:assert out == {"TERMINAL_SSH_HOST": self.SECRET, "mcp_servers.s.auth": "oauth"}.get(key, "${UNSET_THING_API_KEY}")+++class TestContainerTypeRefusal:+ """A value of the wrong shape for a list/mapping key is refused, never warn-and-stored+ (#114471): every isinstance-gated reader would ignore the string while ``config get``+ echoed it back."""++ def _write_config(self, tmp_path, data: dict):+ import yaml as _yaml+ (tmp_path / "config.yaml").write_text(_yaml.safe_dump(data, sort_keys=False), encoding="utf-8")++ def test_string_where_schema_wants_list_is_refused(self, _isolated_hermes_home, capsys):+ self._write_config(_isolated_hermes_home, {"model": {"default": "m"}})++ with pytest.raises(SystemExit):+ set_config_value("custom_providers", "plainstring")+ with pytest.raises(SystemExit):+ set_config_value("custom_providers", '- name: x\n model: "C:\\models\\x"')++ err = capsys.readouterr().err+ assert "must be a list, got a string" in err+ assert "not valid YAML/JSON" in err+ assert "custom_providers" not in _read_config(_isolated_hermes_home)++ def test_valid_literal_and_scalar_keys_still_write(self, _isolated_hermes_home):+ self._write_config(_isolated_hermes_home, {"model": {"default": "m", "aliases": {"a": "p/m"}}})++ set_config_value("custom_providers", "[{name: ok, base_url: http://h/v1}]")+ set_config_value("model.default", "bar")+ with pytest.raises(SystemExit):+ set_config_value("model.aliases", "notamap")+ # --force keeps its documented meaning: replace a whole mapping section.+ set_config_value("model.aliases", "replaced", force=True)++ import yaml as _yaml+ saved = _yaml.safe_load(_read_config(_isolated_hermes_home))+ assert saved["custom_providers"] == [{"name": "ok", "base_url": "http://h/v1"}]+ assert saved["model"] == {"default": "bar", "aliases": "replaced"}diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex c29395e60a6..e2c282c3914 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1252,7 +1252,7 @@ Subcommands:| `show` | Show current config values. || `edit` | Open `config.yaml` in your editor. || `get <key> [--json] [--raw]` | Print a single config value by dotted key (e.g. `hermes config get model.default`). `--json` emits machine-readable output. Credential-shaped values (`api_key`, `*_TOKEN`, `*_SECRET`, `password`, …) are masked (`sk-o...7890`) because the agent runs this from sessions whose transcripts persist; `--raw` prints the real value (or set `security.redact_secrets: false`). A nested key under a known section that the schema does not define (`compression.compressor.enabled`) still prints its file value, plus a stderr notice that Hermes may not read it; stdout and the exit code (0) are unchanged. |-| `set <key> <value> [--force]` | Set a config value. Dotted paths go to `config.yaml`; every `UPPER_SNAKE` name (`OPENROUTER_API_KEY`, `DISCORD_HOME_CHANNEL`, `TELEGRAM_GROUP_ALLOWED_USERS`, `HERMES_TIMEZONE`, …) is an environment variable and goes to `.env` — the same file the platform setup flows and `/sethome` write, and the one every runtime reader resolves against. `config set` never writes an `UPPER_SNAKE` key into `config.yaml`, `--force` included; names on the env writer's denylist (`HERMES_YOLO_MODE`, `PATH`, …) are refused outright; any other `UPPER_SNAKE` name is saved to `.env` as-is (plugins, skills and external tools read it from the process environment). A known key written under the wrong prefix (`gateway.discord.foo`, where `discord.foo` is itself a known key) is refused with a did-you-mean and nothing is written; any other unknown path under a known section (`agent.max_turnz`, or a runtime-read key that has no seeded default) is written with a did-you-mean notice, and an unknown lowercase *top-level* key is written with a notice (top-level scalars are bridged into the environment for skills). `--force` writes the refused wrong-prefix path too. |+| `set <key> <value> [--force]` | Set a config value. Dotted paths go to `config.yaml`; every `UPPER_SNAKE` name (`OPENROUTER_API_KEY`, `DISCORD_HOME_CHANNEL`, `TELEGRAM_GROUP_ALLOWED_USERS`, `HERMES_TIMEZONE`, …) is an environment variable and goes to `.env` — the same file the platform setup flows and `/sethome` write, and the one every runtime reader resolves against. `config set` never writes an `UPPER_SNAKE` key into `config.yaml`, `--force` included; names on the env writer's denylist (`HERMES_YOLO_MODE`, `PATH`, …) are refused outright; any other `UPPER_SNAKE` name is saved to `.env` as-is (plugins, skills and external tools read it from the process environment). A known key written under the wrong prefix (`gateway.discord.foo`, where `discord.foo` is itself a known key) is refused with a did-you-mean and nothing is written; any other unknown path under a known section (`agent.max_turnz`, or a runtime-read key that has no seeded default) is written with a did-you-mean notice, and an unknown lowercase *top-level* key is written with a notice (top-level scalars are bridged into the environment for skills). `--force` writes the refused wrong-prefix path too. Values are type-checked against the schema: a key that must hold a list or a mapping (`custom_providers`, `model.aliases`, `display.platforms`, any key already holding one) refuses a plain string or a wrong-shaped literal, and a value that looks like a list/mapping but is not valid YAML/JSON is refused instead of being stored as a string — nothing is written and the error names the expected type. Pass a YAML/JSON literal (`hermes config set custom_providers '[{name: x, base_url: https://...}]'`); to store a string that merely starts with `[` or `{`, quote it in YAML (`"'[text'"`). `--force` still replaces a whole mapping section; a non-list in a list slot has no override. || `unset <key>` | Remove a config key, reverting it to the built-in default. For `UPPER_SNAKE` names this removes the `.env` entry and also drops a stale top-level `config.yaml` copy left by older `config set` runs (`get` reports such a copy as stale). || `path` | Print the config file path. || `env-path` | Print the `.env` file path. |