The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli/web_routers): memory_providers — unify JSON reads, memory-section access, external-check runner
Tekniumd68f930182bf
diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.pyindex ec75b511e2d..364e15243ae 100644--- a/hermes_cli/web_routers/memory_providers.py+++ b/hermes_cli/web_routers/memory_providers.py@@ -1,7 +1,7 @@"""Memory-provider setup dashboard routes (schema, existing values, external dependency install).Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on-``web_server`` stay there and are imported lazily at call time (cycle-safe).+``web_server`` stay there and are late-bound (cycle-safe)."""import logging@@ -45,6 +45,7 @@ load_config = late("load_config")save_config = late("save_config")save_env_value = late("save_env_value")_dependency_importable = late("_dependency_importable")+load_env = late("load_env")# Sentinel: remove this key so it falls back to the host or built-in default.@@ -52,15 +53,12 @@ _UNSET: Any = object()def _coerce_field_value(field: ProviderField, raw: str) -> Any:- """Coerce a submitted non-secret value to its native JSON type.+ """Coerce a submitted non-secret string to its native JSON type.- Values arrive as strings over the API; this converts them to the type the- Honcho resolver expects (bool/number/list/dict), so e.g. a boolean is stored- as a JSON ``false`` rather than the string ``"false"`` (which would read as- truthy). Returns ``_UNSET`` when the field should be removed. Raises- ``ValueError`` on malformed input.+ A bool is stored as JSON ``false`` rather than ``"false"`` (truthy). Returns+ ``_UNSET`` when the field should be removed; raises ``ValueError`` on+ malformed input."""-value = (raw or "").strip()kind = field.kind@@ -76,9 +74,11 @@ def _coerce_field_value(field: ProviderField, raw: str) -> Any:return is_truthy_value(value)+ if not value:+ # number / json / text / secret — blank clears the key.+ return _UNSET+if kind == "number":- if not value:- return _UNSETtry:number = float(value)except ValueError as exc:@@ -86,8 +86,6 @@ def _coerce_field_value(field: ProviderField, raw: str) -> Any:return int(number) if number.is_integer() else numberif kind == "json":- if not value:- return _UNSETtry:parsed = json.loads(value)except (ValueError, TypeError) as exc:@@ -96,8 +94,19 @@ def _coerce_field_value(field: ProviderField, raw: str) -> Any:raise ValueError(f"'{field.key}' must be a JSON object or array")return parsed- # text / secret — blank clears the key so it falls back to host/default.- return value if value else _UNSET+ return value+++def _read_json_dict(path: Path, log_msg: str) -> Dict[str, Any]:+ """Read a JSON object from ``path``; missing/unreadable/non-dict -> ``{}``."""+ if not path.exists():+ return {}+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ _log.warning(log_msg, path, exc_info=True)+ return {}+ return data if isinstance(data, dict) else {}# — flat-json backend (default; reusable for simple providers) —@@ -108,15 +117,7 @@ def _flat_json_path(provider: ProviderConfigSchema) -> Path:def _read_flat_json(provider: ProviderConfigSchema) -> Dict[str, Any]:- path = _flat_json_path(provider)- if not path.exists():- return {}- try:- data = json.loads(path.read_text(encoding="utf-8"))- except Exception:- _log.warning("Failed to read memory provider config from %s", path, exc_info=True)- return {}- return data if isinstance(data, dict) else {}+ return _read_json_dict(_flat_json_path(provider), "Failed to read memory provider config from %s")# — honcho host-block backend —@@ -124,12 +125,15 @@ def _read_flat_json(provider: ProviderConfigSchema) -> Dict[str, Any]:def _honcho_resolvers():"""Lazily import the Honcho plugin's resolvers (optional plugin)."""-from plugins.memory.honcho.client import _host_block, resolve_active_host, resolve_config_pathreturn resolve_active_host, resolve_config_path, _host_block+def _read_honcho_config(path: Path) -> Dict[str, Any]:+ return _read_json_dict(path, "Failed to read Honcho config from %s")++def _apply_field_values(provider: ProviderConfigSchema, values: Dict[str, str], target_for) -> None:"""Apply submitted non-secret fields to their backend dict, in place.@@ -137,16 +141,14 @@ def _apply_field_values(provider: ProviderConfigSchema, values: Dict[str, str],clobbers fields owned by another surface. ``_UNSET`` clears the key (andits aliases) so it falls back to the host/default mapping."""-for field in provider.fields:if field.is_secret or field.key not in values:continuetarget = target_for(field)coerced = _coerce_field_value(field, values[field.key])if coerced is _UNSET:- target.pop(field.key, None)- for alias in field.aliases:- target.pop(alias, None)+ for key in (field.key, *field.aliases):+ target.pop(key, None)else:target[field.key] = coerced@@ -163,7 +165,6 @@ def _trim_setup_output(value: Optional[str], limit: int = 4000) -> str:def _provider_field_entry(field: ProviderField) -> Dict[str, Any]:"""Static, storage-independent shape of one field for the UI payload."""-return {"key": field.key,"label": field.label,@@ -183,22 +184,18 @@ def _provider_field_entry(field: ProviderField) -> Dict[str, Any]:def _serialize_field_value(field: ProviderField, value: Any) -> str:"""Render a stored native value as the string the generic UI edits.- ``None`` (key absent) yields the field's declared default. Bools become+ ``None`` (key absent) yields the field's declared default; bools become``"true"``/``"false"``, JSON objects/arrays are re-encoded, numbers are- stringified — so the renderer's per-kind controls always get the shape they- expect regardless of how the value sits on disk.+ stringified."""-if value is None:return field.defaultif field.kind == "bool":from utils import is_truthy_valuereturn "true" if is_truthy_value(value) else "false"- if field.kind == "json":- if isinstance(value, (dict, list)):- return json.dumps(value)- return str(value)+ if field.kind == "json" and isinstance(value, (dict, list)):+ return json.dumps(value)return str(value)@@ -208,7 +205,6 @@ def _read_field(field: ProviderField, sources: tuple, env: Dict[str, str]) -> AnPresence (``key in source``) decides, not truthiness, so a stored ``False``or ``0`` survives instead of being mistaken for "unset"."""-for source in sources:for source_key in (field.key, *field.aliases):if source_key in source and source[source_key] is not None:@@ -229,17 +225,9 @@ def _declared_field_is_set(field: ProviderField, sources: tuple, env: Dict[str,def _honcho_read_sources() -> tuple[Dict[str, Any], str, Dict[str, Any]]:"""Return (root config, active host key, host block) for the current profile."""-resolve_active_host, resolve_config_path, host_block_of = _honcho_resolvers()host = resolve_active_host()- path = resolve_config_path()- raw: Dict[str, Any] = {}- if path.exists():- try:- loaded = json.loads(path.read_text(encoding="utf-8"))- raw = loaded if isinstance(loaded, dict) else {}- except Exception:- _log.warning("Failed to read Honcho config from %s", path, exc_info=True)+ raw = _read_honcho_config(resolve_config_path())return raw, host, host_block_of(raw, host)@@ -268,7 +256,6 @@ def _write_provider_honcho(provider: ProviderConfigSchema, values: Dict[str, strinline panel) never clobbers fields owned by the full-config editor. Blanktext clears a key so it falls back to the host/default mapping."""-from plugins.memory.honcho.oauth import ACCESS_TOKEN_PREFIX, _config_refresh_lockfrom utils import atomic_json_write@@ -279,14 +266,7 @@ def _write_provider_honcho(provider: ProviderConfigSchema, values: Dict[str, str# OAuth rotation is single-use; an unlocked RMW here can revoke the grant.with _config_refresh_lock(path):- cfg: Dict[str, Any] = {}- if path.exists():- try:- loaded = json.loads(path.read_text(encoding="utf-8"))- cfg = loaded if isinstance(loaded, dict) else {}- except Exception:- _log.warning("Failed to read Honcho config from %s", path, exc_info=True)-+ cfg = _read_honcho_config(path)hosts = cfg.get("hosts")cfg["hosts"] = hosts = hosts if isinstance(hosts, dict) else {}# Update the block reads resolve (legacy dot-form included), never shadow it.@@ -334,7 +314,6 @@ def _command_result(def _declared_provider_payload(provider: ProviderConfigSchema) -> Dict[str, Any]:- from hermes_cli.web_server import load_envfields: List[Dict[str, Any]] = []env = load_env()is_honcho = provider.storage == STORAGE_HONCHO_HOST_BLOCK@@ -379,7 +358,6 @@ def _declared_provider_payload(provider: ProviderConfigSchema) -> Dict[str, Any]def _stringify_submitted_values(values: Dict[str, Any]) -> Dict[str, str]:"""The declared-schema path edits strings; the dashboard may send natives."""-out: Dict[str, str] = {}for key, value in values.items():if value is None:@@ -395,6 +373,15 @@ def _stringify_submitted_values(values: Dict[str, Any]) -> Dict[str, str]:return out+def _memory_section(config: Dict[str, Any]) -> Dict[str, Any]:+ """Return ``config["memory"]`` as a dict, creating/replacing a non-dict value."""+ memory_config = config.get("memory")+ if not isinstance(memory_config, dict):+ memory_config = {}+ config["memory"] = memory_config+ return memory_config++def _update_memory_provider_config(provider: ProviderConfigSchema, values: Dict[str, str]) -> None:if provider.storage == STORAGE_HONCHO_HOST_BLOCK:_write_provider_honcho(provider, values)@@ -402,10 +389,7 @@ def _update_memory_provider_config(provider: ProviderConfigSchema, values: Dict[_write_provider_flat(provider, values)config = load_config()- memory_config = config.get("memory")- if not isinstance(memory_config, dict):- memory_config = {}- config["memory"] = memory_config+ memory_config = _memory_section(config)if memory_config.get("provider") != provider.name:memory_config["provider"] = provider.namesave_config(config)@@ -420,49 +404,27 @@ def _install_memory_provider_pip_dependencies(dependencies: List[str]) -> List[Dif not dependencies:return []if not missing:- return [- _command_result(kind="pip", name=", ".join(dependencies), status="already_installed")- ]-- # Route through the lazy-install pipeline (tools.lazy_deps.install_specs)- # instead of shelling out to pip against sys.executable directly. That- # pipeline is environment-aware: on hosted/immutable images the agent venv- # under /opt/hermes is sealed read-only, and installs must be redirected- # to the writable durable target on the data volume- # (HERMES_LAZY_INSTALL_TARGET, e.g. /opt/data/lazy-packages) — the same- # path every lazy backend already uses. A direct `pip install --python- # sys.executable` on those images fails with a permission error (NS-605).- # install_specs also activates the target on sys.path post-install so the- # availability recheck below sees the new packages without a restart.+ return [_command_result(kind="pip", name=", ".join(dependencies), status="already_installed")]++ # Route through the lazy-install pipeline rather than pip against+ # sys.executable: on hosted/immutable images the agent venv is sealed+ # read-only and installs must go to HERMES_LAZY_INSTALL_TARGET, which+ # install_specs also activates on sys.path so the recheck sees the packages.+ name = ", ".join(missing)try:from tools.lazy_deps import install_specsoutcome = install_specs(missing, timeout=240)except Exception as exc:- return [- _command_result(- kind="pip",- name=", ".join(missing),- status="failed",- error=str(exc),- )- ]+ return [_command_result(kind="pip", name=name, status="failed", error=str(exc))]if outcome.blocked:- return [- _command_result(- kind="pip",- name=", ".join(missing),- status="failed",- command=outcome.command,- error=outcome.reason,- )- ]+ return [_command_result(kind="pip", name=name, status="failed", command=outcome.command, error=outcome.reason)]return [_command_result(kind="pip",- name=", ".join(missing),+ name=name,status="installed" if outcome.ok else "failed",command=outcome.command,completed=subprocess.CompletedProcess(@@ -484,66 +446,28 @@ def _install_memory_provider_external_dependencies(check_cmd = dep.get("check") or ""install_cmd = dep.get("install") or ""- if check_cmd:+ def _check(status_of) -> bool:+ """Run the check command; append its result; True when it passed."""try:- check = _run_setup_command(- shlex.split(check_cmd),- display=check_cmd,- timeout=20,- )+ check = _run_setup_command(shlex.split(check_cmd), display=check_cmd, timeout=20)except Exception as exc:- results.append(- _command_result(- kind="external_check",- name=name,- status="missing" if install_cmd else "failed",- command=check_cmd,- error=str(exc),- )- )- else:- if check.returncode == 0:- results.append(- _command_result(- kind="external_check",- name=name,- status="already_installed",- command=check_cmd,- completed=check,- )- )- continue- results.append(- _command_result(- kind="external_check",- name=name,- status="missing" if install_cmd else "failed",- command=check_cmd,- completed=check,- )- )+ results.append(_command_result(kind="external_check", name=name, status=status_of(None), command=check_cmd, error=str(exc)))+ return False+ ok = check.returncode == 0+ results.append(_command_result(kind="external_check", name=name, status=status_of(ok), command=check_cmd, completed=check))+ return ok+ if check_cmd:+ if _check(lambda ok: "already_installed" if ok else ("missing" if install_cmd else "failed")):+ continueif not install_cmd:continueif install_cmd:try:- install = _run_setup_command(- install_cmd,- display=install_cmd,- shell=True,- timeout=300,- )+ install = _run_setup_command(install_cmd, display=install_cmd, shell=True, timeout=300)except Exception as exc:- results.append(- _command_result(- kind="external_install",- name=name,- status="failed",- command=install_cmd,- error=str(exc),- )- )+ results.append(_command_result(kind="external_install", name=name, status="failed", command=install_cmd, error=str(exc)))continueresults.append(@@ -557,31 +481,7 @@ def _install_memory_provider_external_dependencies()if check_cmd and install.returncode == 0:- try:- post_check = _run_setup_command(- shlex.split(check_cmd),- display=check_cmd,- timeout=20,- )- results.append(- _command_result(- kind="external_check",- name=name,- status="verified" if post_check.returncode == 0 else "failed",- command=check_cmd,- completed=post_check,- )- )- except Exception as exc:- results.append(- _command_result(- kind="external_check",- name=name,- status="failed",- command=check_cmd,- error=str(exc),- )- )+ _check(lambda ok: "verified" if ok else "failed")return results@@ -593,20 +493,11 @@ def _install_memory_provider_setup(name: str) -> Dict[str, Any]:raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")setup = _memory_provider_setup_manifest(name)- results = []- results.extend(_install_memory_provider_pip_dependencies(setup["pip_dependencies"]))- results.extend(- _install_memory_provider_external_dependencies(setup["external_dependencies"])- )+ results = _install_memory_provider_pip_dependencies(setup["pip_dependencies"])+ results.extend(_install_memory_provider_external_dependencies(setup["external_dependencies"]))if not results:- results.append(- _command_result(- kind="setup",- name=name,- status="no_declared_steps",- )- )+ results.append(_command_result(kind="setup", name=name, status="no_declared_steps"))ok = all(result["status"] not in {"failed"} for result in results)statuses = {row["name"]: row for row in _discover_memory_provider_statuses()}@@ -619,7 +510,7 @@ def _install_memory_provider_setup(name: str) -> Dict[str, Any]:def _public_memory_provider_field(field: Dict[str, Any], data: Dict[str, Any]) -> Dict[str, Any]:- entry = {+ return {"key": field["key"],"label": field["label"],"kind": field["kind"],@@ -635,7 +526,6 @@ def _public_memory_provider_field(field: Dict[str, Any], data: Dict[str, Any]) -"maximum": field.get("maximum"),"step": field.get("step"),}- return entrydef _memory_provider_payload(name: str, provider: Any) -> Dict[str, Any]:@@ -705,10 +595,7 @@ def _save_memory_provider_native_config(name: str, provider: Any, values: Dict[sreturncfg = load_config()- memory_cfg = cfg.get("memory")- if not isinstance(memory_cfg, dict):- memory_cfg = {}- cfg["memory"] = memory_cfg+ memory_cfg = _memory_section(cfg)current = memory_cfg.get(name)if not isinstance(current, dict):current = {}@@ -758,9 +645,8 @@ def _require_valid_memory_provider_name(name: str) -> None:"""Reject provider names that could traverse outside the plugin dirs.``name`` is interpolated into filesystem paths by ``find_provider_dir()``- and gates which plugin manifest's setup commands run. A strict charset- allowlist (no path separators, no dots) makes traversal impossible- regardless of how the downstream lookup evolves.+ and gates which plugin manifest's setup commands run; a strict charset+ allowlist (no path separators, no dots) makes traversal impossible."""if not _MEMORY_PROVIDER_NAME_RE.fullmatch(name or ""):raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")@@ -772,18 +658,16 @@ async def get_memory_provider_config(name: str, surface: Optional[str] = None, pdef _run():with _profile_scope(profile):+ # Undeclared providers (e.g. builtin) have no config surface; an+ # empty schema makes the generic panel render nothing.if surface == "declared":declared = get_provider_config_schema(name)if declared is None:- # Undeclared providers (e.g. builtin) have no desktop- # config surface; the generic panel renders nothing.return {"name": name, "label": name, "docs_url": "", "fields": []}return _declared_provider_payload(declared)provider = _load_memory_provider(name)if provider is None:- # Undeclared providers (e.g. builtin) have no config surface. Return an- # empty schema so the generic panel simply renders nothing.return {"name": name, "label": name, "fields": [], "setup": _memory_provider_setup_info(name)}return _memory_provider_payload(name, provider)@@ -795,10 +679,10 @@ async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest):_require_valid_memory_provider_name(name)provider = _load_memory_provider(name)if provider is None and not _memory_provider_manifest(name):- # No discoverable plugin directory → nothing whose manifest could- # legitimately declare setup commands. Refuse before the- # command-running path. (provider may be None with a manifest present- # when its pip deps aren't installed yet — that's the setup use case.)+ # No discoverable plugin directory -> no manifest that could declare+ # setup commands; refuse before the command-running path. (provider+ # may be None with a manifest present when its pip deps aren't+ # installed yet — that's the setup use case.)raise HTTPException(status_code=404, detail=f"Unknown memory provider: {name}")if provider is not None and body.values:try:@@ -835,11 +719,7 @@ async def update_memory_provider_config(_write_memory_provider_config_values(name, provider, values)_require_memory_provider_ready(name)config = load_config()- memory_config = config.get("memory")- if not isinstance(memory_config, dict):- memory_config = {}- config["memory"] = memory_config- memory_config["provider"] = name+ _memory_section(config)["provider"] = namesave_config(config)_invalidate_plugins_hub_cache()return {"ok": True, "active": name}