config.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """Install-wide configuration with easiest-first defaults.
  2. Everything works zero-config. `setup --auto` (the autonomous path) detects what
  3. this environment can do and picks the MOST AUTONOMOUS valid configuration without
  4. asking anyone; plain `setup` keeps the easiest-first defaults and only upgrades a
  5. setting when a flag opts in.
  6. `autonomy` is policy, orthogonal to capability:
  7. full - intake consent is standing authorization; the agent submits T0-T2
  8. opt-outs without pausing per submission (default).
  9. assisted - the agent pauses for operator confirmation before each submission.
  10. """
  11. from __future__ import annotations
  12. import os
  13. from pathlib import Path
  14. from shutil import which
  15. import emailer
  16. import paths
  17. import storage
  18. DEFAULT_CONFIG = {
  19. "autonomy": "full", # hands-off after intake+consent
  20. "email_mode": "draft_only", # zero credentials
  21. "browser_backend": "auto", # auto = Browserbase when BROWSERBASE_API_KEY is set
  22. # (recommended default; clears soft CAPTCHAs), else plain browser
  23. "tracker_backend": "local-json", # no external dependency
  24. "encryption": "none", # files still written 0600
  25. "default_rescan_interval_days": 120,
  26. "email_min_interval_seconds": 20, # pace SMTP sends so a run can't torch the account
  27. }
  28. VALID = {
  29. "autonomy": {"full", "assisted"},
  30. # email_mode:
  31. # draft_only - render drafts; the operator sends + clicks verify links (zero setup)
  32. # browser - the agent sends + opens verify links through the operator's logged-in
  33. # webmail via browser_exec (NO password stored; needs a browser the
  34. # operator's inbox is signed into)
  35. # programmatic - CLI sends via SMTP + reads verify links via IMAP (needs EMAIL_* creds)
  36. # alias - AgentMail agent-owned inboxes / per-broker aliases
  37. "email_mode": {"draft_only", "browser", "programmatic", "alias"},
  38. # browser_backend: local = Hermes's own Chromium via browser_exec; camofox = the `camofox`
  39. # catalog plugin. Only browserbase (or auto + key) changes planning (soft-CAPTCHA clearing).
  40. "browser_backend": {"auto", "browserbase", "local", "camofox"},
  41. "tracker_backend": {"local-json", "google-sheets"},
  42. "encryption": {"none", "age"},
  43. }
  44. # Values written by older installs, renamed when Hermes dropped agent-browser.
  45. LEGACY_VALUES = {"browser_backend": {"agent-browser": "local"}}
  46. def load_config() -> dict:
  47. cfg = dict(DEFAULT_CONFIG)
  48. cfg.update(storage.read_json(paths.config_path(), {}) or {})
  49. for key, renames in LEGACY_VALUES.items():
  50. cfg[key] = renames.get(cfg.get(key), cfg.get(key))
  51. return cfg
  52. def save_config(cfg: dict) -> Path:
  53. merged = dict(DEFAULT_CONFIG)
  54. merged.update(cfg)
  55. for key, allowed in VALID.items():
  56. if merged.get(key) not in allowed:
  57. raise ValueError(f"invalid {key!r}: {merged.get(key)!r} (allowed: {sorted(allowed)})")
  58. return storage.write_json(paths.config_path(), merged)
  59. def dotenv_env() -> dict:
  60. """Shell env overlaid on `$HERMES_HOME/.env`, so capability detection sees the creds Hermes
  61. loads for its own tools (BROWSERBASE_API_KEY, EMAIL_*, AGENTMAIL_API_KEY, ...) even though the
  62. terminal-tool shell doesn't export them. Shell env wins; the .env only fills gaps."""
  63. merged: dict = {}
  64. p = paths.hermes_home() / ".env"
  65. if p.exists():
  66. try:
  67. for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
  68. line = line.strip()
  69. if not line or line.startswith("#") or "=" not in line:
  70. continue
  71. k, v = line.split("=", 1)
  72. merged[k.strip()] = v.strip().strip('"').strip("'")
  73. except OSError:
  74. pass
  75. merged.update(os.environ)
  76. return merged
  77. def detect_capabilities(env: dict | None = None) -> dict:
  78. """Report which opt-in upgrades are available without extra setup."""
  79. env = os.environ if env is None else env
  80. home = paths.hermes_home()
  81. google = (
  82. (home / "google_token.json").exists()
  83. or (home / "skills" / "productivity" / "google-workspace").exists()
  84. or (home / "skills" / "google-workspace").exists()
  85. )
  86. mail = emailer.available(env)
  87. return {
  88. "browserbase": bool(env.get("BROWSERBASE_API_KEY")),
  89. "agentmail": bool(env.get("AGENTMAIL_API_KEY")),
  90. "email_imap_smtp": bool(env.get("EMAIL_ADDRESS") and env.get("EMAIL_PASSWORD")),
  91. "smtp_send": mail["smtp"], # CLI can SEND opt-out emails itself
  92. "imap_read": mail["imap"], # CLI can POLL verification links itself
  93. "google_workspace": google,
  94. "age": which("age") is not None,
  95. }
  96. def auto_configure(env: dict | None = None) -> dict:
  97. """Pick the most autonomous configuration this environment supports (no questions).
  98. - email: programmatic when SMTP creds exist (CLI sends + IMAP-verifies itself);
  99. alias mode when only AgentMail exists; draft_only as the capability floor.
  100. - browser: browserbase when the key exists (clears soft CAPTCHAs -> more T1).
  101. - encryption: age when the binary is installed (free privacy, zero human cost).
  102. - tracker: stays local-json (google-sheets needs a sheet id -> a human choice).
  103. """
  104. caps = detect_capabilities(env)
  105. cfg = load_config()
  106. cfg["autonomy"] = "full"
  107. if caps["smtp_send"]:
  108. cfg["email_mode"] = "programmatic"
  109. elif caps["agentmail"]:
  110. cfg["email_mode"] = "alias"
  111. else:
  112. cfg["email_mode"] = "draft_only"
  113. cfg["browser_backend"] = "browserbase" if caps["browserbase"] else "auto"
  114. if caps["age"]:
  115. cfg["encryption"] = "age"
  116. return cfg
  117. def browser_clears_captcha(cfg: dict, env: dict | None = None) -> bool:
  118. """True if the chosen browser backend can clear soft CAPTCHAs (shifts T2 -> T1).
  119. Browserbase is the recommended default: a real residential-IP cloud browser passes
  120. soft/managed challenges (Turnstile, hCaptcha/reCAPTCHA checkbox) as normal operation.
  121. This is NOT solving/spoofing - hard interactive challenges still escalate to a human.
  122. `auto` inherits this whenever BROWSERBASE_API_KEY is present.
  123. """
  124. backend = cfg.get("browser_backend", "auto")
  125. if backend == "browserbase":
  126. return True
  127. if backend == "auto":
  128. env = os.environ if env is None else env
  129. return bool(env.get("BROWSERBASE_API_KEY"))
  130. return False