Skip to content

The agent that grows with you

refactor(hermes_cli): auth_zai_kimi/auth_qwen — priority-walk helper, shared probe model list, packed layout

Teknium77d6e5700d38
diff --git a/hermes_cli/auth_qwen.py b/hermes_cli/auth_qwen.py
index 69235b32963..1f82e3daab7 100644
--- a/hermes_cli/auth_qwen.py
+++ b/hermes_cli/auth_qwen.py
@@ -15,19 +15,15 @@ import time
from pathlib import Path
from typing import Any, Dict
from hermes_cli.auth_constants import (
- AuthError,
- DEFAULT_QWEN_BASE_URL,
- QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,
- QWEN_OAUTH_CLIENT_ID,
- QWEN_OAUTH_TOKEN_URL,
- _FORM_JSON_HEADERS,
- _qwen_err,
- httpx,
+ AuthError, DEFAULT_QWEN_BASE_URL, QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, QWEN_OAUTH_CLIENT_ID,
+ QWEN_OAUTH_TOKEN_URL, _FORM_JSON_HEADERS, _qwen_err, httpx,
)
# Log-record parity with the origin module (caplog tests pin "hermes_cli.auth").
logger = logging.getLogger("hermes_cli.auth")
+_RERUN = "Re-run 'qwen auth qwen-oauth'."
+
def _qwen_cli_auth_path() -> Path:
return Path.home() / ".qwen" / "oauth_creds.json"
@@ -37,16 +33,12 @@ def _read_qwen_cli_tokens() -> Dict[str, Any]:
from hermes_cli.auth import _qwen_cli_auth_path
auth_path = _qwen_cli_auth_path()
if not auth_path.exists():
- raise _qwen_err(
- "Qwen CLI credentials not found. Run 'qwen auth qwen-oauth' first.",
- "qwen_auth_missing",
- )
+ raise _qwen_err("Qwen CLI credentials not found. Run 'qwen auth qwen-oauth' first.", "qwen_auth_missing")
try:
data = json.loads(auth_path.read_text(encoding="utf-8"))
except Exception as exc:
raise _qwen_err(
- f"Failed to read Qwen CLI credentials from {auth_path}: {exc}",
- "qwen_auth_read_failed",
+ f"Failed to read Qwen CLI credentials from {auth_path}: {exc}", "qwen_auth_read_failed",
) from exc
if not isinstance(data, dict):
raise _qwen_err(f"Invalid Qwen CLI credentials in {auth_path}.", "qwen_auth_invalid")
@@ -71,20 +63,13 @@ def _qwen_access_token_is_expiring(expiry_date_ms: Any, skew_seconds: int = QWEN
def _refresh_qwen_cli_tokens(tokens: Dict[str, Any], timeout_seconds: float = 20.0) -> Dict[str, Any]:
refresh_token = str(tokens.get("refresh_token", "") or "").strip()
if not refresh_token:
- raise _qwen_err(
- "Qwen OAuth refresh token missing. Re-run 'qwen auth qwen-oauth'.",
- "qwen_refresh_token_missing",
- )
+ raise _qwen_err(f"Qwen OAuth refresh token missing. {_RERUN}", "qwen_refresh_token_missing")
try:
response = httpx.post(
QWEN_OAUTH_TOKEN_URL,
headers=_FORM_JSON_HEADERS,
- data={
- "grant_type": "refresh_token",
- "refresh_token": refresh_token,
- "client_id": QWEN_OAUTH_CLIENT_ID,
- },
+ data={"grant_type": "refresh_token", "refresh_token": refresh_token, "client_id": QWEN_OAUTH_CLIENT_ID},
timeout=timeout_seconds,
)
except Exception as exc:
@@ -93,28 +78,19 @@ def _refresh_qwen_cli_tokens(tokens: Dict[str, Any], timeout_seconds: float = 20
if response.status_code >= 400:
body = response.text.strip()
raise _qwen_err(
- "Qwen OAuth refresh failed. Re-run 'qwen auth qwen-oauth'."
- + (f" Response: {body}" if body else ""),
- "qwen_refresh_failed",
+ f"Qwen OAuth refresh failed. {_RERUN}" + (f" Response: {body}" if body else ""), "qwen_refresh_failed",
)
try:
payload = response.json()
except Exception as exc:
- raise _qwen_err(
- f"Qwen OAuth refresh returned invalid JSON: {exc}",
- "qwen_refresh_invalid_json",
- ) from exc
+ raise _qwen_err(f"Qwen OAuth refresh returned invalid JSON: {exc}", "qwen_refresh_invalid_json") from exc
if not isinstance(payload, dict) or not str(payload.get("access_token", "") or "").strip():
- raise _qwen_err(
- "Qwen OAuth refresh response missing access_token.",
- "qwen_refresh_invalid_response",
- )
+ raise _qwen_err("Qwen OAuth refresh response missing access_token.", "qwen_refresh_invalid_response")
- expires_in = payload.get("expires_in")
try:
- expires_in_seconds = int(expires_in)
+ expires_in_seconds = int(payload.get("expires_in"))
except Exception:
expires_in_seconds = 6 * 60 * 60
@@ -139,9 +115,7 @@ def _mark_qwen_oauth_active(creds: Dict[str, Any]) -> None:
from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store, _save_provider_state
with _auth_store_lock():
auth_store = _load_auth_store()
- state: Dict[str, Any] = {}
- if creds.get("base_url"):
- state["base_url"] = str(creds["base_url"])
+ state: Dict[str, Any] = {"base_url": str(creds["base_url"])} if creds.get("base_url") else {}
_save_provider_state(auth_store, "qwen-oauth", state)
_save_auth_store(auth_store)
@@ -154,23 +128,18 @@ def resolve_qwen_runtime_credentials(
) -> Dict[str, Any]:
from hermes_cli.auth import _qwen_cli_auth_path, _refresh_qwen_cli_tokens
tokens = _read_qwen_cli_tokens()
- access_token = str(tokens.get("access_token", "") or "").strip()
should_refresh = bool(force_refresh)
if not should_refresh and refresh_if_expiring:
should_refresh = _qwen_access_token_is_expiring(tokens.get("expiry_date"), refresh_skew_seconds)
if should_refresh:
tokens = _refresh_qwen_cli_tokens(tokens)
- access_token = str(tokens.get("access_token", "") or "").strip()
+ access_token = str(tokens.get("access_token", "") or "").strip()
if not access_token:
- raise _qwen_err(
- "Qwen OAuth access token missing. Re-run 'qwen auth qwen-oauth'.",
- "qwen_access_token_missing",
- )
+ raise _qwen_err(f"Qwen OAuth access token missing. {_RERUN}", "qwen_access_token_missing")
- base_url = os.getenv("HERMES_QWEN_BASE_URL", "").strip().rstrip("/") or DEFAULT_QWEN_BASE_URL
return {
"provider": "qwen-oauth",
- "base_url": base_url,
+ "base_url": os.getenv("HERMES_QWEN_BASE_URL", "").strip().rstrip("/") or DEFAULT_QWEN_BASE_URL,
"api_key": access_token,
"source": "qwen-cli",
"expires_at_ms": tokens.get("expiry_date"),
@@ -182,9 +151,9 @@ def get_qwen_auth_status() -> Dict[str, Any]:
from hermes_cli.auth import _qwen_cli_auth_path, resolve_qwen_runtime_credentials
auth_path = _qwen_cli_auth_path()
try:
- # Validate the runtime credentials, including refresh when the cached
- # CLI token is expired. Otherwise stale tokens show up as "logged in"
- # and `hermes model` walks users into a broken Qwen setup flow.
+ # Validate the runtime credentials, including refresh when the cached CLI token is expired;
+ # otherwise stale tokens show up as "logged in" and `hermes model` walks users into a
+ # broken Qwen setup flow.
creds = resolve_qwen_runtime_credentials(refresh_if_expiring=True)
return {
"logged_in": True,
@@ -194,8 +163,4 @@ def get_qwen_auth_status() -> Dict[str, Any]:
"expires_at_ms": creds.get("expires_at_ms"),
}
except AuthError as exc:
- return {
- "logged_in": False,
- "auth_file": str(auth_path),
- "error": str(exc),
- }
+ return {"logged_in": False, "auth_file": str(auth_path), "error": str(exc)}
diff --git a/hermes_cli/auth_zai_kimi.py b/hermes_cli/auth_zai_kimi.py
index 5a3c78d25c2..64ab2733d3e 100644
--- a/hermes_cli/auth_zai_kimi.py
+++ b/hermes_cli/auth_zai_kimi.py
@@ -17,83 +17,50 @@ from hermes_cli.auth_constants import httpx
logger = logging.getLogger("hermes_cli.auth")
-# Kimi Code (kimi.com/code) issues keys prefixed "sk-kimi-" that only work
-# on api.kimi.com/coding. Legacy keys from platform.moonshot.ai work on
-# api.moonshot.ai/v1 (the old default). Auto-detect when user hasn't set
-# KIMI_BASE_URL explicitly.
-#
-# Note: the base URL intentionally has NO /v1 suffix. The /coding endpoint
-# speaks the Anthropic Messages protocol, and the anthropic SDK appends
-# "/v1/messages" internally — so "/coding" + SDK suffix → "/coding/v1/messages"
-# (the correct target). Using "/coding/v1" here would produce
-# "/coding/v1/v1/messages" (a 404).
+# Kimi Code (kimi.com/code) issues "sk-kimi-" keys that only work on api.kimi.com/coding; legacy
+# platform.moonshot.ai keys work on api.moonshot.ai/v1 (the old default). Intentionally NO /v1
+# suffix: the /coding endpoint speaks Anthropic Messages and the SDK appends "/v1/messages"
+# itself — "/coding/v1" would produce "/coding/v1/v1/messages" (a 404).
KIMI_CODE_BASE_URL = "https://api.kimi.com/coding"
def _resolve_kimi_base_url(api_key: str, default_url: str, env_override: str) -> str:
- """Return the correct Kimi base URL based on the API key prefix.
-
- If the user has explicitly set KIMI_BASE_URL, that always wins. Otherwise, sk-kimi- prefixed
- keys route to api.kimi.com/coding/v1.
- """
+ """Kimi base URL from the key prefix; an explicit KIMI_BASE_URL always wins."""
if env_override:
return env_override
- # No key → nothing to infer from. Return default without inspecting.
- if not api_key:
- return default_url
- if api_key.startswith("sk-kimi-"):
+ if api_key and api_key.startswith("sk-kimi-"):
return KIMI_CODE_BASE_URL
return default_url
-# Z.AI has separate billing for general vs coding plans, and global vs China
-# endpoints. A key that works on one may return "Insufficient balance" on
-# another. We probe at setup time and store the working endpoint.
-# Each entry lists candidate models to try in order — newer coding plan accounts
-# may only have access to recent models (glm-5.1, glm-5v-turbo) while older
-# ones still use glm-4.7.
+# Z.AI bills general vs coding plans, and global vs China endpoints, separately; a key that works
+# on one may return "Insufficient balance" on another, so we probe at setup time and store the
+# working endpoint. Each entry lists candidate models to try in order — newer coding-plan accounts
+# may only have access to recent models while older ones still use glm-4.7.
+_ZAI_CODING_PROBE_MODELS = ["glm-5.3", "glm-5.3-flash", "glm-5.2", "glm-5.1", "glm-5v-turbo", "glm-4.7"]
ZAI_ENDPOINTS = [
# (id, base_url, probe_models, label)
("global", "https://api.z.ai/api/paas/v4", ["glm-5"], "Global"),
("cn", "https://open.bigmodel.cn/api/paas/v4", ["glm-5"], "China"),
- ("coding-global", "https://api.z.ai/api/coding/paas/v4", ["glm-5.3", "glm-5.3-flash", "glm-5.2", "glm-5.1", "glm-5v-turbo", "glm-4.7"], "Global (Coding Plan)"),
- ("coding-cn", "https://open.bigmodel.cn/api/coding/paas/v4", ["glm-5.3", "glm-5.3-flash", "glm-5.2", "glm-5.1", "glm-5v-turbo", "glm-4.7"], "China (Coding Plan)"),
+ ("coding-global", "https://api.z.ai/api/coding/paas/v4", _ZAI_CODING_PROBE_MODELS, "Global (Coding Plan)"),
+ ("coding-cn", "https://open.bigmodel.cn/api/coding/paas/v4", _ZAI_CODING_PROBE_MODELS, "China (Coding Plan)"),
]
-def _probe_single_zai_endpoint(
- api_key: str, endpoint: tuple, timeout: float,
-) -> Optional[Dict[str, str]]:
- """Probe a single Z.AI endpoint. Returns endpoint info dict or None.
-
- Preserves the per-endpoint candidate-model loop: endpoints carry a ``probe_models`` LIST and
- each model is tried in order until one succeeds (some plans only accept newer/older GLM slugs).
- """
+def _probe_single_zai_endpoint(api_key: str, endpoint: tuple, timeout: float) -> Optional[Dict[str, str]]:
+ """Probe one Z.AI endpoint, trying its candidate models in order; None when none succeeds."""
ep_id, base_url, probe_models, label = endpoint
for model in probe_models:
try:
resp = httpx.post(
f"{base_url}/chat/completions",
- headers={
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json",
- },
- json={
- "model": model,
- "stream": False,
- "max_tokens": 1,
- "messages": [{"role": "user", "content": "ping"}],
- },
+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
+ json={"model": model, "stream": False, "max_tokens": 1, "messages": [{"role": "user", "content": "ping"}]},
timeout=timeout,
)
if resp.status_code == 200:
logger.debug("Z.AI endpoint probe: %s (%s) model=%s OK", ep_id, base_url, model)
- return {
- "id": ep_id,
- "base_url": base_url,
- "model": model,
- "label": label,
- }
+ return {"id": ep_id, "base_url": base_url, "model": model, "label": label}
logger.debug("Z.AI endpoint probe: %s model=%s returned %s", ep_id, model, resp.status_code)
except Exception as exc:
logger.debug("Z.AI endpoint probe: %s model=%s failed: %s", ep_id, model, exc)
@@ -101,124 +68,99 @@ def _probe_single_zai_endpoint(
def detect_zai_endpoint(api_key: str, timeout: float = 8.0) -> Optional[Dict[str, str]]:
- """Probe z.ai endpoints in parallel to find one that accepts this API key.
-
- Returns {"id": ..., "base_url": ..., "model": ..., "label": ...} for the first working endpoint
- (in ZAI_ENDPOINTS priority order), or None if all fail. For endpoints with multiple candidate
- models, each worker tries its endpoint's models in order and returns the first that succeeds.
- """
+ """Probe z.ai endpoints in parallel; first working one in ZAI_ENDPOINTS priority order, or None."""
from concurrent.futures import ThreadPoolExecutor, as_completed
- # No `with` block: a context manager would join ALL probe threads on
- # exit, defeating the early return below. shutdown(wait=False) lets the
- # surviving daemon-style probes drain in the background instead of
- # blocking the caller on slow/unreachable endpoints.
+ # No `with` block: a context manager would join ALL probe threads on exit, defeating the early
+ # return below. shutdown(wait=False) lets surviving probes drain in the background.
pool = ThreadPoolExecutor(max_workers=len(ZAI_ENDPOINTS))
try:
- futures = {
- pool.submit(_probe_single_zai_endpoint, api_key, ep, timeout): ep[0]
- for ep in ZAI_ENDPOINTS
- }
+ futures = {pool.submit(_probe_single_zai_endpoint, api_key, ep, timeout): ep[0] for ep in ZAI_ENDPOINTS}
by_id = {ep_id: f for f, ep_id in futures.items()}
results: Dict[str, Dict[str, str]] = {}
+
+ def _first_ready(require_done: bool) -> Optional[Dict[str, str]]:
+ # Walk endpoints in PRIORITY order; a lower-priority success only wins once every
+ # higher-priority probe has finished without success.
+ for ep in ZAI_ENDPOINTS:
+ if require_done and not by_id[ep[0]].done():
+ return None # a higher-priority probe is still in flight
+ if ep[0] in results:
+ return results[ep[0]]
+ return None
+
for future in as_completed(futures):
- ep_id = futures[future]
try:
result = future.result()
if result is not None:
- results[ep_id] = result
+ results[futures[future]] = result
except Exception:
pass
- # Early exit in PRIORITY order: walk endpoints highest-priority
- # first; if one has succeeded and every higher-priority probe
- # has already finished (without success), no later completion
- # can win — return now instead of waiting out slow endpoints
- # (main's sequential loop also stopped at first success).
- for ep in ZAI_ENDPOINTS:
- if not by_id[ep[0]].done():
- break # a higher-priority probe is still in flight
- if ep[0] in results:
- return results[ep[0]]
-
- # All probes finished: first match in priority order, if any.
- for ep in ZAI_ENDPOINTS:
- if ep[0] in results:
- return results[ep[0]]
- return None
+ winner = _first_ready(require_done=True)
+ if winner is not None:
+ return winner
+ return _first_ready(require_done=False)
finally:
pool.shutdown(wait=False)
def _resolve_zai_base_url(api_key: str, default_url: str, env_override: str) -> str:
- """Return the correct Z.AI base URL by probing endpoints.
+ """Z.AI base URL by probing endpoints; an explicit GLM_BASE_URL always wins.
- If the user has explicitly set GLM_BASE_URL, that always wins. Otherwise, probe the candidate
- endpoints to find one that accepts the key. The detected endpoint is cached in provider state
- (auth.json) keyed on a hash of the API key so subsequent starts skip the probe.
+ The detected endpoint is cached in provider state (auth.json) keyed on a hash of the API key so
+ subsequent starts skip the probe.
"""
from hermes_cli.auth import _auth_store_lock, _load_auth_store, _load_provider_state, _save_auth_store, _store_provider_state, detect_zai_endpoint
if env_override:
return env_override
-
- # No API key set → don't probe (would fire N×M HTTPS requests with an
- # empty Bearer token, all returning 401). This path is hit during
- # auxiliary-client auto-detection when the user has no Z.AI credentials
- # at all — the caller discards the result immediately, so the probe is
- # pure latency for every AIAgent construction.
+ # No API key → don't probe (N×M HTTPS requests with an empty Bearer, all 401). Hit during
+ # auxiliary-client auto-detection for users with no Z.AI credentials at all — pure latency.
if not api_key:
return default_url
- # Check provider-state cache for a previously-detected endpoint.
- auth_store = _load_auth_store()
- state = _load_provider_state(auth_store, "zai") or {}
+ key_hash = hashlib.sha256(api_key.encode()).hexdigest()[:16]
+ state = _load_provider_state(_load_auth_store(), "zai") or {}
cached = state.get("detected_endpoint")
- if isinstance(cached, dict) and cached.get("base_url"):
- key_hash = cached.get("key_hash", "")
- if key_hash == hashlib.sha256(api_key.encode()).hexdigest()[:16]:
- logger.debug("Z.AI: using cached endpoint %s", cached["base_url"])
- return cached["base_url"]
+ if isinstance(cached, dict) and cached.get("base_url") and cached.get("key_hash", "") == key_hash:
+ logger.debug("Z.AI: using cached endpoint %s", cached["base_url"])
+ return cached["base_url"]
# Probe — may take up to ~8s per endpoint.
detected = detect_zai_endpoint(api_key)
- if detected and detected.get("base_url"):
- # Persist the detection result keyed on the API key hash.
- key_hash = hashlib.sha256(api_key.encode()).hexdigest()[:16]
- detected_endpoint = {
- "base_url": detected["base_url"],
- "endpoint_id": detected.get("id", ""),
- "model": detected.get("model", ""),
- "label": detected.get("label", ""),
- "key_hash": key_hash,
- }
- # Persist failure (disk full, permissions, lock timeout) must not
- # break resolution — detection already succeeded; worst case the
- # next start re-probes.
- try:
- with _auth_store_lock():
- # Reload auth_store under lock to avoid overwriting concurrent changes
- auth_store = _load_auth_store()
- state_under_lock = _load_provider_state(auth_store, "zai") or {}
- state_under_lock["detected_endpoint"] = detected_endpoint
- # set_active=False: this runs from credential-pool env seeding
- # (agent/credential_pool.py) for ANY user with a Z.AI key in env,
- # and caching a probe result must not flip their active provider.
- _store_provider_state(auth_store, "zai", state_under_lock, set_active=False)
- _save_auth_store(auth_store)
- except Exception as exc:
- logger.warning("Z.AI: could not persist detected endpoint (%s); will re-probe next start", exc)
- logger.info("Z.AI: auto-detected endpoint %s (%s)", detected["label"], detected["base_url"])
- return detected["base_url"]
+ if not (detected and detected.get("base_url")):
+ logger.debug("Z.AI: probe failed, falling back to default %s", default_url)
+ return default_url
- logger.debug("Z.AI: probe failed, falling back to default %s", default_url)
- return default_url
+ detected_endpoint = {
+ "base_url": detected["base_url"],
+ "endpoint_id": detected.get("id", ""),
+ "model": detected.get("model", ""),
+ "label": detected.get("label", ""),
+ "key_hash": key_hash,
+ }
+ # Persist failure (disk full, permissions, lock timeout) must not break resolution — detection
+ # already succeeded; worst case the next start re-probes.
+ try:
+ with _auth_store_lock():
+ auth_store = _load_auth_store() # reload under lock to avoid overwriting concurrent changes
+ state_under_lock = _load_provider_state(auth_store, "zai") or {}
+ state_under_lock["detected_endpoint"] = detected_endpoint
+ # set_active=False: this runs from credential-pool env seeding for ANY user with a Z.AI
+ # key in env, and caching a probe result must not flip their active provider.
+ _store_provider_state(auth_store, "zai", state_under_lock, set_active=False)
+ _save_auth_store(auth_store)
+ except Exception as exc:
+ logger.warning("Z.AI: could not persist detected endpoint (%s); will re-probe next start", exc)
+ logger.info("Z.AI: auto-detected endpoint %s (%s)", detected["label"], detected["base_url"])
+ return detected["base_url"]
def _normalize_lmstudio_runtime_base_url(base_url: str) -> str:
"""Return the OpenAI-compatible LM Studio runtime base URL.
LM Studio's native management API lives under ``/api/v1`` while its OpenAI-compatible chat
- endpoint lives under ``/v1``. Users often paste either form into ``LM_BASE_URL`` or
- ``model.base_url``; normalize before the OpenAI SDK appends ``/chat/completions``.
+ endpoint lives under ``/v1``; users paste either form, so normalize before the SDK appends
+ ``/chat/completions``.
"""
root = str(base_url or "").strip().rstrip("/")
for suffix in ("/api/v1", "/api", "/v1"):