runtime_provider_missing_key.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """A provider key the active profile's secret scope does not have, said before any request.
  2. Custom resolution substitutes the ``no-key-required`` placeholder for an empty key so keyless local
  3. servers (Ollama, llama.cpp, vLLM) work. When the endpoint's config DECLARES a key variable
  4. (``key_env`` / ``api_key_env``) and it resolves to nothing, the request can only be refused, and the
  5. refusal reads "rejected your API key" although no key was sent. Under a multiplexing server a named
  6. profile reads keys only from its own ``.env``, never the server's process environment (secret scope
  7. is per profile by design), so a key exported in the server's shell is invisible to it. The error
  8. names the provider, the variable, the profile and the command that puts the key where it is read.
  9. """
  10. from __future__ import annotations
  11. import os
  12. from typing import Any, Optional
  13. from agent.secret_scope import get_secret_str
  14. NO_KEY_PLACEHOLDER = "no-key-required"
  15. def _declared_key_env(entry: Optional[dict[str, Any]]) -> str:
  16. if not isinstance(entry, dict):
  17. return ""
  18. return str(entry.get("key_env") or entry.get("api_key_env") or "").strip()
  19. def _declared_custom_key(requested_provider: str, runtime: dict[str, Any], model_cfg: dict[str, Any],
  20. config: Optional[dict[str, Any]]) -> tuple[str, str]:
  21. """``(label, key_env)`` of the config block that declared a key variable for this custom
  22. endpoint, else ``("", "")``: the owning ``providers:`` / ``custom_providers:`` entry, then
  23. ``model.key_env`` when ``model.base_url`` is this endpoint. A runtime the named-entry rung built
  24. (``source: custom_provider:<name>``) took its credential from the SELECTED entry even when an
  25. explicit base_url replaced the entry's URL, so that entry is found by name alone; any other
  26. runtime (direct alias, URL-matched bare custom) is owned by whichever entry serves its URL."""
  27. from agent.custom_entry_pool import custom_entry_for_endpoint, named_custom_entry
  28. base_url = str(runtime.get("base_url") or "")
  29. name = requested_provider if requested_provider not in ("", "auto", "custom") else None
  30. from_named_entry = str(runtime.get("source") or "").startswith("custom_provider:")
  31. match = named_custom_entry(name, config) if name and from_named_entry else custom_entry_for_endpoint(base_url, name, config)
  32. if match is not None and (key_env := _declared_key_env(match[1])):
  33. return f"custom provider '{match[1].get('name') or match[0]}'", key_env
  34. cfg_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")
  35. if cfg_url and cfg_url == base_url.strip().rstrip("/") and (key_env := _declared_key_env(model_cfg)):
  36. return "the custom endpoint in config.yaml (model.key_env)", key_env
  37. return "", ""
  38. def where_to_set_key(env_var: str) -> str:
  39. """Sentence naming the profile whose ``.env`` must hold ``env_var`` and the command that writes
  40. it there. Says so when the variable exists only in this process's environment while a routed
  41. (named) profile is served: that is the copy users hit after exporting keys in an SSH shell."""
  42. from agent.secret_scope import serves_routed_profile
  43. from hermes_constants import display_hermes_home, get_hermes_home, profile_cli_selector, profile_name_for_home
  44. profile = profile_name_for_home(get_hermes_home()) or "default"
  45. env_path = f"{display_hermes_home()}/.env"
  46. hint = (f"Add it to profile '{profile}': run `hermes {profile_cli_selector()}config set {env_var} <your key>` "
  47. f"(stored in {env_path}).")
  48. if serves_routed_profile() and os.environ.get(env_var):
  49. hint = (f"{env_var} is set in this server's environment, but profile '{profile}' reads keys only "
  50. f"from its own .env. {hint}")
  51. return hint
  52. def named_profile_key_hint(env_vars) -> str:
  53. """``" <where_to_set_key>"`` for a registry provider's missing key while a NAMED profile is
  54. active, else ``""``: the default profile also reads the process environment, so the plain
  55. "Set X." already tells it everything."""
  56. from hermes_constants import get_hermes_home, profile_name_for_home
  57. names = [str(v) for v in (env_vars or ()) if str(v or "").strip()]
  58. if not names or profile_name_for_home(get_hermes_home()) in (None, "default"):
  59. return ""
  60. return f" {where_to_set_key(names[0])}"
  61. # Transports that never send the resolved key: the codex app-server authenticates with its own login,
  62. # Bedrock with the AWS SDK credential chain (agent_init builds neither client from ``api_key``).
  63. _KEYLESS_API_MODES = frozenset({"codex_app_server", "bedrock_converse"})
  64. def raise_if_declared_key_missing(requested_provider: Optional[str], runtime: dict[str, Any], model_cfg: dict[str, Any],
  65. config: Optional[dict[str, Any]] = None, *, explicit_api_key: Optional[str] = None) -> None:
  66. """Refuse a custom runtime carrying the placeholder when its config declared a key variable
  67. that resolves to nothing in a ROUTED profile's scope (a profile served by a process launched
  68. for another, which never reads that process's environment). A single-profile process keeps
  69. the placeholder plus ``_key_env_secret``'s warning: there the variable is read from the
  70. process environment too, and callers rely on the placeholder rather than an error. A block
  71. that declares no key variable keeps the placeholder: that IS the keyless local-server
  72. configuration. Only a placeholder the resolver SYNTHESIZED is refused: a caller-supplied key
  73. (even the literal ``no-key-required``, the same value a set key variable may hold) and a
  74. transport that never sends the key (``_KEYLESS_API_MODES``, judged on the final api_mode) pass.
  75. ``config`` is a frozen
  76. route's config (the entry that owned the endpoint when the session froze it). Typed ``AuthError``
  77. (``missing_api_key``) so every caller's fallback chain still advances."""
  78. from agent.secret_scope import serves_routed_profile
  79. if runtime.get("provider") != "custom" or runtime.get("api_key") != NO_KEY_PLACEHOLDER:
  80. return
  81. if str(explicit_api_key or "").strip() or runtime.get("api_mode") in _KEYLESS_API_MODES:
  82. return
  83. if not serves_routed_profile():
  84. return
  85. label, key_env = _declared_custom_key(str(requested_provider or "").strip().lower(), runtime, model_cfg, config)
  86. if not key_env or get_secret_str(key_env, "").strip():
  87. return
  88. from hermes_cli.auth import AuthError
  89. raise AuthError(f"No API key for {label}: it reads {key_env}, which is not set for this profile, so the "
  90. f"request was not sent. {where_to_set_key(key_env)}",
  91. provider=str(requested_provider or "custom"), code="missing_api_key")