skills_tool_setup.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """Skill readiness: required env vars, secret capture, and setup notes. Split out of
  2. ``tools.skills_tool`` (names re-imported there); module state (``_secret_capture_callback``,
  3. ``load_env``) stays there and is read lazily at call time so origin-module patches are honored."""
  4. import logging
  5. import re
  6. from enum import Enum
  7. from typing import Any, Dict, List
  8. from hermes_constants import display_hermes_home
  9. from utils import env_var_enabled
  10. logger = logging.getLogger("tools.skills_tool")
  11. _ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
  12. _REMOTE_ENV_BACKENDS = frozenset({"docker", "modal", "ssh", "daytona", "vercel_sandbox"})
  13. class SkillReadinessStatus(str, Enum):
  14. AVAILABLE = "available"
  15. SETUP_NEEDED = "setup_needed"
  16. UNSUPPORTED = "unsupported"
  17. def _is_remote_env_backend(backend: str) -> bool:
  18. """Built-in remote backends plus plugin backends declaring is_remote."""
  19. if backend in _REMOTE_ENV_BACKENDS or not backend or backend == "local":
  20. return backend in _REMOTE_ENV_BACKENDS
  21. try:
  22. from agent.terminal_env_registry import provider_flag
  23. return bool(provider_flag(backend, "is_remote", False))
  24. except Exception:
  25. return False
  26. def _as_dict_list(raw: Any) -> list:
  27. """Accept a single mapping or a list; anything else is treated as empty."""
  28. return [raw] if isinstance(raw, dict) else raw if isinstance(raw, list) else []
  29. def _clean_str(value: Any) -> str | None:
  30. """Stripped string when *value* is a non-blank str, else None."""
  31. return value.strip() if isinstance(value, str) and value.strip() else None
  32. def _get_required_environment_variables(frontmatter: dict[str, Any]) -> list[dict[str, Any]]:
  33. """Merge required_environment_variables, setup.collect_secrets and legacy
  34. prerequisites.env_vars into one deduped, validated list (first entry wins)."""
  35. setup = frontmatter.get("setup")
  36. setup = setup if isinstance(setup, dict) else {}
  37. setup_help = _clean_str(setup.get("help"))
  38. prereqs = frontmatter.get("prerequisites")
  39. legacy = (prereqs.get("env_vars") if isinstance(prereqs, dict) else None) or []
  40. legacy = [legacy] if isinstance(legacy, str) else legacy
  41. required: dict[str, dict[str, Any]] = {} # env name -> entry, insertion-ordered, first wins
  42. declared = _as_dict_list(frontmatter.get("required_environment_variables"))
  43. entries = [{"name": i} if isinstance(i, str) else i for i in declared
  44. if isinstance(i, (str, dict))]
  45. # collect_secrets entries: env_var is the name; provider_url (or url) doubles as help.
  46. entries += [
  47. {"name": i.get("env_var"), "prompt": i.get("prompt"),
  48. "url": str(i.get("provider_url") or i.get("url") or "").strip() or None}
  49. for i in _as_dict_list(setup.get("collect_secrets")) if isinstance(i, dict)]
  50. entries += [{"name": str(v)} for v in legacy if str(v).strip()]
  51. for entry in entries:
  52. env_name = str(entry.get("name") or entry.get("env_var") or "").strip()
  53. if not env_name or env_name in required or not _ENV_VAR_NAME_RE.match(env_name):
  54. continue
  55. normalized: dict[str, Any] = {
  56. "name": env_name,
  57. "prompt": str(entry.get("prompt") or f"Enter value for {env_name}").strip()}
  58. if help_text := _clean_str(
  59. entry.get("help") or entry.get("provider_url") or entry.get("url") or setup_help):
  60. normalized["help"] = help_text
  61. if required_for := _clean_str(entry.get("required_for")):
  62. normalized["required_for"] = required_for
  63. if entry.get("optional"):
  64. normalized["optional"] = True
  65. required[env_name] = normalized
  66. return list(required.values())
  67. def _capture_result(missing_names, setup_skipped=False, gateway_setup_hint=None):
  68. return {"missing_names": missing_names, "setup_skipped": setup_skipped, "gateway_setup_hint": gateway_setup_hint}
  69. def _capture_required_environment_variables(
  70. skill_name: str, missing_entries: list[dict[str, Any]]) -> dict[str, Any]:
  71. """Prompt for missing secrets via the registered capture callback (if any)."""
  72. from tools import skills_tool as _st
  73. if not missing_entries:
  74. return _capture_result([])
  75. missing_names = [entry["name"] for entry in missing_entries]
  76. callback = _st._turn_secret_capture.get()
  77. # Messaging-platform gateway surfaces can't prompt for a secret, so they get the "unsupported"
  78. # hint. Interactive gateway surfaces (desktop app / TUI) set HERMES_INTERACTIVE (same flag
  79. # tools/approval.py uses) and register a callback routing to a secure secret.request overlay.
  80. if callback is None and _is_gateway_surface() and not env_var_enabled("HERMES_INTERACTIVE"):
  81. try:
  82. from gateway.platforms.base import GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE as hint
  83. except Exception:
  84. hint = (f"Secure secret entry is not available. Load this skill in the local CLI to be "
  85. f"prompted, or add the key to {display_hermes_home()}/.env manually.")
  86. return _capture_result(missing_names, gateway_setup_hint=hint)
  87. if callback is None and (callback := _st._secret_capture_callback) is None:
  88. return _capture_result(missing_names)
  89. remaining_names: list[str] = []
  90. for entry in missing_entries:
  91. metadata = {"skill_name": skill_name, **{k: entry[k] for k in ("help", "required_for") if entry.get(k)}}
  92. try:
  93. callback_result = callback(entry["name"], entry["prompt"], metadata)
  94. except Exception:
  95. logger.warning(f"Secret capture callback failed for {entry['name']}", exc_info=True)
  96. callback_result = {"success": False, "stored_as": entry["name"], "validated": False, "skipped": True}
  97. ok = isinstance(callback_result, dict) and callback_result.get("success")
  98. if not (ok and not callback_result.get("skipped")):
  99. remaining_names.append(entry["name"])
  100. return _capture_result(remaining_names, bool(remaining_names))
  101. def _is_gateway_surface() -> bool:
  102. if env_var_enabled("HERMES_GATEWAY_SESSION"):
  103. return True
  104. from gateway.session_context import get_session_env
  105. return bool(get_session_env("HERMES_SESSION_PLATFORM"))
  106. def _is_env_var_persisted(var_name: str, env_snapshot: dict[str, str]) -> bool:
  107. """Return whether a requirement is present in this profile's secret sources.
  108. The snapshot keeps the existing ``.env`` precedence. A miss must use
  109. ``get_secret`` rather than reading ``os.environ`` directly so an active
  110. multiplex worker can see its hydrated external secrets without seeing a
  111. different profile's process environment.
  112. """
  113. if var_name in env_snapshot:
  114. return bool(env_snapshot[var_name])
  115. try:
  116. from agent.secret_scope import UnscopedSecretError, get_secret
  117. return bool(get_secret(var_name))
  118. except UnscopedSecretError:
  119. return False
  120. def _build_setup_note(
  121. readiness_status: SkillReadinessStatus, missing: list[str],
  122. setup_help: str | None = None) -> str | None:
  123. if readiness_status != SkillReadinessStatus.SETUP_NEEDED:
  124. return None
  125. note = f"Setup needed before using this skill: missing {', '.join(missing) if missing else 'required prerequisites'}."
  126. return f"{note} {setup_help}" if setup_help else note