auxiliary_client_registry.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. """``auth_type`` dispatch table for the auxiliary registry branch.
  2. ``_resolve_registry_branch`` in ``agent/auxiliary_client`` routes every
  3. ``PROVIDER_REGISTRY`` provider here on its registered ``auth_type``; this table is the
  4. registry twin of the facade's ``_EXPLICIT_PROVIDER_BRANCHES``. Arms late-import the
  5. facade (siblings never form a module-level cycle) so the seam every test patches —
  6. ``agent.auxiliary_client.*`` — is the module production reads.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from typing import TYPE_CHECKING, Callable, Dict
  11. if TYPE_CHECKING:
  12. from agent.auxiliary_client import _ResolveRequest, _ResolveResult
  13. logger = logging.getLogger("agent.auxiliary_client")
  14. # First occurrence surfaces for diagnostics; per-call retries stay silent (the
  15. # contract test_auxiliary_client_resolve_dedup.py pins for every fall-through).
  16. _LOGGED_MINIMAX_ABSENT_KEYS: set = set()
  17. _LOGGED_MINIMAX_UNEXPECTED_KEYS: set = set()
  18. def _resolve_vertex_arm(req: _ResolveRequest) -> _ResolveResult:
  19. from agent.auxiliary_client import _build_vertex_client, _route_client
  20. client, final_model = _build_vertex_client(req.provider, req.model)
  21. return _route_client(req, client, final_model) if client is not None else (None, None)
  22. def _resolve_bedrock_arm(req: _ResolveRequest) -> _ResolveResult:
  23. from agent.auxiliary_client import _build_bedrock_client, _route_client
  24. client, final_model = _build_bedrock_client(req.provider, req.model, raw_codex=req.raw_codex)
  25. return _route_client(req, client, final_model) if client is not None else (None, None)
  26. def _log_once_debug(seen: set, key: str, msg: str, *args: object) -> None:
  27. if key not in seen:
  28. seen.add(key)
  29. logger.debug(msg, *args)
  30. def _resolve_minimax_oauth_arm(req: _ResolveRequest) -> _ResolveResult:
  31. """``minimax-oauth`` → AnthropicAuxiliaryClient over a callable bearer; (None, None) when absent.
  32. MiniMax OAuth resolves to an Anthropic-compatible inference endpoint with a callable
  33. bearer: tokens live ~15 minutes and the Anthropic SDK re-invokes the provider on each
  34. request, so a static string would 401 mid-session. ``is_oauth`` comes from
  35. ``anthropic_route_is_oauth`` — the MiniMax host is a third-party Anthropic-protocol
  36. endpoint, so the wrapper must NOT carry the native Claude Code OAuth identity (mcp__
  37. tool-name wire transforms, identity rewrites, response prefix stripping); those are
  38. api.anthropic.com-only (#114967).
  39. """
  40. from hermes_cli.auth_constants import AuthError
  41. from agent.auxiliary_client import (
  42. AnthropicAuxiliaryClient, _AuxProbeClientStub, _aux_probe_active,
  43. _get_aux_model_for_provider, _normalize_resolved_model, _route_client,
  44. )
  45. from agent.anthropic_credentials import anthropic_route_is_oauth
  46. from hermes_cli.auth import get_provider_auth_state, resolve_minimax_oauth_runtime_credentials
  47. # Probe mode answers "resolvable?" for availability gates and must not touch the
  48. # network: read the raw persisted state (access_token + inference_base_url present →
  49. # stub) and skip the refresh an expired token would otherwise trigger (mirrors
  50. # credential_pool.py::_seed_minimax_singleton).
  51. if _aux_probe_active():
  52. state = get_provider_auth_state("minimax-oauth")
  53. base_url = str((state or {}).get("inference_base_url") or "").strip().rstrip("/")
  54. if not ((state or {}).get("access_token") and base_url):
  55. _log_once_debug(_LOGGED_MINIMAX_ABSENT_KEYS, "minimax-oauth",
  56. "resolve_provider_client: minimax-oauth not logged in")
  57. return None, None
  58. final_model = _normalize_resolved_model(
  59. req.model or _get_aux_model_for_provider(req.provider) or "MiniMax-M3", req.provider,
  60. )
  61. return _route_client(req, _AuxProbeClientStub(api_key="", base_url=base_url), final_model)
  62. try:
  63. credentials = resolve_minimax_oauth_runtime_credentials(as_token_provider=True)
  64. except AuthError as exc:
  65. # Expected absent/not-logged-in/quarantined states: the resolver contract is
  66. # "absent → (None, None), never an exception" (the aux ladder then falls through
  67. # to its Step-2 chain). Debug-once, like every other fall-through — a per-call
  68. # WARNING would recreate the #21521 log spam once a quarantine wipes the tokens.
  69. _log_once_debug(_LOGGED_MINIMAX_ABSENT_KEYS, "minimax-oauth",
  70. "resolve_provider_client: minimax-oauth unavailable: %s", exc)
  71. return None, None
  72. except Exception as exc:
  73. # Deliberate boundary (BLE001): a genuinely unexpected failure still ends the arm
  74. # with (None, None) — never an exception into the aux ladder — but keeps the
  75. # traceback, logged once.
  76. if "minimax-oauth" not in _LOGGED_MINIMAX_UNEXPECTED_KEYS:
  77. _LOGGED_MINIMAX_UNEXPECTED_KEYS.add("minimax-oauth")
  78. logger.warning(
  79. "resolve_provider_client: unexpected minimax-oauth resolution failure: %s", exc,
  80. exc_info=True)
  81. return None, None
  82. token_provider = credentials.get("api_key")
  83. base_url = str(credentials.get("base_url") or "").strip().rstrip("/")
  84. if not callable(token_provider) or not base_url:
  85. _log_once_debug(_LOGGED_MINIMAX_ABSENT_KEYS, "minimax-oauth",
  86. "resolve_provider_client: minimax-oauth credentials incomplete")
  87. return None, None
  88. final_model = _normalize_resolved_model(
  89. req.model or _get_aux_model_for_provider(req.provider) or "MiniMax-M3", req.provider,
  90. )
  91. from agent.anthropic_adapter import build_anthropic_client # SDK-absent boundary, like _try_anthropic
  92. try:
  93. real_client = build_anthropic_client(token_provider, base_url)
  94. except ImportError:
  95. return None, None
  96. client = AnthropicAuxiliaryClient(
  97. real_client, final_model, token_provider, base_url,
  98. is_oauth=anthropic_route_is_oauth(base_url, token_provider))
  99. return _route_client(req, client, final_model)
  100. def _resolve_plugin_oauth_arm(req: _ResolveRequest) -> _ResolveResult:
  101. from agent.auxiliary_plugin_oauth import resolve_plugin_oauth_client
  102. return resolve_plugin_oauth_client(req)
  103. # ``api_key`` / ``external_process`` arms stay on the facade (they share its credential
  104. # resolvers); the table maps the auth types whose arms are build-and-route one-liners
  105. # or live here as topical arms.
  106. REGISTRY_AUTHTYPE_ARMS: dict[str, Callable[[_ResolveRequest], _ResolveResult]] = {
  107. "vertex": _resolve_vertex_arm,
  108. "aws_sdk": _resolve_bedrock_arm,
  109. "oauth_minimax": _resolve_minimax_oauth_arm,
  110. # Plugin OAuth: nous / openai-codex / xai-oauth returned from their explicit branches.
  111. "oauth_device_code": _resolve_plugin_oauth_arm,
  112. "oauth_external": _resolve_plugin_oauth_arm,
  113. }