Skip to content

Agent Zero AI framework

Simplify OAuth provider plumbing

Alessandro0ef60326e743
diff --git a/plugins/_oauth/helpers/providers/base.py b/plugins/_oauth/helpers/providers/base.py
index 31c3e3324..622d340ef 100644
--- a/plugins/_oauth/helpers/providers/base.py
+++ b/plugins/_oauth/helpers/providers/base.py
@@ -61,9 +61,6 @@ class OAuthProviderMetadata:
supports_quota_project: bool = False
note: str = ""
warning: str = ""
- usage_plans: list[dict[str, Any]] = field(default_factory=list)
- usage_plan_notes: list[str] = field(default_factory=list)
- usage_plan_sources: list[dict[str, str]] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
diff --git a/plugins/_oauth/helpers/providers/codex.py b/plugins/_oauth/helpers/providers/codex.py
index 56f6ea5cc..7a2eb7218 100644
--- a/plugins/_oauth/helpers/providers/codex.py
+++ b/plugins/_oauth/helpers/providers/codex.py
@@ -12,11 +12,6 @@ from plugins._oauth.helpers.providers.base import (
LoginStartResult,
OAuthProviderMetadata,
)
-from plugins._oauth.helpers.usage_plans import (
- usage_plan_notes_for,
- usage_plan_sources_for,
- usage_plans_for,
-)
from plugins._oauth.helpers.state import (
get_device_attempt,
pop_device_attempt,
@@ -52,9 +47,6 @@ class CodexOAuthProvider:
default_models=models,
proxy_base_path=cfg["proxy_base_path"],
callback_path=cfg["callback_path"],
- usage_plans=usage_plans_for(CODEX_PROVIDER_ID),
- usage_plan_notes=usage_plan_notes_for(CODEX_PROVIDER_ID),
- usage_plan_sources=usage_plan_sources_for(CODEX_PROVIDER_ID),
)
def status(self) -> dict[str, Any]:
diff --git a/plugins/_oauth/helpers/providers/common.py b/plugins/_oauth/helpers/providers/common.py
new file mode 100644
index 000000000..c1b85812a
--- /dev/null
+++ b/plugins/_oauth/helpers/providers/common.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+import time
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+from plugins._oauth.helpers import state as state_store
+
+
+def parse_manual_callback(raw: Any) -> dict[str, str | None] | None:
+ text = "" if raw is None else str(raw).strip()
+ if not text:
+ return None
+
+ if text.startswith("http://") or text.startswith("https://"):
+ query = urlparse(text).query
+ elif text.startswith("?"):
+ query = text[1:]
+ elif "=" in text or "&" in text:
+ query = text
+ else:
+ return {
+ "code": text,
+ "state": None,
+ "error": None,
+ "error_description": None,
+ }
+
+ parsed = parse_qs(query, keep_blank_values=True)
+ return {
+ "code": first_query_value(parsed, "code"),
+ "state": first_query_value(parsed, "state"),
+ "error": first_query_value(parsed, "error"),
+ "error_description": first_query_value(parsed, "error_description"),
+ }
+
+
+def latest_attempt(provider_id: str):
+ state_store.cleanup_expired()
+ with state_store._lock:
+ attempts = [
+ attempt
+ for attempt in state_store._attempts.values()
+ if attempt.provider_id == provider_id and not attempt.expired()
+ ]
+ if not attempts:
+ return None
+ return max(attempts, key=lambda attempt: attempt.created_at)
+
+
+def models_from_payload(payload: Any) -> list[str]:
+ values: list[Any]
+ if isinstance(payload, dict) and isinstance(payload.get("data"), list):
+ values = payload["data"]
+ elif isinstance(payload, dict) and isinstance(payload.get("models"), list):
+ values = payload["models"]
+ elif isinstance(payload, list):
+ values = payload
+ else:
+ return []
+
+ models: list[str] = []
+ seen: set[str] = set()
+ for value in values:
+ model_id = ""
+ if isinstance(value, str):
+ model_id = value
+ elif isinstance(value, dict):
+ model_id = str(value.get("id") or value.get("name") or "")
+ model_id = model_id.strip()
+ if model_id.startswith("models/"):
+ model_id = model_id.split("/", 1)[1]
+ if model_id and model_id not in seen:
+ seen.add(model_id)
+ models.append(model_id)
+ return models
+
+
+def json_payload(response: Any) -> dict[str, Any]:
+ try:
+ payload = response.json()
+ except Exception:
+ payload = {}
+ if not isinstance(payload, dict):
+ return {}
+ return payload
+
+
+def error_message(payload: dict[str, Any], fallback: str) -> str:
+ error = payload.get("error")
+ if isinstance(error, dict):
+ return str(error.get("message") or error.get("status") or fallback)
+ return str(payload.get("error_description") or payload.get("error") or fallback)
+
+
+def first_query_value(parsed: dict[str, list[str]], key: str) -> str | None:
+ values = parsed.get(key) or []
+ if not values:
+ return None
+ return values[0]
+
+
+def as_optional_string(value: Any) -> str | None:
+ if isinstance(value, list):
+ value = value[0] if value else None
+ text = "" if value is None else str(value).strip()
+ return text or None
+
+
+def expires_ms(payload: dict[str, Any]) -> int:
+ if payload.get("expires_at") is not None:
+ try:
+ value = float(payload["expires_at"])
+ if value < 1_000_000_000_000:
+ value *= 1000
+ return int(value)
+ except (TypeError, ValueError):
+ pass
+ try:
+ return int((time.time() + float(payload.get("expires_in") or 0)) * 1000)
+ except (TypeError, ValueError):
+ return 0
+
+
+def as_int(value: Any, default: int) -> int:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
diff --git a/plugins/_oauth/helpers/providers/gemini_api.py b/plugins/_oauth/helpers/providers/gemini_api.py
index 48fe2749e..2252fb6d2 100644
--- a/plugins/_oauth/helpers/providers/gemini_api.py
+++ b/plugins/_oauth/helpers/providers/gemini_api.py
@@ -5,7 +5,7 @@ import json
import time
from pathlib import Path
from typing import Any
-from urllib.parse import parse_qs, urlencode, urlparse
+from urllib.parse import urlencode, urlparse
from plugins._oauth.helpers.providers.base import (
DUMMY_API_KEY,
@@ -19,12 +19,16 @@ from plugins._oauth.helpers.providers.base import (
read_json_file,
write_private_json,
)
-from plugins._oauth.helpers.usage_plans import (
- usage_plan_notes_for,
- usage_plan_sources_for,
- usage_plans_for,
+from plugins._oauth.helpers.providers.common import (
+ as_int as _as_int,
+ as_optional_string as _as_optional_string,
+ error_message as _error_message,
+ expires_ms as _expires_ms,
+ json_payload as _json_payload,
+ latest_attempt,
+ models_from_payload as _models_from_payload,
+ parse_manual_callback,
)
-from plugins._oauth.helpers import state as state_store
from plugins._oauth.helpers.state import get_attempt, pop_attempt, put_attempt
@@ -48,34 +52,6 @@ CLIENT_CONFIG_NOTE = (
REFRESH_MARGIN_MS = 60_000
-def parse_manual_callback(raw: Any) -> dict[str, str | None] | None:
- text = "" if raw is None else str(raw).strip()
- if not text:
- return None
-
- if text.startswith("http://") or text.startswith("https://"):
- query = urlparse(text).query
- elif text.startswith("?"):
- query = text[1:]
- elif "=" in text or "&" in text:
- query = text
- else:
- return {
- "code": text,
- "state": None,
- "error": None,
- "error_description": None,
- }
-
- parsed = parse_qs(query, keep_blank_values=True)
- return {
- "code": _first_query_value(parsed, "code"),
- "state": _first_query_value(parsed, "state"),
- "error": _first_query_value(parsed, "error"),
- "error_description": _first_query_value(parsed, "error_description"),
- }
-
-
class GeminiApiOAuthProvider:
provider_id = GEMINI_API_PROVIDER_ID
@@ -106,9 +82,6 @@ class GeminiApiOAuthProvider:
supports_oauth_client_config=True,
supports_quota_project=True,
note=CLIENT_CONFIG_NOTE,
- usage_plans=usage_plans_for(GEMINI_API_PROVIDER_ID),
- usage_plan_notes=usage_plan_notes_for(GEMINI_API_PROVIDER_ID),
- usage_plan_sources=usage_plan_sources_for(GEMINI_API_PROVIDER_ID),
)
def status(self) -> dict[str, Any]:
@@ -302,7 +275,7 @@ class GeminiApiOAuthProvider:
if state:
attempt = get_attempt(state)
if attempt is None:
- if _latest_gemini_attempt() is not None:
+ if latest_attempt(GEMINI_API_PROVIDER_ID) is not None:
return LoginPollResult(
ok=False,
provider_id=GEMINI_API_PROVIDER_ID,
@@ -321,7 +294,7 @@ class GeminiApiOAuthProvider:
error="OAuth state mismatch. Return to Agent Zero and start a new Google Gemini API connection.",
)
elif allow_missing_state:
- attempt = _latest_gemini_attempt()
+ attempt = latest_attempt(GEMINI_API_PROVIDER_ID)
if attempt is None:
return LoginPollResult(
ok=False,
@@ -642,78 +615,6 @@ def _validate_google_token_endpoint(value: str) -> None:
)
-def _latest_gemini_attempt():
- state_store.cleanup_expired()
- with state_store._lock:
- attempts = [
- attempt
- for attempt in state_store._attempts.values()
- if attempt.provider_id == GEMINI_API_PROVIDER_ID and not attempt.expired()
- ]
- if not attempts:
- return None
- return max(attempts, key=lambda attempt: attempt.created_at)
-
-
-def _models_from_payload(payload: Any) -> list[str]:
- values: list[Any]
- if isinstance(payload, dict) and isinstance(payload.get("data"), list):
- values = payload["data"]
- elif isinstance(payload, dict) and isinstance(payload.get("models"), list):
- values = payload["models"]
- elif isinstance(payload, list):
- values = payload
- else:
- return []
-
- models: list[str] = []
- seen: set[str] = set()
- for value in values:
- model_id = ""
- if isinstance(value, str):
- model_id = value
- elif isinstance(value, dict):
- model_id = str(value.get("id") or value.get("name") or "")
- model_id = model_id.strip()
- if model_id.startswith("models/"):
- model_id = model_id.split("/", 1)[1]
- if model_id and model_id not in seen:
- seen.add(model_id)
- models.append(model_id)
- return models
-
-
-def _json_payload(response: Any) -> dict[str, Any]:
- try:
- payload = response.json()
- except Exception:
- payload = {}
- if not isinstance(payload, dict):
- return {}
- return payload
-
-
-def _error_message(payload: dict[str, Any], fallback: str) -> str:
- error = payload.get("error")
- if isinstance(error, dict):
- return str(error.get("message") or error.get("status") or fallback)
- return str(payload.get("error_description") or payload.get("error") or fallback)
-
-
-def _first_query_value(parsed: dict[str, list[str]], key: str) -> str | None:
- values = parsed.get(key) or []
- if not values:
- return None
- return values[0]
-
-
-def _as_optional_string(value: Any) -> str | None:
- if isinstance(value, list):
- value = value[0] if value else None
- text = "" if value is None else str(value).strip()
- return text or None
-
-
def _account_label(auth: dict[str, Any]) -> str:
claims = _jwt_claims(str(auth.get("id_token") or ""))
return str(claims.get("email") or auth.get("account_label") or "Google Gemini API")
@@ -732,28 +633,6 @@ def _jwt_claims(token: str) -> dict[str, Any]:
return parsed if isinstance(parsed, dict) else {}
-def _expires_ms(payload: dict[str, Any]) -> int:
- if payload.get("expires_at") is not None:
- try:
- value = float(payload["expires_at"])
- if value < 1_000_000_000_000:
- value *= 1000
- return int(value)
- except (TypeError, ValueError):
- pass
- try:
- return int((time.time() + float(payload.get("expires_in") or 0)) * 1000)
- except (TypeError, ValueError):
- return 0
-
-
-def _as_int(value: Any, default: int) -> int:
- try:
- return int(value)
- except (TypeError, ValueError):
- return default
-
-
def _codex_helper():
import importlib
diff --git a/plugins/_oauth/helpers/providers/github_copilot.py b/plugins/_oauth/helpers/providers/github_copilot.py
index beaf0f752..2adbc411f 100644
--- a/plugins/_oauth/helpers/providers/github_copilot.py
+++ b/plugins/_oauth/helpers/providers/github_copilot.py
@@ -18,11 +18,6 @@ from plugins._oauth.helpers.providers.base import (
read_json_file,
write_private_json,
)
-from plugins._oauth.helpers.usage_plans import (
- usage_plan_notes_for,
- usage_plan_sources_for,
- usage_plans_for,
-)
from plugins._oauth.helpers.state import (
DeviceAttempt,
get_device_attempt,
@@ -213,9 +208,6 @@ class GitHubCopilotOAuthProvider:
proxy_base_path="/oauth/github-copilot",
supports_enterprise_domain=True,
note=ENTERPRISE_NOTE,
- usage_plans=usage_plans_for(GITHUB_COPILOT_PROVIDER_ID),
- usage_plan_notes=usage_plan_notes_for(GITHUB_COPILOT_PROVIDER_ID),
- usage_plan_sources=usage_plan_sources_for(GITHUB_COPILOT_PROVIDER_ID),
)
def status(self) -> dict[str, Any]:
diff --git a/plugins/_oauth/helpers/providers/xai_grok.py b/plugins/_oauth/helpers/providers/xai_grok.py
index a01e72654..b94555ef9 100644
--- a/plugins/_oauth/helpers/providers/xai_grok.py
+++ b/plugins/_oauth/helpers/providers/xai_grok.py
@@ -5,7 +5,7 @@ import time
import importlib
from pathlib import Path
from typing import Any
-from urllib.parse import parse_qs, urlencode, urlparse
+from urllib.parse import urlencode, urlparse
from plugins._oauth.helpers.providers.base import (
DUMMY_API_KEY,
@@ -19,12 +19,16 @@ from plugins._oauth.helpers.providers.base import (
read_json_file,
write_private_json,
)
-from plugins._oauth.helpers.usage_plans import (
- usage_plan_notes_for,
- usage_plan_sources_for,
- usage_plans_for,
+from plugins._oauth.helpers.providers.common import (
+ as_int as _as_int,
+ as_optional_string as _as_optional_string,
+ error_message as _error_message,
+ expires_ms as _expires_ms,
+ json_payload as _json_payload,
+ latest_attempt,
+ models_from_payload as _models_from_payload,
+ parse_manual_callback,
)
-from plugins._oauth.helpers import state as state_store
from plugins._oauth.helpers.state import get_attempt, pop_attempt, put_attempt
@@ -49,34 +53,6 @@ OAUTH_TIER_WARNING = (
REFRESH_MARGIN_MS = 60_000
-def parse_manual_callback(raw: Any) -> dict[str, str | None] | None:
- text = "" if raw is None else str(raw).strip()
- if not text:
- return None
-
- if text.startswith("http://") or text.startswith("https://"):
- query = urlparse(text).query
- elif text.startswith("?"):
- query = text[1:]
- elif "=" in text or "&" in text:
- query = text
- else:
- return {
- "code": text,
- "state": None,
- "error": None,
- "error_description": None,
- }
-
- parsed = parse_qs(query, keep_blank_values=True)
- return {
- "code": _first_query_value(parsed, "code"),
- "state": _first_query_value(parsed, "state"),
- "error": _first_query_value(parsed, "error"),
- "error_description": _first_query_value(parsed, "error_description"),
- }
-
-
class XaiGrokOAuthProvider:
provider_id = XAI_GROK_PROVIDER_ID
@@ -133,9 +109,6 @@ class XaiGrokOAuthProvider:
callback_path="/oauth/xai-grok/callback",
supports_manual_callback=True,
warning=OAUTH_TIER_WARNING,
- usage_plans=usage_plans_for(XAI_GROK_PROVIDER_ID),
- usage_plan_notes=usage_plan_notes_for(XAI_GROK_PROVIDER_ID),
- usage_plan_sources=usage_plan_sources_for(XAI_GROK_PROVIDER_ID),
)
def status(self) -> dict[str, Any]:
@@ -312,7 +285,7 @@ class XaiGrokOAuthProvider:
if state:
attempt = get_attempt(state)
if attempt is None:
- if _latest_xai_attempt() is not None:
+ if latest_attempt(XAI_GROK_PROVIDER_ID) is not None:
return LoginPollResult(
ok=False,
provider_id=XAI_GROK_PROVIDER_ID,
@@ -331,7 +304,7 @@ class XaiGrokOAuthProvider:
error="OAuth state mismatch. Return to Agent Zero and start a new xAI Grok connection.",
)
elif allow_missing_state:
- attempt = _latest_xai_attempt()
+ attempt = latest_attempt(XAI_GROK_PROVIDER_ID)
if attempt is None:
return LoginPollResult(
ok=False,
@@ -572,92 +545,3 @@ def _validate_xai_endpoint(value: str, *, code: str = "discovery_invalid_endpoin
code=code,
status=502,
)
-
-
-def _latest_xai_attempt():
- state_store.cleanup_expired()
- with state_store._lock:
- attempts = [
- attempt
- for attempt in state_store._attempts.values()
- if attempt.provider_id == XAI_GROK_PROVIDER_ID and not attempt.expired()
- ]
- if not attempts:
- return None
- return max(attempts, key=lambda attempt: attempt.created_at)
-
-
-def _models_from_payload(payload: Any) -> list[str]:
- values: list[Any]
- if isinstance(payload, dict) and isinstance(payload.get("data"), list):
- values = payload["data"]
- elif isinstance(payload, dict) and isinstance(payload.get("models"), list):
- values = payload["models"]
- elif isinstance(payload, list):
- values = payload
- else:
- return []
-
- models: list[str] = []
- seen: set[str] = set()
- for value in values:
- model_id = ""
- if isinstance(value, str):
- model_id = value
- elif isinstance(value, dict):
- model_id = str(value.get("id") or value.get("name") or "")
- model_id = model_id.strip()
- if model_id and model_id not in seen:
- seen.add(model_id)
- models.append(model_id)
- return models
-
-
-def _json_payload(response: Any) -> dict[str, Any]:
- try:
- payload = response.json()
- except Exception:
- payload = {}
- if not isinstance(payload, dict):
- return {}
- return payload
-
-
-def _error_message(payload: dict[str, Any], fallback: str) -> str:
- return str(payload.get("error_description") or payload.get("error") or fallback)
-
-
-def _first_query_value(parsed: dict[str, list[str]], key: str) -> str | None:
- values = parsed.get(key) or []
- if not values:
- return None
- return values[0]
-
-
-def _as_optional_string(value: Any) -> str | None:
- if isinstance(value, list):
- value = value[0] if value else None
- text = "" if value is None else str(value).strip()
- return text or None
-
-
-def _expires_ms(payload: dict[str, Any]) -> int:
- if payload.get("expires_at") is not None:
- try:
- value = float(payload["expires_at"])
- if value < 1_000_000_000_000:
- value *= 1000
- return int(value)
- except (TypeError, ValueError):
- pass
- try:
- return int((time.time() + float(payload.get("expires_in") or 0)) * 1000)
- except (TypeError, ValueError):
- return 0
-
-
-def _as_int(value: Any, default: int) -> int:
- try:
- return int(value)
- except (TypeError, ValueError):
- return default
diff --git a/plugins/_oauth/helpers/routes.py b/plugins/_oauth/helpers/routes.py
index 0008b430f..e0cb78a13 100644
--- a/plugins/_oauth/helpers/routes.py
+++ b/plugins/_oauth/helpers/routes.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import ipaddress
import json
import time
-from typing import Any
+from typing import Any, Callable
from flask import Response, jsonify, request, stream_with_context
@@ -357,62 +357,63 @@ def gemini_api_responses():
def _github_copilot_json_proxy(path: str):
- denied = _proxy_denied_response()
- if denied:
- return denied
+ from plugins._oauth.helpers.providers.github_copilot import COPILOT_HEADERS, safe_copilot_base_url
+
+ return _oauth_json_proxy(
+ GITHUB_COPILOT_PROVIDER_ID,
+ path,
+ "GitHub Copilot OAuth is not connected.",
+ lambda auth: safe_copilot_base_url(auth.get("base_url"), auth.get("enterprise_domain")),
+ lambda auth, access: {
+ **COPILOT_HEADERS,
+ "Authorization": f"Bearer {access}",
+ "Content-Type": "application/json",
+ },
+ )
- body = request.get_json(silent=True)
- if not isinstance(body, dict):
- return _json_error("Request body must be a JSON object.")
- provider = get_provider(GITHUB_COPILOT_PROVIDER_ID)
- ensure_fresh_auth = getattr(provider, "ensure_fresh_auth", None)
- read_auth = getattr(provider, "read_auth", None)
- try:
- if callable(ensure_fresh_auth):
- auth = ensure_fresh_auth()
- elif callable(read_auth):
- auth = read_auth()
- else:
- auth = {}
- except ProviderError as exc:
- return _json_error(str(exc), status=exc.status, code=exc.code)
- except Exception as exc:
- return _json_error(str(exc), status=502, code="upstream_error")
- access = str(auth.get("access") or "")
- if not access:
- return _json_error("GitHub Copilot OAuth is not connected.", status=401, code="not_connected")
-
- wants_stream = body.get("stream") is True
- try:
- import requests
+def _xai_grok_json_proxy(path: str):
+ from plugins._oauth.helpers.providers.xai_grok import safe_api_base_url
- from plugins._oauth.helpers.providers.github_copilot import COPILOT_HEADERS, safe_copilot_base_url
+ return _oauth_json_proxy(
+ XAI_GROK_PROVIDER_ID,
+ path,
+ "xAI Grok OAuth is not connected.",
+ lambda auth: safe_api_base_url(auth.get("base_url")),
+ lambda auth, access: {
+ "Accept": "application/json",
+ "Authorization": f"Bearer {access}",
+ "Content-Type": "application/json",
+ },
+ require_refresh=True,
+ )
- base_url = safe_copilot_base_url(auth.get("base_url"), auth.get("enterprise_domain"))
- upstream = requests.post(
- f"{base_url}{path}",
- headers={
- **COPILOT_HEADERS,
- "Authorization": f"Bearer {access}",
- "Content-Type": "application/json",
- },
- json=body,
- stream=wants_stream,
- timeout=120,
- )
- except ProviderError as exc:
- return _json_error(str(exc), status=exc.status, code=exc.code)
- except Exception as exc:
- return _json_error(str(exc), status=502, code="upstream_error")
+def _gemini_api_json_proxy(path: str):
+ from plugins._oauth.helpers.providers.gemini_api import _gemini_headers, safe_api_base_url
- if wants_stream and upstream.ok:
- return _stream_upstream_sse(upstream)
- return _copy_upstream_response(upstream)
+ return _oauth_json_proxy(
+ GEMINI_API_PROVIDER_ID,
+ path,
+ "Google Gemini API OAuth is not connected.",
+ lambda auth: safe_api_base_url(auth.get("base_url")),
+ lambda auth, access: {
+ **_gemini_headers(auth),
+ "Content-Type": "application/json",
+ },
+ require_refresh=True,
+ )
-def _xai_grok_json_proxy(path: str):
+def _oauth_json_proxy(
+ provider_id: str,
+ path: str,
+ not_connected_message: str,
+ base_url_for: Callable[[dict[str, Any]], str],
+ headers_for: Callable[[dict[str, Any], str], dict[str, str]],
+ *,
+ require_refresh: bool = False,
+):
denied = _proxy_denied_response()
if denied:
return denied
@@ -421,16 +422,8 @@ def _xai_grok_json_proxy(path: str):
if not isinstance(body, dict):
return _json_error("Request body must be a JSON object.")
- provider = get_provider(XAI_GROK_PROVIDER_ID)
- ensure_fresh_auth = getattr(provider, "ensure_fresh_auth", None)
- read_auth = getattr(provider, "read_auth", None)
try:
- if callable(ensure_fresh_auth):
- auth = ensure_fresh_auth()
- elif callable(read_auth):
- auth = read_auth()
- else:
- auth = {}
+ auth = _provider_auth(provider_id)
except ProviderError as exc:
return _json_error(str(exc), status=exc.status, code=exc.code)
except Exception as exc:
@@ -438,27 +431,23 @@ def _xai_grok_json_proxy(path: str):
access = str(auth.get("access") or "")
refresh = str(auth.get("refresh") or "")
- if not access or not refresh:
- return _json_error("xAI Grok OAuth is not connected.", status=401, code="not_connected")
-
- from plugins._oauth.helpers.providers.xai_grok import safe_api_base_url
+ if not access or (require_refresh and not refresh):
+ return _json_error(not_connected_message, status=401, code="not_connected")
- base_url = safe_api_base_url(auth.get("base_url"))
wants_stream = body.get("stream") is True
try:
import requests
+ base_url = base_url_for(auth)
upstream = requests.post(
f"{base_url}{path}",
- headers={
- "Accept": "application/json",
- "Authorization": f"Bearer {access}",
- "Content-Type": "application/json",
- },
+ headers=headers_for(auth, access),
json=body,
stream=wants_stream,
timeout=120,
)
+ except ProviderError as exc:
+ return _json_error(str(exc), status=exc.status, code=exc.code)
except Exception as exc:
return _json_error(str(exc), status=502, code="upstream_error")
@@ -467,58 +456,17 @@ def _xai_grok_json_proxy(path: str):
return _copy_upstream_response(upstream)
-def _gemini_api_json_proxy(path: str):
- denied = _proxy_denied_response()
- if denied:
- return denied
-
- body = request.get_json(silent=True)
- if not isinstance(body, dict):
- return _json_error("Request body must be a JSON object.")
-
- provider = get_provider(GEMINI_API_PROVIDER_ID)
+def _provider_auth(provider_id: str) -> dict[str, Any]:
+ provider = get_provider(provider_id)
ensure_fresh_auth = getattr(provider, "ensure_fresh_auth", None)
read_auth = getattr(provider, "read_auth", None)
- try:
- if callable(ensure_fresh_auth):
- auth = ensure_fresh_auth()
- elif callable(read_auth):
- auth = read_auth()
- else:
- auth = {}
- except ProviderError as exc:
- return _json_error(str(exc), status=exc.status, code=exc.code)
- except Exception as exc:
- return _json_error(str(exc), status=502, code="upstream_error")
-
- access = str(auth.get("access") or "")
- refresh = str(auth.get("refresh") or "")
- if not access or not refresh:
- return _json_error("Google Gemini API OAuth is not connected.", status=401, code="not_connected")
-
- from plugins._oauth.helpers.providers.gemini_api import _gemini_headers, safe_api_base_url
-
- base_url = safe_api_base_url(auth.get("base_url"))
- wants_stream = body.get("stream") is True
- try:
- import requests
-
- upstream = requests.post(
- f"{base_url}{path}",
- headers={
- **_gemini_headers(auth),
- "Content-Type": "application/json",
- },
- json=body,
- stream=wants_stream,
- timeout=120,
- )
- except Exception as exc:
- return _json_error(str(exc), status=502, code="upstream_error")
-
- if wants_stream and upstream.ok:
- return _stream_upstream_sse(upstream)
- return _copy_upstream_response(upstream)
+ if callable(ensure_fresh_auth):
+ auth = ensure_fresh_auth()
+ elif callable(read_auth):
+ auth = read_auth()
+ else:
+ auth = {}
+ return auth if isinstance(auth, dict) else {}
def _stream_upstream_sse(upstream):
diff --git a/plugins/_oauth/helpers/usage_plans.py b/plugins/_oauth/helpers/usage_plans.py
index b2957f45a..511e3be21 100644
--- a/plugins/_oauth/helpers/usage_plans.py
+++ b/plugins/_oauth/helpers/usage_plans.py
@@ -102,25 +102,3 @@ USAGE_PLAN_CATALOG: dict[str, dict[str, Any]] = {
def usage_plan_catalog() -> dict[str, dict[str, Any]]:
return deepcopy(USAGE_PLAN_CATALOG)
-
-
-def usage_plan_entry(provider_id: str) -> dict[str, Any]:
- return deepcopy(USAGE_PLAN_CATALOG.get(provider_id, {}))
-
-
-def usage_plans_for(provider_id: str) -> list[dict[str, Any]]:
- entry = usage_plan_entry(provider_id)
- plans = entry.get("plans", [])
- return plans if isinstance(plans, list) else []
-
-
-def usage_plan_notes_for(provider_id: str) -> list[str]:
- entry = usage_plan_entry(provider_id)
- notes = entry.get("notes", [])
- return notes if isinstance(notes, list) else []
-
-
-def usage_plan_sources_for(provider_id: str) -> list[dict[str, str]]:
- entry = usage_plan_entry(provider_id)
- sources = entry.get("sources", [])
- return sources if isinstance(sources, list) else []
diff --git a/plugins/_oauth/webui/config.html b/plugins/_oauth/webui/config.html
index e0975f32c..c6cab4006 100644
--- a/plugins/_oauth/webui/config.html
+++ b/plugins/_oauth/webui/config.html
@@ -181,7 +181,7 @@
<div class="oauth-plan-grid">
<template x-for="entry in $store.oauthConfig.usagePlanEntries()" :key="entry.provider_id">
- <article class="oauth-plan-card" :class="entry.implemented ? 'is-implemented' : 'is-metadata-only'">
+ <article class="oauth-plan-card">
<div class="oauth-plan-head">
<strong x-text="entry.display_name"></strong>
<span x-text="$store.oauthConfig.usagePlanStatus(entry)"></span>
@@ -695,10 +695,6 @@
background: color-mix(in srgb, var(--color-panel) 82%, transparent);
}
- .oauth-plan-card.is-metadata-only {
- border-style: dashed;
- }
-
.oauth-plan-head {
display: flex;
min-width: 0;
diff --git a/plugins/_oauth/webui/oauth-config-store.js b/plugins/_oauth/webui/oauth-config-store.js
index 7fe225879..c00adef10 100644
--- a/plugins/_oauth/webui/oauth-config-store.js
+++ b/plugins/_oauth/webui/oauth-config-store.js
@@ -322,8 +322,8 @@ export const store = createStore("oauthConfig", {
.filter((entry) => entry && Array.isArray(entry.plans) && entry.plans.length);
},
- usagePlanStatus(entry) {
- return entry?.implemented ? "Provider available" : "Metadata only";
+ usagePlanStatus() {
+ return "Provider available";
},
usagePlanNotes(entry) {