Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 112 additions & 1 deletion cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def load_cli_config() -> Dict[str, Any]:
"model": {
"default": "anthropic/claude-opus-4.6",
"base_url": "https://openrouter.ai/api/v1",
"provider": "auto",
},
"terminal": {
"env_type": "local",
Expand Down Expand Up @@ -605,6 +606,7 @@ def __init__(
self,
model: str = None,
toolsets: List[str] = None,
provider: str = None,
api_key: str = None,
base_url: str = None,
max_turns: int = 60,
Expand All @@ -617,6 +619,7 @@ def __init__(
Args:
model: Model to use (default: from env or claude-sonnet)
toolsets: List of toolsets to enable (default: all)
provider: Inference provider ("auto", "openrouter", "nous")
api_key: API key (default: from environment)
base_url: API base URL (default: OpenRouter)
max_turns: Maximum tool-calling iterations (default: 60)
Expand All @@ -637,6 +640,20 @@ def __init__(

# API key: custom endpoint (OPENAI_API_KEY) takes precedence over OpenRouter
self.api_key = api_key or os.getenv("OPENAI_API_KEY") or os.getenv("OPENROUTER_API_KEY")

self.requested_provider = (
provider
or os.getenv("HERMES_INFERENCE_PROVIDER")
or CLI_CONFIG["model"].get("provider")
or "auto"
)
self.provider = self._resolve_inference_provider(
self.requested_provider,
explicit_api_key=api_key,
explicit_base_url=base_url,
)
self._nous_key_expires_at: Optional[str] = None
self._nous_key_source: Optional[str] = None
# Max turns priority: CLI arg > env var > config file (agent.max_turns or root max_turns) > default
if max_turns != 60: # CLI arg was explicitly set
self.max_turns = max_turns
Expand Down Expand Up @@ -676,6 +693,85 @@ def __init__(

# History file for persistent input recall across sessions
self._history_file = Path.home() / ".hermes_history"

def _resolve_inference_provider(
self,
requested_provider: str,
*,
explicit_api_key: Optional[str],
explicit_base_url: Optional[str],
) -> str:
normalized = (requested_provider or "auto").strip().lower()
if normalized not in {"auto", "openrouter", "nous"}:
self.console.print(
f"[yellow]Unknown provider '{requested_provider}', falling back to auto.[/]"
)
normalized = "auto"

if normalized != "auto":
return normalized

# Explicit one-off CLI creds should always win.
if explicit_api_key or explicit_base_url:
return "openrouter"

try:
from hermes_cli.login import get_nous_portal_auth_state

nous_state = get_nous_portal_auth_state() or {}
except Exception:
nous_state = {}

if nous_state.get("access_token") or nous_state.get("refresh_token"):
return "nous"

if os.getenv("OPENAI_API_KEY") or os.getenv("OPENROUTER_API_KEY"):
return "openrouter"

return "openrouter"

def _ensure_nous_runtime_credentials(self) -> bool:
if self.provider != "nous":
return True

from hermes_cli.login import (
format_nous_auth_error,
resolve_nous_runtime_credentials,
)

try:
credentials = resolve_nous_runtime_credentials(
min_key_ttl_seconds=max(
60, int(os.getenv("HERMES_NOUS_MIN_KEY_TTL_SECONDS", "1800"))
),
timeout_seconds=float(os.getenv("HERMES_NOUS_TIMEOUT_SECONDS", "15")),
)
except Exception as exc:
# Keep UX-friendly error mapping in one place (re-auth/subscription hints).
message = format_nous_auth_error(exc) if "format_nous_auth_error" in locals() else str(exc)
self.console.print(f"[bold red]{message}[/]")
return False

api_key = credentials.get("api_key")
base_url = credentials.get("base_url")
if not isinstance(api_key, str) or not api_key:
self.console.print("[bold red]Nous credential resolver returned an empty API key.[/]")
return False
if not isinstance(base_url, str) or not base_url:
self.console.print("[bold red]Nous credential resolver returned an empty base URL.[/]")
return False

credentials_changed = api_key != self.api_key or base_url != self.base_url
self.api_key = api_key
self.base_url = base_url
self._nous_key_expires_at = credentials.get("expires_at")
self._nous_key_source = credentials.get("source")

# AIAgent/OpenAI client holds auth at initialization time, so rebuild if key rotated.
if credentials_changed and self.agent is not None:
self.agent = None

return True

def _init_agent(self) -> bool:
"""
Expand All @@ -686,6 +782,9 @@ def _init_agent(self) -> bool:
"""
if self.agent is not None:
return True

if self.provider == "nous" and not self._ensure_nous_runtime_credentials():
return False

try:
self.agent = AIAgent(
Expand Down Expand Up @@ -777,11 +876,17 @@ def _show_status(self):
toolsets_info = ""
if self.enabled_toolsets and "all" not in self.enabled_toolsets:
toolsets_info = f" [dim #B8860B]·[/] [#CD7F32]toolsets: {', '.join(self.enabled_toolsets)}[/]"

provider_info = f" [dim #B8860B]·[/] [dim]provider: {self.provider}[/]"
if self.provider == "nous" and self._nous_key_source:
provider_info = (
f"{provider_info} [dim #B8860B]·[/] [dim]key: {self._nous_key_source}[/]"
)

self.console.print(
f" {api_indicator} [#FFBF00]{model_short}[/] "
f"[dim #B8860B]·[/] [bold cyan]{tool_count} tools[/]"
f"{toolsets_info}"
f"{toolsets_info}{provider_info}"
)

def show_help(self):
Expand Down Expand Up @@ -1389,6 +1494,9 @@ def chat(self, message: str) -> Optional[str]:
Returns:
The agent's response, or None on error
"""
if self.provider == "nous" and not self._ensure_nous_runtime_credentials():
return None

# Initialize agent if needed
if not self._init_agent():
return None
Expand Down Expand Up @@ -1665,6 +1773,7 @@ def main(
q: str = None,
toolsets: str = None,
model: str = None,
provider: str = None,
api_key: str = None,
base_url: str = None,
max_turns: int = 60,
Expand All @@ -1684,6 +1793,7 @@ def main(
q: Shorthand for --query
toolsets: Comma-separated list of toolsets to enable (e.g., "web,terminal")
model: Model to use (default: anthropic/claude-opus-4-20250514)
provider: Inference provider ("auto", "openrouter", "nous")
api_key: API key for authentication
base_url: Base URL for the API
max_turns: Maximum tool-calling iterations (default: 60)
Expand Down Expand Up @@ -1754,6 +1864,7 @@ def main(
cli = HermesCLI(
model=model,
toolsets=toolsets_list,
provider=provider,
api_key=api_key,
base_url=base_url,
max_turns=max_turns,
Expand Down
Loading