memory_oauth.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """HTTP routes for memory-provider OAuth connect, mounted by ``web_server``."""
  2. from __future__ import annotations
  3. from contextlib import contextmanager
  4. from typing import Optional
  5. from fastapi import APIRouter, HTTPException
  6. router = APIRouter(prefix="/api/memory/providers")
  7. def _resolve_flow(provider: str):
  8. """Return a provider's ``oauth_flow`` module (bundled or user-dir copy), or raise 404."""
  9. if not provider.isidentifier():
  10. raise HTTPException(status_code=404, detail=f"unknown memory provider {provider!r}")
  11. from plugins.memory import import_provider_module
  12. try:
  13. return import_provider_module(provider, "oauth_flow")
  14. except ImportError:
  15. raise HTTPException(status_code=404, detail=f"{provider} does not support OAuth connect")
  16. @contextmanager
  17. def _scope_to_profile(profile: Optional[str]):
  18. """Scope config resolution to ``profile`` so the flow's eager path resolve targets that profile's
  19. honcho.json. None/""/"current" leaves it untouched."""
  20. requested = (profile or "").strip()
  21. if not requested or requested.lower() == "current":
  22. yield
  23. return
  24. from hermes_cli import profiles as profiles_mod
  25. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  26. try:
  27. profiles_mod.validate_profile_name(requested)
  28. except ValueError as e:
  29. raise HTTPException(status_code=400, detail=str(e))
  30. if not profiles_mod.profile_exists(requested):
  31. raise HTTPException(status_code=404, detail=f"Profile '{requested}' does not exist.")
  32. token = set_hermes_home_override(str(profiles_mod.get_profile_dir(requested)))
  33. try:
  34. yield
  35. finally:
  36. reset_hermes_home_override(token)
  37. @router.post("/{provider}/oauth/start")
  38. async def start_memory_oauth(provider: str, profile: Optional[str] = None):
  39. """Begin a provider's zero-CLI OAuth flow (browser + loopback listener); returns immediately, poll status."""
  40. try:
  41. # The flow resolves its config path eagerly inside this scope; its worker thread outlives it.
  42. with _scope_to_profile(profile):
  43. flow = _resolve_flow(provider)
  44. return flow.start_loopback_flow_background()
  45. except HTTPException:
  46. raise
  47. except Exception as exc:
  48. raise HTTPException(status_code=500, detail=f"Failed to start {provider} OAuth: {exc}")
  49. @router.get("/{provider}/oauth/status")
  50. async def memory_oauth_status(provider: str, profile: Optional[str] = None):
  51. """Poll a provider's OAuth flow: idle | pending | connected | error."""
  52. try:
  53. with _scope_to_profile(profile):
  54. flow = _resolve_flow(provider)
  55. return flow.get_flow_status()
  56. except HTTPException:
  57. raise
  58. except Exception as exc:
  59. raise HTTPException(status_code=500, detail=f"Failed to read {provider} OAuth status: {exc}")