_nas_client.py 3.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """Thin HTTP client for the agent -> NAS ``agent-cron`` endpoints (Chronos): arm one-shot / cancel /
  2. list, authenticated with the existing Nous Portal token.
  3. Wire contract: ``website/docs/developer-guide/chronos-managed-cron-contract.md``."""
  4. from __future__ import annotations
  5. import contextlib
  6. import logging
  7. from typing import Any, Dict, List
  8. logger = logging.getLogger("cron.chronos")
  9. _PROVISION_PATH = "/api/agent-cron/provision"
  10. _CANCEL_PATH = "/api/agent-cron/cancel"
  11. _LIST_PATH = "/api/agent-cron/list"
  12. class NasCronClientError(RuntimeError):
  13. """Raised when a NAS agent-cron call fails (non-2xx or transport error).
  14. ``status`` is the HTTP status (None on transport error) and ``error_code`` the OAuth-style
  15. ``error`` field of a JSON error body (``invalid_client`` marks a deterministic identity
  16. rejection the provider can act on, unlike a transient 5xx).
  17. """
  18. def __init__(self, message: str, *, status: int | None = None, error_code: str = "") -> None:
  19. super().__init__(message)
  20. self.status = status
  21. self.error_code = error_code
  22. @property
  23. def identity_rejected(self) -> bool:
  24. """NAS refused the bearer as not belonging to a provisioned agent (never transient)."""
  25. return self.status == 403 and self.error_code == "invalid_client"
  26. class NasCronClient:
  27. """Minimal client for the agent->NAS provision/cancel/list endpoints."""
  28. def __init__(self, portal_url: str, *, timeout_seconds: float = 15.0) -> None:
  29. self.portal_url = portal_url.rstrip("/")
  30. self.timeout_seconds = timeout_seconds
  31. def _headers(self) -> dict[str, str]:
  32. """Bearer auth with the agent's existing Nous Portal access token (refresh-aware)."""
  33. from hermes_cli.auth import resolve_nous_access_token
  34. return {"Authorization": f"Bearer {resolve_nous_access_token()}",
  35. "Content-Type": "application/json"}
  36. def _request(self, method: str, path: str, **kwargs: Any) -> dict[str, Any]:
  37. """Issue one request; raise NasCronClientError on transport error or non-2xx."""
  38. import requests # lazy: agent already depends on requests
  39. try:
  40. resp = requests.request(method, f"{self.portal_url}{path}", headers=self._headers(),
  41. timeout=self.timeout_seconds, **kwargs)
  42. except Exception as e:
  43. raise NasCronClientError(f"{method} {path} failed: {e}") from e
  44. if resp.status_code // 100 != 2:
  45. error_code = ""
  46. with contextlib.suppress(Exception):
  47. error_code = str((resp.json() or {}).get("error") or "")
  48. raise NasCronClientError(
  49. f"{method} {path} returned {resp.status_code}: {resp.text[:200]}",
  50. status=resp.status_code, error_code=error_code)
  51. with contextlib.suppress(Exception):
  52. return resp.json() if resp.content else {}
  53. return {}
  54. def provision(self, *, job_id: str, fire_at: str, agent_callback_url: str,
  55. dedup_key: str) -> dict[str, Any]:
  56. """Arm a one-shot for ``job_id`` at ``fire_at`` (ISO 8601); ``dedup_key`` makes re-arming
  57. idempotent NAS-side. Returns the NAS response (e.g. ``{schedule_id}``)."""
  58. return self._request("POST", _PROVISION_PATH, json={
  59. "job_id": job_id, "fire_at": fire_at, "agent_callback_url": agent_callback_url,
  60. "dedup_key": dedup_key})
  61. def cancel(self, *, job_id: str) -> dict[str, Any]:
  62. """Cancel any armed one-shot for ``job_id``."""
  63. return self._request("POST", _CANCEL_PATH, json={"job_id": job_id})
  64. def list_armed(self) -> list[dict[str, Any]]:
  65. """List armed one-shots (``{job_id, fire_at, schedule_id}``); best-effort, [] on odd shape."""
  66. data = self._request("GET", _LIST_PATH, params={})
  67. items = data.get("armed") if isinstance(data, dict) else None
  68. return items if isinstance(items, list) else []