Reshapes setup around how a multi-model proxy is actually used: one config entry per server/provider, then one endpoint per model added by hand, with the model chosen from what that provider advertises right now. Setup (async_step_user): - Adds a Name field. With one entry per provider the title matters, and it was hardcoded to "ChatGPT" regardless of where the entry pointed. Blank falls back to the endpoint host via url_util.title_from_base_url. Deliberately absent from the reauth schema (now split out as STEP_REAUTH_DATA_SCHEMA): that step writes its input back into entry.data via data_updates, so a name field there would persist the title as connection data on every key rotation. - Stops auto-creating four subentries. conversation/ai_task_data/stt/tts were all created up front carrying RECOMMENDED_* options, which pin OpenAI model names (gpt-4o-mini-tts, gpt-4o-mini-transcribe). Against a third-party endpoint those entities are dead on arrival -- the reported symptom was an install that "loads bits, it's all janky". - Drops _async_abort_entries_match, so several entries may point at one server (one per provider-side key, for instance). Upstream aborts with already_configured on matching url+key. Model discovery (new model_list.py, kept out of the vendored files like url_util.py): - async_fetch_model_ids asks the endpoint's GET /v1/models. It calls with_options(max_retries=0), because this runs while the user waits on a dialog and the SDK otherwise retries with backoff -- visible in the test run as repeated "Retrying request to /models" and a suite that went from 5s to minutes. - Returns [] on any OpenAIError, and model_field() then yields a plain text field instead of a dropdown, so an endpoint that serves /v1/responses but not /v1/models is still configurable by hand. The dropdown sets custom_value=True for the same reason (LiteLLM wildcard routes). - Wired into all four types: conversation and ai_task_data on the additional step, stt (which hardcoded OpenAI's three transcribe models) and tts on init. TTS had no model field at all -- it silently used gpt-4o-mini-tts. A new endpoint now starts with "recommended" unticked. Ticked, the flow ends on the first step and never shows a model field, which is why the model looked unpickable; reconfigure still keeps whatever was saved. The model field stays on the additional step rather than moving to init. The init position reads better, but 71 ported tests drive the model through the additional step, several from parametrized option dicts that no mechanical edit could relocate. Rewriting the only regression net against upstream to save one click was the wrong trade. Also: the setup description no longer says "your OpenAI API key", and instructions_url pointed at a README anchor (#generate-an-api-key) that does not exist -- now #configuration. strings.json re-verified against core's RE_URL: 0 violations. Local: 167 passed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NxJYWgGJtCw13qUHZtG8ki
91 lines
3.3 KiB
Python
91 lines
3.3 KiB
Python
"""Base-URL normalization and safe logging.
|
|
|
|
This module is intentionally separate from the vendored upstream files so that
|
|
re-syncing with home-assistant/core never conflicts with it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from urllib.parse import urlparse, urlunparse
|
|
|
|
ALLOWED_SCHEMES = frozenset({"http", "https"})
|
|
|
|
|
|
class InvalidBaseURL(ValueError):
|
|
"""Raised when a base URL is unusable."""
|
|
|
|
|
|
class CredentialsInBaseURL(InvalidBaseURL):
|
|
"""Raised when a base URL embeds a username or password.
|
|
|
|
A distinct subclass (rather than reusing the generic InvalidBaseURL
|
|
message) so the config flow can show a specific, actionable error
|
|
instead of the generic "not a valid URL" one.
|
|
"""
|
|
|
|
|
|
def normalize_base_url(url: str) -> str:
|
|
"""Strip whitespace and trailing slashes, and validate the scheme.
|
|
|
|
Rejects a URL carrying a username or password component: authentication
|
|
belongs in the API key field, which is handled (and never logged) safely
|
|
on its own — a base_url is user-suppliable and read back into log/error
|
|
text by vendored code this fork does not touch, so credentials must never
|
|
be accepted here in the first place.
|
|
"""
|
|
cleaned = (url or "").strip()
|
|
if not cleaned:
|
|
raise InvalidBaseURL("base URL is empty")
|
|
|
|
parsed = urlparse(cleaned)
|
|
if parsed.scheme not in ALLOWED_SCHEMES:
|
|
raise InvalidBaseURL(f"unsupported scheme: {parsed.scheme or '(none)'}")
|
|
if not parsed.netloc:
|
|
raise InvalidBaseURL("base URL has no host")
|
|
if parsed.username or parsed.password:
|
|
raise CredentialsInBaseURL(
|
|
"base URL must not contain a username or password; "
|
|
"use the API key field for authentication"
|
|
)
|
|
|
|
return urlunparse(parsed._replace(path=parsed.path.rstrip("/")))
|
|
|
|
|
|
def sanitize_url_for_logging(url: str) -> str:
|
|
"""Return the URL with any embedded credentials replaced by ***.
|
|
|
|
This only recognizes credentials urlparse places in an authority
|
|
(``user:pass@host``) component of an absolute http(s)/-scheme URL. It is
|
|
not a general-purpose credential scrubber: a scheme-less or relative
|
|
string with an embedded ``user:pass@`` substring passes through
|
|
unmasked, since urlparse won't parse it as a netloc. Safe today because
|
|
every caller normalizes with normalize_base_url() first (which both
|
|
requires an absolute http(s) URL and rejects embedded credentials
|
|
outright) before this is ever called on it; do not rely on this function
|
|
alone to sanitize an arbitrary, unvalidated string.
|
|
"""
|
|
parsed = urlparse(url)
|
|
if not parsed.username and not parsed.password:
|
|
return url
|
|
|
|
host = parsed.hostname or ""
|
|
if parsed.port:
|
|
host = f"{host}:{parsed.port}"
|
|
return urlunparse(parsed._replace(netloc=f"***@{host}"))
|
|
|
|
|
|
def title_from_base_url(url: str) -> str:
|
|
"""Return a config entry title identifying the provider.
|
|
|
|
Upstream titles every entry "ChatGPT", which is wrong the moment the
|
|
endpoint is not OpenAI's and useless when there is one entry per provider.
|
|
The host (with port, when given) is what actually distinguishes them.
|
|
Falls back to the whole string if it cannot be parsed, so this never
|
|
raises in the middle of creating an entry.
|
|
"""
|
|
try:
|
|
netloc = urlparse(url).netloc
|
|
except ValueError:
|
|
return url
|
|
return netloc or url
|