plugins_settings.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """Plugin-declared settings fields for the Desktop/TUI Plugins hub (#46600, #87934).
  2. A ``plugin.yaml`` ``config_schema`` describes the keys under ``plugins.entries.<id>.settings``.
  3. This module turns that schema into renderable form fields (type, current value, choices) and
  4. writes edits back through :func:`hermes_cli.plugins_state.save_plugin_setting` — the same writer
  5. ``ctx.set_config`` uses, so the CLI, the plugin and the Desktop never disagree on where a
  6. setting lives. Secrets are declared with ``type: secret`` and never touch ``config.yaml``: the
  7. field carries the ``.env`` name (``env:`` or ``<PLUGIN>_<KEY>``) plus a presence flag, and the
  8. client writes the value through the existing ``PUT /api/env`` credential route.
  9. """
  10. from __future__ import annotations
  11. import logging
  12. import re
  13. from pathlib import Path
  14. from typing import Any, Dict, List, Mapping, Optional
  15. from hermes_cli.plugins_state import _plugin_relative_segments, _plugin_settings_entry, save_plugin_setting
  16. logger = logging.getLogger(__name__)
  17. # manifest ``type`` → wire field type the renderer keys its component table on.
  18. _FIELD_TYPES: dict[str, str] = {
  19. "str": "string", "string": "string",
  20. "int": "number", "integer": "number", "float": "number", "number": "number",
  21. "bool": "boolean", "boolean": "boolean",
  22. "list": "json", "array": "json", "dict": "json", "object": "json",
  23. "secret": "secret",
  24. }
  25. # wire field type → Python types a saved value must have (bool is excluded from number on purpose).
  26. _VALUE_TYPES: dict[str, tuple] = {
  27. "string": (str,), "enum": (str,), "number": (int, float), "boolean": (bool,), "json": (list, dict),
  28. }
  29. _ENV_NAME_CLEAN_RE = re.compile(r"[^A-Z0-9]+")
  30. def _manifest_config_schema(plugin_dir: Optional[Path]) -> Mapping[str, Mapping[str, Any]]:
  31. """``config_schema`` from ``<plugin_dir>/plugin.yaml``, or for a portable package from
  32. ``plugin.json`` ``extensions.com.nousresearch.hermes.config_schema`` (Agent Plugins v1 forbids
  33. unknown top-level fields, so Hermes-specific keys live in the vendor namespace); ``{}`` when
  34. absent or malformed (the loader already warned about malformed entries at load time)."""
  35. if plugin_dir is None:
  36. return {}
  37. manifest = Path(plugin_dir) / "plugin.yaml"
  38. try:
  39. if manifest.is_file():
  40. from utils import fast_safe_load
  41. data = fast_safe_load(manifest.read_text(encoding="utf-8-sig")) or {}
  42. raw = data.get("config_schema") if isinstance(data, Mapping) else None
  43. else:
  44. raw = _portable_config_schema(Path(plugin_dir))
  45. except Exception as exc: # unreadable manifest: no settings surface, never a failed list
  46. logger.debug("plugin settings: cannot read the manifest in %s: %s", plugin_dir, exc)
  47. return {}
  48. if not isinstance(raw, Mapping):
  49. return {}
  50. return {str(k): v for k, v in raw.items() if isinstance(v, Mapping)}
  51. def _portable_config_schema(plugin_dir: Path) -> Any:
  52. portable = plugin_dir / "plugin.json"
  53. if not portable.is_file():
  54. return None
  55. import json
  56. from hermes_cli.agent_plugins import manifest_config_schema
  57. return manifest_config_schema(json.loads(portable.read_text(encoding="utf-8-sig")))
  58. def secret_env_name(plugin_id: str, key: str, spec: Mapping[str, Any]) -> str:
  59. """``.env`` variable a ``type: secret`` field is stored under: the manifest's ``env:`` or
  60. ``<PLUGIN_ID>_<KEY>`` upper-snaked (``image_gen/fal`` + ``api_key`` → ``IMAGE_GEN_FAL_API_KEY``)."""
  61. declared = str(spec.get("env") or "").strip()
  62. if declared:
  63. return declared
  64. return _ENV_NAME_CLEAN_RE.sub("_", f"{plugin_id}_{key}".upper()).strip("_")
  65. def _field_type(spec: Mapping[str, Any]) -> str:
  66. if spec.get("secret") is True:
  67. return "secret"
  68. kind = _FIELD_TYPES.get(str(spec.get("type") or "str").lower(), "string")
  69. choices = spec.get("choices", spec.get("enum"))
  70. if kind == "string" and isinstance(choices, list) and choices:
  71. return "enum"
  72. return kind
  73. def plugin_settings_fields(plugin_id: str, plugin_dir: Optional[Path]) -> list[dict[str, Any]]:
  74. """Renderable settings fields for one plugin: schema + the current value of each key.
  75. Secret fields never carry the value — only ``env`` (where it lives) and ``has_value``.
  76. """
  77. schema = _manifest_config_schema(plugin_dir)
  78. if not schema:
  79. return []
  80. from hermes_cli.config import get_env_value, load_config_readonly
  81. entry = _plugin_settings_entry(load_config_readonly() or {}, plugin_id) or {}
  82. raw_current = entry.get("settings")
  83. current: Mapping[str, Any] = raw_current if isinstance(raw_current, Mapping) else {}
  84. fields: list[dict[str, Any]] = []
  85. for key, spec in schema.items():
  86. try:
  87. _plugin_relative_segments(key)
  88. except ValueError:
  89. continue # a key the plugin could never read through ctx.get_config
  90. kind = _field_type(spec)
  91. field: dict[str, Any] = {
  92. "key": key, "type": kind,
  93. "label": str(spec.get("label") or spec.get("title") or key),
  94. "description": str(spec.get("description") or ""),
  95. "required": bool(spec.get("required")),
  96. }
  97. if kind == "secret":
  98. env = secret_env_name(plugin_id, key, spec)
  99. field.update({"env": env, "has_value": get_env_value(env) is not None})
  100. else:
  101. choices = spec.get("choices", spec.get("enum"))
  102. if kind == "enum":
  103. field["choices"] = [str(c) for c in choices]
  104. if "default" in spec:
  105. field["default"] = spec["default"]
  106. field["value"] = current.get(key, spec.get("default"))
  107. fields.append(field)
  108. return fields
  109. def save_plugin_settings(plugin_id: str, plugin_dir: Optional[Path], values: Mapping[str, Any]) -> list[str]:
  110. """Write ``values`` (``{key: value}``) for the plugin's schema keys; returns the keys written.
  111. Raises ``ValueError`` on an unknown key, a type mismatch, an enum value outside ``choices`` or a
  112. secret (secrets go to ``.env`` through the credential route, never ``config.yaml``);
  113. ``PermissionError`` propagates from the shared writer (managed installs / managed keys).
  114. """
  115. schema = _manifest_config_schema(plugin_dir)
  116. plan: list[tuple] = []
  117. for key, value in values.items():
  118. spec = schema.get(str(key))
  119. if spec is None:
  120. raise ValueError(f"{key!r} is not declared in the plugin's config_schema")
  121. kind = _field_type(spec)
  122. if kind == "secret":
  123. raise ValueError(f"{key!r} is a secret; it is stored in .env, not config.yaml")
  124. expected = _VALUE_TYPES[kind]
  125. if not isinstance(value, expected) or (isinstance(value, bool) and bool not in expected):
  126. raise ValueError(f"{key!r} should be {kind} (got {type(value).__name__})")
  127. if kind == "enum" and value not in [str(c) for c in spec.get("choices", spec.get("enum"))]:
  128. raise ValueError(f"{key!r} must be one of the declared choices")
  129. plan.append((str(key), _plugin_relative_segments(str(key)), value))
  130. for key, segments, value in plan:
  131. save_plugin_setting(plugin_id, segments, value)
  132. return [key for key, _segments, _value in plan]