setup_migration.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """Post-import section-skip logic: after ``hermes setup`` imported another agent's settings, each
  2. section that is already configured shows its summary and offers to skip (setup.py re-exports the
  3. names it uses; setup helpers are imported lazily so test patches apply)."""
  4. from functools import partial
  5. from typing import Optional
  6. # ── Post-Migration Section Skip Logic ──
  7. _OPENROUTER_ENV_VARS = ("OPENROUTER_API_KEY", "OPENAI_API_KEY")
  8. def _model_section_has_credentials(config: dict) -> bool:
  9. """True when any known inference provider has usable credentials: ``active_provider`` in the
  10. auth store (OAuth providers), ``PROVIDER_REGISTRY`` ``api_key_env_vars``, or the legacy
  11. OpenRouter aggregator env vars (``OPENAI_API_KEY`` / ``OPENROUTER_API_KEY``)."""
  12. from hermes_cli.setup import get_env_value
  13. try:
  14. from hermes_cli.auth import get_active_provider
  15. if get_active_provider():
  16. return True
  17. except Exception:
  18. pass
  19. try:
  20. from hermes_cli.auth import PROVIDER_REGISTRY
  21. except Exception:
  22. PROVIDER_REGISTRY = {} # type: ignore[assignment]
  23. def _has_key(pconfig) -> bool:
  24. # CLAUDE_CODE_OAUTH_TOKEN is set by Claude Code itself, not by the user —
  25. # mirrors is_provider_explicitly_configured in auth.py.
  26. return any(get_env_value(v) for v in pconfig.api_key_env_vars if v != "CLAUDE_CODE_OAUTH_TOKEN")
  27. any_openrouter_key = any(get_env_value(v) for v in _OPENROUTER_ENV_VARS)
  28. # Prefer the provider declared in config.yaml, avoids false positives from stray
  29. # env vars (GH_TOKEN, etc.) when the user has already picked a different provider.
  30. model_cfg = config.get("model") if isinstance(config, dict) else None
  31. if isinstance(model_cfg, dict):
  32. provider_id = (model_cfg.get("provider") or "").strip().lower()
  33. if provider_id in PROVIDER_REGISTRY and _has_key(PROVIDER_REGISTRY[provider_id]):
  34. return True
  35. if provider_id == "openrouter" and any_openrouter_key:
  36. return True
  37. # OpenRouter aggregator fallback (no provider declared in config).
  38. if any_openrouter_key:
  39. return True
  40. # Skip providers whose credentials are commonly ambient (a token exported for other tooling):
  41. # auto-detect never selects them. Mirrors resolve_provider in auth.py.
  42. from providers import get_provider_profile
  43. return any(_has_key(pconfig) and not getattr(get_provider_profile(pid), "ambient_credentials", False)
  44. for pid, pconfig in PROVIDER_REGISTRY.items())
  45. def _model_summary(config: dict) -> Optional[str]:
  46. if not _model_section_has_credentials(config):
  47. return None
  48. model = config.get("model")
  49. if isinstance(model, str) and model.strip():
  50. return model.strip()
  51. if isinstance(model, dict):
  52. return str(model.get("default") or model.get("model") or "configured")
  53. return "configured"
  54. def _cfg_summary(config: dict, section: str, key: str, default, prefix: str) -> str:
  55. from hermes_cli.setup import cfg_get
  56. return f"{prefix}{cfg_get(config, section, key, default=default)}"
  57. def _gateway_summary(config: dict) -> Optional[str]:
  58. from hermes_cli.gateway import _all_platforms, _platform_status
  59. # Any non-empty status other than "not configured" counts — WhatsApp ("enabled, not paired"),
  60. # Matrix ("configured + E2EE") mean setup already started.
  61. configured = [
  62. # Trailing parenthetical qualifiers are stripped from the label.
  63. plat["label"].split("(", 1)[0].strip() or plat["label"]
  64. for plat in _all_platforms()
  65. if _platform_status(plat) and _platform_status(plat) != "not configured"
  66. ]
  67. return ", ".join(configured) if configured else None
  68. _TOOL_ENV_LABELS = (
  69. ("ELEVENLABS_API_KEY", "TTS/ElevenLabs"),
  70. ("BROWSERBASE_API_KEY", "Browser"),
  71. ("FIRECRAWL_API_KEY", "Firecrawl"),
  72. )
  73. def _tools_summary(config: dict) -> Optional[str]:
  74. from hermes_cli.setup import get_env_value
  75. tools = [label for env_var, label in _TOOL_ENV_LABELS if get_env_value(env_var)]
  76. return ", ".join(tools) if tools else None
  77. _SECTION_SUMMARIES = {
  78. "model": _model_summary,
  79. "terminal": partial(_cfg_summary, section="terminal", key="backend", default="local", prefix="backend: "),
  80. "agent": partial(_cfg_summary, section="agent", key="max_turns", default=90, prefix="max turns: "),
  81. "gateway": _gateway_summary,
  82. "tools": _tools_summary,
  83. }
  84. def _get_section_config_summary(config: dict, section_key: str) -> Optional[str]:
  85. """Short summary if a setup section is already configured (post-import skip detection), else
  86. None. ``get_env_value`` is reached through hermes_cli.setup so test patches
  87. on ``setup_mod.get_env_value`` apply."""
  88. summarize = _SECTION_SUMMARIES.get(section_key)
  89. return summarize(config) if summarize else None
  90. def _skip_configured_section(config: dict, section_key: str, label: str) -> bool:
  91. """Show an already-configured section summary and offer to skip; True when the user skips."""
  92. from hermes_cli.setup import print_success, prompt_yes_no
  93. summary = _get_section_config_summary(config, section_key)
  94. if not summary:
  95. return False
  96. print()
  97. print_success(f" {label}: {summary}")
  98. return not prompt_yes_no(f" Reconfigure {label.lower()}?", default=False)