config_schema.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. """Declarative config schema for memory provider plugins: each declares its fields in
  2. a ``config_schema.py`` beside ``__init__.py``; one generic renderer and one
  3. ``GET/PUT /api/memory/providers/{name}/config`` pair drive the UI. Schema files are
  4. loaded by path, never imported as a package (plugin ``__init__`` pulls in the agent
  5. runtime, which must not load into the web server); they may import only this
  6. pure-data module. ``web_server`` owns read/write, dispatching on ``storage``.
  7. """
  8. from __future__ import annotations
  9. import importlib.util
  10. import logging
  11. from dataclasses import dataclass, field as dataclass_field
  12. _log = logging.getLogger(__name__)
  13. # Field kinds understood by the generic renderer.
  14. KIND_TEXT = "text"
  15. KIND_SELECT = "select"
  16. KIND_SECRET = "secret"
  17. KIND_BOOL = "bool"
  18. KIND_NUMBER = "number"
  19. KIND_JSON = "json"
  20. # Storage backends understood by web_server (see its read/write dispatch).
  21. STORAGE_FLAT_JSON = "flat_json"
  22. STORAGE_HONCHO_HOST_BLOCK = "honcho_host_block"
  23. # The provider's read_config_fields / write_config_fields own the file layout
  24. # (agent.memory_provider.MemoryProvider); loading them loads the provider itself (in the plugin
  25. # host when ``plugins.isolation`` is ``host``), and its writer also receives submitted secrets.
  26. STORAGE_PROVIDER = "provider"
  27. @dataclass(frozen=True)
  28. class ProviderFieldOption:
  29. """A single choice for a ``select`` field."""
  30. value: str
  31. label: str
  32. description: str = ""
  33. @dataclass(frozen=True)
  34. class ProviderField:
  35. """One configurable field. Stored in exactly one place by ``kind``: non-secret
  36. kinds under ``key`` in the provider's storage; ``secret`` in the env store under
  37. ``env_key``, never read back (only ``is_set``). ``aliases``/``env_fallbacks`` read
  38. legacy values; ``inline`` marks the compact-panel subset (rest: modal, by ``group``)."""
  39. key: str
  40. label: str
  41. kind: str = KIND_TEXT
  42. default: str = ""
  43. description: str = ""
  44. placeholder: str = ""
  45. options: tuple[ProviderFieldOption, ...] = ()
  46. env_key: str | None = None
  47. aliases: tuple[str, ...] = ()
  48. env_fallbacks: tuple[str, ...] = ()
  49. inline: bool = False
  50. group: str = ""
  51. # Longer help text surfaced as an info tooltip next to the field label.
  52. info: str = ""
  53. # Host-block placement: "host" (per-profile) or "root"; flat-json ignores it.
  54. scope: str = "host"
  55. @property
  56. def is_secret(self) -> bool:
  57. return self.kind == KIND_SECRET
  58. def allowed_values(self) -> set[str]:
  59. return {opt.value for opt in self.options}
  60. @dataclass(frozen=True)
  61. class ProviderConfigSchema:
  62. """A provider plugin's declared config surface."""
  63. name: str
  64. label: str
  65. storage: str = STORAGE_FLAT_JSON
  66. # Optional link to the provider's config docs, shown in the full-config modal.
  67. docs_url: str = ""
  68. fields: tuple[ProviderField, ...] = dataclass_field(default_factory=tuple)
  69. def inline_fields(self) -> tuple[ProviderField, ...]:
  70. return tuple(f for f in self.fields if f.inline)
  71. _SCHEMA_CACHE: dict[str, ProviderConfigSchema] = {}
  72. def get_provider_config_schema(name: str) -> ProviderConfigSchema | None:
  73. """``CONFIG_SCHEMA`` of provider ``name``; None (no panel) without a ``config_schema.py``.
  74. Cached by resolved file path, not name: user plugins are per-profile."""
  75. from plugins.memory import find_provider_dir
  76. provider_dir = find_provider_dir(name)
  77. path = provider_dir / "config_schema.py" if provider_dir else None
  78. if path is None or not path.is_file():
  79. return None
  80. key = str(path)
  81. if key in _SCHEMA_CACHE:
  82. return _SCHEMA_CACHE[key]
  83. try:
  84. from plugins.memory import _is_bundled
  85. from hermes_cli.plugin_isolation import user_plugin_host
  86. host = None if _is_bundled(provider_dir) else user_plugin_host()
  87. if host is not None: # plugins.isolation: host — a user schema file is user code too
  88. schema = _schema_from_record(host.config_schema(path))
  89. else:
  90. spec = importlib.util.spec_from_file_location(f"_hermes_memory_config_schema.{name}", path)
  91. module = importlib.util.module_from_spec(spec)
  92. spec.loader.exec_module(module)
  93. schema = getattr(module, "CONFIG_SCHEMA", None)
  94. except Exception:
  95. # Never cache a failed load: it would pin an empty panel until restart.
  96. _log.exception("failed to load config schema for memory provider %r", name)
  97. return None
  98. if schema is not None:
  99. _SCHEMA_CACHE[key] = schema
  100. return schema
  101. def _schema_from_record(record) -> ProviderConfigSchema | None:
  102. """Rebuild a schema that crossed the plugin-host boundary as plain data."""
  103. if not record:
  104. return None
  105. fields = tuple(
  106. ProviderField(**{**f, "options": tuple(ProviderFieldOption(**o) for o in f.get("options") or ()),
  107. "aliases": tuple(f.get("aliases") or ()),
  108. "env_fallbacks": tuple(f.get("env_fallbacks") or ())})
  109. for f in record.get("fields") or ())
  110. return ProviderConfigSchema(**{**record, "fields": fields})