The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore: stack on #115828 to resolve config_env.py conflict
teknium150638799b4ea
diff --cc apps/desktop/src/app/settings/custom-endpoints-settings.tsxindex 5b59e6c2478,f382d7da6db..8aef994b96b--- a/apps/desktop/src/app/settings/custom-endpoints-settings.tsx+++ b/apps/desktop/src/app/settings/custom-endpoints-settings.tsx@@@ -206,20 -179,26 +206,29 @@@ export function CustomEndpointsSettings}setDiscoveredModels(response.models)+ setDiscoveredDetails(response.model_details ?? [])if (response.ok) {+ // Persist the URL that actually served /models (e.g. "<root>/v1" when the user typed the+ // bare root): chat POSTs {base_url}/chat/completions verbatim, so saving the typed root+ // would 404 every request even though the test looked green (#65488).+ const resolvedBaseUrl = response.resolved_base_url?.trim()+if (!form.model && response.models[0]) {setForm(current => ({ ...current, model: response.models[0] }))}+ if (resolvedBaseUrl && resolvedBaseUrl !== form.baseUrl.trim().replace(/\/+$/, '')) {+ setForm(current => ({ ...current, baseUrl: resolvedBaseUrl }))+ }++ // The backend also POSTed the transport the runtime will use; name it so an+ // auto-detected mode is visible before Save (#93622).+ const transport = API_MODE_OPTIONS.find(option => option.id === response.transport_checked)?.label+ const reachable = transport ? `Endpoint is reachable (${transport} route served).` : 'Endpoint is reachable.'notify({kind: 'success',- message: response.models.length- ? `Endpoint is reachable. Found ${response.models.length} models.`- : 'Endpoint is reachable.'+ message: response.models.length ? `${reachable} Found ${response.models.length} models.` : reachable})} else {notify({diff --cc apps/desktop/src/types/hermes.tsindex 694ce0b97ca,0773ab74d55..9d4b27d459a--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@@ -280,8 -263,8 +280,10 @@@ export interface CustomEndpointValidatimodels: string[]ok: booleanreachable: boolean+ // Base URL that actually served /models (the entered URL or its /v1 variant); persist this one.+ resolved_base_url?: string+ /** The transport whose route the backend probed (pinned api_mode, or the runtime's URL auto-detect). */+ transport_checked?: CustomEndpointApiMode}export interface MessagingEnvVarInfo {diff --cc hermes_cli/web_routers/config_env.pyindex d38b4ad91e0,4a909762b13..1a46447f7e0--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@@ -769,72 -718,42 +768,98 @@@ async def validate_custom_endpoint(bodyif body.api_key and body.api_key.strip():headers["Authorization"] = f"Bearer {body.api_key.strip()}"+ resolved, resp = await _probe_openai_compatible_models(base_url, headers)+ if resp is None:+ return {"ok": False, "reachable": False, "message": f"Could not reach {base_url}/models.", "models": []}-+ if resp.status_code in (401, 403):+ return {"ok": False, "reachable": True, "message": "The endpoint rejected the API key.", "models": []}+ if not resp.is_success:+ return {"ok": False, "reachable": True, "message": f"Endpoint returned HTTP {resp.status_code}.", "models": []}++ # ``models`` stays the bare id list older clients read; ``model_details`` keeps the++ # alias metadata (``canonical_model`` / ``reasoning_effort``) the id list flattens.++ entries = _parse_model_entries(resp)++ ids = [e["id"] for e in entries]++ # /models answering proves nothing about the transport the runtime will POST to:++ # a Responses-only host lists models fine and 404s every /chat/completions (#93622).++ # Probe the route the saved mode (or the runtime's URL auto-detect) actually uses, on the++ # base that actually served /models (#65488) — that is the URL the runtime will persist.++ mode = _canonical_api_mode(body.api_mode or "").lower() or _auto_api_mode(resolved)++ probe_model = (body.model or "").strip() or (ids[0] if ids else "")+ try:- async with _endpoint_probe_client(url, 8.0) as client:- resp = await client.get(url, headers=headers)- if resp.status_code in (401, 403):- return {"ok": False, "reachable": True, "message": "The endpoint rejected the API key.", "models": []}- if not resp.is_success:- return {"ok": False, "reachable": True, "message": f"Endpoint returned HTTP {resp.status_code}.", "models": []}- # ``models`` stays the bare id list older clients read; ``model_details`` keeps the- # alias metadata (``canonical_model`` / ``reasoning_effort``) the id list flattens.- entries = _parse_model_entries(resp)- ids = [e["id"] for e in entries]- # /models answering proves nothing about the transport the runtime will POST to:- # a Responses-only host lists models fine and 404s every /chat/completions (#93622).- # Probe the route the saved mode (or the runtime's URL auto-detect) actually uses.- mode = _canonical_api_mode(body.api_mode or "").lower() or _auto_api_mode(base_url)- probe_model = (body.model or "").strip() or (ids[0] if ids else "")- missing = await _probe_transport_route(client, base_url, mode, probe_model, headers)++ async with _endpoint_probe_client(resolved, 8.0) as client:++ missing = await _probe_transport_route(client, resolved, mode, probe_model, headers)+ except Exception:- return {"ok": False, "reachable": False, "message": f"Could not reach {url}.", "models": []}++ missing = "" # inconclusive (see _probe_transport_route): never block on a transport error- return {"ok": True, "reachable": True, "message": "", "models": _parse_model_ids(resp), "resolved_base_url": resolved}-+ result = {"ok": True, "reachable": True, "message": "", "models": ids, "model_details": entries,- "transport_checked": mode}++ "transport_checked": mode, "resolved_base_url": resolved}+ if missing:+ result.update(ok=False, message=missing)+ return result+ async def _probe_openai_compatible_models(base_url: str, headers: Optional[dict]) -> Tuple[str, Any]:+ """GET ``{base}/models``, then ``{base}/v1/models`` (or the ``/v1``-stripped variant) when the+ first answers a non-success. Returns ``(resolved_base_url, response)`` — the base that served the+ model list is what the caller must PERSIST: the runtime appends ``/chat/completions`` to the saved+ URL verbatim, so a bare host root that only "detected" via ``/v1/models`` would 404 every chat+ (#65488). ``response`` is None when no candidate could be reached at all."""+ base = base_url.rstrip("/")+ alternate = base[:-3].rstrip("/") if base.lower().endswith("/v1") else base + "/v1"+ resolved, resp = base, None+ async with _endpoint_probe_client(base, 8.0) as client:+ for candidate in (base, alternate):+ try:+ candidate_resp = await client.get(candidate + "/models", headers=headers)+ except Exception:+ continue+ # Keep the most telling failure: a 401/403 from the /v1 alternate says "server is+ # there, key rejected", which beats the typed root's 404 (wrong path).+ if resp is None or candidate_resp.is_success or resp.status_code == 404:+ resolved, resp = candidate, candidate_resp+ if candidate_resp.is_success:+ break+ return resolved, resp++_TRANSPORT_ROUTES = {"chat_completions": "/chat/completions", "codex_responses": "/responses",+ "anthropic_messages": "/messages"}+_TRANSPORT_LABELS = {"chat_completions": "Chat Completions", "codex_responses": "Responses API",+ "anthropic_messages": "Anthropic Messages"}+++def _auto_api_mode(base_url: str) -> str:+ """The transport the runtime falls back to for an endpoint without a pinned ``api_mode``+ (same resolver as ``runtime_provider_custom._custom_runtime``)."""+ from hermes_cli.runtime_provider import _detect_api_mode_for_url+ return _detect_api_mode_for_url(base_url) or "chat_completions"+++async def _probe_transport_route(client, base_url: str, mode: str, model: str, headers: Dict[str, str]) -> str:+ """POST a 1-token request to ``mode``'s route; return a failure message when the host does+ not serve it (404/405/501), ``""`` otherwise. Any other status — 200, 400 (bad body), 401,+ 422, 429 — means the route exists, which is all the check needs to know; a network error or+ timeout (a local server still loading the model) is inconclusive and does not block."""+ route = _TRANSPORT_ROUTES.get(mode)+ if route is None:+ return ""+ if mode == "anthropic_messages":+ payload = {"model": model, "max_tokens": 1, "messages": [{"role": "user", "content": "hi"}]}+ token = headers.get("Authorization", "").removeprefix("Bearer ")+ headers = {**headers, "anthropic-version": "2023-06-01", **({"x-api-key": token} if token else {})}+ elif mode == "codex_responses":+ payload = {"model": model, "input": "hi", "max_output_tokens": 16}+ else:+ payload = {"model": model, "max_tokens": 1, "messages": [{"role": "user", "content": "hi"}]}+ try:+ resp = await client.post(base_url + route, json=payload, headers=headers)+ except Exception:+ return ""+ if resp.status_code not in (404, 405, 501):+ return ""+ return (f"{base_url}/models answered, but POST {route} returned HTTP {resp.status_code}: this host "+ f"does not serve the {_TRANSPORT_LABELS[mode]} API. Pick the API mode it does serve.")++def _endpoint_probe_client(url: str, timeout: float):"""httpx client for a user-entered endpoint probe. Local endpoints (loopback, LAN, Tailscale)ignore ``HTTP(S)_PROXY``: httpx honours the env/system proxy but not its bypass list, so a@@@ -868,21 -787,18 +893,20 @@@ async def validate_provider_credential(# default. The optional API key is sent so servers that require auth on# ``/v1/models`` still enumerate instead of returning an empty list.if key == "OPENAI_BASE_URL":- url = value.rstrip("/") + "/models"api_key = (body.api_key or "").strip()headers = {"Authorization": f"Bearer {api_key}"} if api_key else None- try:- async with _endpoint_probe_client(url, 8.0) as client:- resp = await client.get(url, headers=headers)- except Exception:+ resolved, resp = await _probe_openai_compatible_models(value, headers)+ url = resolved + "/models"+ if resp is None:return {"ok": False, "reachable": False, "message": f"Could not reach {url}."}- models = _parse_model_ids(resp)+ entries = _parse_model_entries(resp)+ models = [e["id"] for e in entries]if not models and not resp.is_success:# A proxy/gateway error page parses as "no models"; name the status instead so the# GUI does not tell the user to "start a model" on a server that answered.return {"ok": False, "reachable": True, "message": f"{url} answered HTTP {resp.status_code}.", "models": []}- return {"ok": True, "reachable": True, "message": "", "models": models, "model_details": entries}- return {"ok": True, "reachable": True, "message": "", "models": models, "resolved_base_url": resolved}++ return {"ok": True, "reachable": True, "message": "", "models": models, "model_details": entries,++ "resolved_base_url": resolved}probe = _CREDENTIAL_PROBES.get(key)if not probe:diff --cc tests/hermes_cli/test_web_server.pyindex e3ad671fad6,022e8674bf6..73f012b8238--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@@ -5387,8 -5243,7 +5387,9 @@@ class TestValidateProviderCredential"reachable": True,"message": "","models": ["local-model"],+ "resolved_base_url": "http://localhost:8000/v1",+ "model_details": [{"id": "local-model"}],+ "transport_checked": "chat_completions",}assert captured == {"url": "http://localhost:8000/v1/models",