Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(keyproxy): foundation — store, token store, vendor table
Ruben Lütke887f23cb402f
diff --git a/keyproxy/__init__.py b/keyproxy/__init__.pynew file mode 100644index 0000000000..1c6d5e9763--- /dev/null+++ b/keyproxy/__init__.py@@ -0,0 +1,20 @@+"""keyproxy — a vendor-aware streaming reverse proxy for LLM API keys.++A small, self-contained FastAPI + httpx + SQLite service that holds real LLM+vendor API keys server-side and lets team clients reach the vendors with a+per-user token instead of the real key. Zero dependency on the ``jarvis``+package; boots on a fresh ``python:3.11-slim`` with only ``fastapi``,+``httpx``, and ``uvicorn``.++Public surface:+ - :func:`keyproxy.app.create_app` — the FastAPI application factory.+ - ``/p/{provider_id}/{path:path}`` — the generic streaming passthrough.+ - ``/admin/tokens`` / ``/admin/usage`` — admin endpoints (bearer-guarded).+ - :mod:`keyproxy.cli` — admin CLI (issue-token, list-tokens, revoke, usage).+"""++from __future__ import annotations++__all__ = ["__version__"]++__version__ = "0.1.0"diff --git a/keyproxy/schema.sql b/keyproxy/schema.sqlnew file mode 100644index 0000000000..16b5d96e0e--- /dev/null+++ b/keyproxy/schema.sql@@ -0,0 +1,31 @@+-- keyproxy schema — per-user tokens + best-effort usage metering.+--+-- Two tables, additive (CREATE TABLE IF NOT EXISTS) so the schema can be+-- re-applied on every boot. Real vendor keys are NEVER stored here; only the+-- SHA-256 of each issued token is persisted (the plaintext is shown once at+-- issue time and then unrecoverable).++CREATE TABLE IF NOT EXISTS tokens (+ id TEXT PRIMARY KEY, -- uuid4+ label TEXT NOT NULL, -- human label, e.g. "alice-laptop"+ token_sha256 TEXT NOT NULL UNIQUE, -- hex sha256 of the plaintext token+ created_at INTEGER NOT NULL, -- unix seconds+ revoked_at INTEGER -- unix seconds; NULL => active+);++CREATE INDEX IF NOT EXISTS idx_tokens_sha256 ON tokens (token_sha256);++CREATE TABLE IF NOT EXISTS usage (+ id TEXT PRIMARY KEY, -- uuid4+ token_id TEXT, -- FK -> tokens.id (NULL if untracked)+ provider_id TEXT NOT NULL, -- wire-contract provider id+ model TEXT, -- model name if parsed, else NULL+ prompt_tokens INTEGER, -- NULL on a parse miss+ completion_tokens INTEGER, -- NULL on a parse miss+ total_tokens INTEGER, -- NULL on a parse miss+ est_cost REAL, -- NULL when model price unknown+ ts INTEGER NOT NULL -- unix seconds+);++CREATE INDEX IF NOT EXISTS idx_usage_token_ts ON usage (token_id, ts);+CREATE INDEX IF NOT EXISTS idx_usage_ts ON usage (ts);diff --git a/keyproxy/store.py b/keyproxy/store.pynew file mode 100644index 0000000000..10c6ed6702--- /dev/null+++ b/keyproxy/store.py@@ -0,0 +1,85 @@+"""SQLite store — open + migrate from ``schema.sql``.++Synchronous ``sqlite3`` (no extra dependency beyond the stdlib). The proxy+opens a single shared connection guarded by a re-entrant lock; the few writes+(token issue/revoke, best-effort usage rows) are short and serialized, which is+the right trade-off for a lean metering store. ``check_same_thread=False`` plus+the lock lets FastAPI's threadpool call the store from worker threads.+"""++from __future__ import annotations++import sqlite3+import threading+from pathlib import Path+from typing import Any++SCHEMA_FILE = Path(__file__).parent / "schema.sql"+++def default_db_path() -> Path:+ """Default DB location — overridable via ``KEYPROXY_DB_PATH``."""+ return Path.home() / ".keyproxy" / "keyproxy.sqlite"+++class Store:+ """A thread-safe SQLite wrapper with an additive migrate-on-open schema."""++ def __init__(self, db_path: str | Path | None = None) -> None:+ if db_path is None or str(db_path) == ":memory:":+ # An in-memory DB must use a single connection for the whole+ # process; ``check_same_thread=False`` keeps it usable from the+ # threadpool while the lock serializes access.+ self._db_path = ":memory:"+ else:+ path = Path(db_path)+ path.parent.mkdir(parents=True, exist_ok=True)+ self._db_path = str(path)+ self._lock = threading.RLock()+ self._conn = sqlite3.connect(+ self._db_path, check_same_thread=False, isolation_level=None+ )+ self._conn.row_factory = sqlite3.Row+ self._conn.execute("PRAGMA journal_mode = WAL")+ self._conn.execute("PRAGMA busy_timeout = 5000")+ self._conn.executescript(SCHEMA_FILE.read_text(encoding="utf-8"))++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------++ def close(self) -> None:+ with self._lock:+ self._conn.close()++ def __enter__(self) -> "Store":+ return self++ def __exit__(self, *_: Any) -> None:+ self.close()++ # ------------------------------------------------------------------+ # Low-level helpers (all guarded by the lock)+ # ------------------------------------------------------------------++ def execute(self, sql: str, params: tuple[Any, ...] = ()) -> sqlite3.Cursor:+ with self._lock:+ return self._conn.execute(sql, params)++ def query_one(+ self, sql: str, params: tuple[Any, ...] = ()+ ) -> sqlite3.Row | None:+ with self._lock:+ cur = self._conn.execute(sql, params)+ row = cur.fetchone()+ cur.close()+ return row++ def query_all(+ self, sql: str, params: tuple[Any, ...] = ()+ ) -> list[sqlite3.Row]:+ with self._lock:+ cur = self._conn.execute(sql, params)+ rows = cur.fetchall()+ cur.close()+ return list(rows)diff --git a/keyproxy/tests/__init__.py b/keyproxy/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/keyproxy/tests/conftest.py b/keyproxy/tests/conftest.pynew file mode 100644index 0000000000..2412540ad7--- /dev/null+++ b/keyproxy/tests/conftest.py@@ -0,0 +1,16 @@+"""Make the repo root importable so ``import keyproxy`` works without install.++keyproxy is a standalone package run directly from the source tree (and from+its own Dockerfile via the working directory). When the tests are invoked as+``py -3.11 -m pytest keyproxy/`` from the repo root, the root is already on+``sys.path``; this conftest makes the suite robust to being run from anywhere.+"""++from __future__ import annotations++import sys+from pathlib import Path++_REPO_ROOT = Path(__file__).resolve().parents[2]+if str(_REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(_REPO_ROOT))diff --git a/keyproxy/tests/test_tokens.py b/keyproxy/tests/test_tokens.pynew file mode 100644index 0000000000..ec0e46300a--- /dev/null+++ b/keyproxy/tests/test_tokens.py@@ -0,0 +1,80 @@+"""Token store: issue / verify / list / revoke, with hashing at rest."""++from __future__ import annotations++import hashlib++import pytest++from keyproxy.store import Store+from keyproxy.tokens import TokenStore+++def tokens() -> TokenStore:+ return TokenStore(Store(":memory:"))+++def test_issue_returns_plaintext_once_and_stores_only_hash(+ tokens: TokenStore,+) -> None:+ issued = tokens.issue("alice-laptop")++ assert issued.plaintext # non-empty plaintext returned once+ assert issued.label == "alice-laptop"+ assert issued.id++ # The plaintext must NOT be stored anywhere — only the sha256 hex.+ rows = tokens.list()+ assert len(rows) == 1+ stored = rows[0]+ assert "token_sha256" in stored+ assert stored["token_sha256"] == hashlib.sha256(+ issued.plaintext.encode("utf-8")+ ).hexdigest()+ # The plaintext string itself is never present in any stored column.+ assert issued.plaintext not in str(dict(stored))+++def test_verify_accepts_valid_returns_token_id(tokens: TokenStore) -> None:+ issued = tokens.issue("alice")+ token_id = tokens.verify(issued.plaintext)+ assert token_id == issued.id+++def test_verify_rejects_unknown_token(tokens: TokenStore) -> None:+ tokens.issue("alice")+ assert tokens.verify("sk-not-a-real-token") is None+++def test_verify_rejects_empty_token(tokens: TokenStore) -> None:+ assert tokens.verify("") is None+ assert tokens.verify(None) is None # type: ignore[arg-type]+++def test_revoked_token_fails_verify(tokens: TokenStore) -> None:+ issued = tokens.issue("alice")+ assert tokens.verify(issued.plaintext) == issued.id++ revoked = tokens.revoke(issued.id)+ assert revoked is True+ assert tokens.verify(issued.plaintext) is None+++def test_revoke_unknown_id_returns_false(tokens: TokenStore) -> None:+ assert tokens.revoke("00000000-0000-0000-0000-000000000000") is False+++def test_list_includes_revoked_with_timestamp(tokens: TokenStore) -> None:+ issued = tokens.issue("alice")+ tokens.revoke(issued.id)+ rows = tokens.list()+ assert len(rows) == 1+ assert rows[0]["revoked_at"] is not None+++def test_each_token_is_unique(tokens: TokenStore) -> None:+ a = tokens.issue("a")+ b = tokens.issue("b")+ assert a.plaintext != b.plaintext+ assert a.id != b.iddiff --git a/keyproxy/tests/test_vendors.py b/keyproxy/tests/test_vendors.pynew file mode 100644index 0000000000..53dc08c443--- /dev/null+++ b/keyproxy/tests/test_vendors.py@@ -0,0 +1,218 @@+"""vendors.py — provider->vendor map + credential extraction/placement + usage."""++from __future__ import annotations++import json++import pytest++from keyproxy import vendors+++# --------------------------------------------------------------------------+# provider_id -> vendor wire contract (must match the client side exactly)+# --------------------------------------------------------------------------++def test_provider_to_vendor_map_is_exact() -> None:+ assert vendors.PROVIDER_VENDORS == {+ "claude-api": ("anthropic", "https://api.anthropic.com"),+ "openai": ("openai_compatible", "https://api.openai.com/v1"),+ "openrouter": ("openai_compatible", "https://openrouter.ai/api/v1"),+ "grok": ("openai_compatible", "https://api.x.ai/v1"),+ "gemini": ("gemini", "https://generativelanguage.googleapis.com"),+ "groq-api": ("openai_compatible", "https://api.groq.com/openai/v1"),+ }+++def test_resolve_provider_known() -> None:+ vendor, base = vendors.resolve_provider("openrouter")+ assert vendor == "openai_compatible"+ assert base == "https://openrouter.ai/api/v1"+++def test_resolve_provider_unknown_returns_none() -> None:+ assert vendors.resolve_provider("does-not-exist") is None+++# --------------------------------------------------------------------------+# inbound credential extraction+# --------------------------------------------------------------------------++def test_extract_openai_compatible_bearer() -> None:+ headers = {"authorization": "Bearer kp_inbound_token"}+ token = vendors.extract_inbound_token(+ "openai_compatible", headers, query={}+ )+ assert token == "kp_inbound_token"+++def test_extract_openai_compatible_missing() -> None:+ assert (+ vendors.extract_inbound_token("openai_compatible", {}, query={}) is None+ )+++def test_extract_anthropic_x_api_key() -> None:+ headers = {"x-api-key": "kp_inbound_token"}+ token = vendors.extract_inbound_token("anthropic", headers, query={})+ assert token == "kp_inbound_token"+++def test_extract_gemini_header() -> None:+ headers = {"x-goog-api-key": "kp_inbound_token"}+ token = vendors.extract_inbound_token("gemini", headers, query={})+ assert token == "kp_inbound_token"+++def test_extract_gemini_query_key() -> None:+ token = vendors.extract_inbound_token(+ "gemini", {}, query={"key": "kp_inbound_token"}+ )+ assert token == "kp_inbound_token"+++def test_extract_gemini_header_wins_over_query() -> None:+ token = vendors.extract_inbound_token(+ "gemini",+ {"x-goog-api-key": "from_header"},+ query={"key": "from_query"},+ )+ assert token == "from_header"+++# --------------------------------------------------------------------------+# outbound credential placement (the real key goes in the right slot, the+# inbound token is gone)+# --------------------------------------------------------------------------++def test_place_openai_compatible_sets_bearer() -> None:+ headers, query = vendors.place_outbound_credential(+ "openai_compatible",+ headers={"content-type": "application/json"},+ query={},+ real_key="sk-REAL-KEY",+ )+ assert headers["authorization"] == "Bearer sk-REAL-KEY"+ assert headers["content-type"] == "application/json"+ assert "key" not in query+++def test_place_anthropic_sets_x_api_key() -> None:+ headers, _query = vendors.place_outbound_credential(+ "anthropic", headers={}, query={}, real_key="sk-ant-REAL"+ )+ assert headers["x-api-key"] == "sk-ant-REAL"+ assert "authorization" not in headers+++def test_place_gemini_sets_header_and_strips_query_key() -> None:+ headers, query = vendors.place_outbound_credential(+ "gemini",+ headers={},+ query={"key": "inbound", "alt": "sse"},+ real_key="REAL-GEMINI",+ )+ assert headers["x-goog-api-key"] == "REAL-GEMINI"+ # The inbound ?key= must be removed so the proxy token never reaches Google.+ assert "key" not in query+ assert query["alt"] == "sse"+++# --------------------------------------------------------------------------+# usage parsing per vendor+# --------------------------------------------------------------------------++def test_parse_usage_openai_json() -> None:+ body = json.dumps(+ {+ "model": "gpt-4o-mini",+ "usage": {+ "prompt_tokens": 11,+ "completion_tokens": 22,+ "total_tokens": 33,+ },+ }+ ).encode()+ u = vendors.parse_usage("openai_compatible", body)+ assert u is not None+ assert u.model == "gpt-4o-mini"+ assert u.prompt_tokens == 11+ assert u.completion_tokens == 22+ assert u.total_tokens == 33+++def test_parse_usage_openai_sse_with_final_usage_chunk() -> None:+ body = (+ b'data: {"model":"gpt-4o-mini","choices":[{"delta":{"content":"hi"}}]}\n\n'+ b'data: {"model":"gpt-4o-mini","usage":{"prompt_tokens":5,'+ b'"completion_tokens":7,"total_tokens":12}}\n\n'+ b"data: [DONE]\n\n"+ )+ u = vendors.parse_usage("openai_compatible", body)+ assert u is not None+ assert u.prompt_tokens == 5+ assert u.completion_tokens == 7+ assert u.total_tokens == 12+ assert u.model == "gpt-4o-mini"+++def test_parse_usage_anthropic_stream() -> None:+ body = (+ b'event: message_start\n'+ b'data: {"type":"message_start","message":{"model":"claude-3-5-sonnet",'+ b'"usage":{"input_tokens":40,"output_tokens":1}}}\n\n'+ b'event: message_delta\n'+ b'data: {"type":"message_delta","usage":{"output_tokens":99}}\n\n'+ )+ u = vendors.parse_usage("anthropic", body)+ assert u is not None+ assert u.prompt_tokens == 40+ # output_tokens from the final message_delta wins (cumulative final count).+ assert u.completion_tokens == 99+ assert u.total_tokens == 139+ assert u.model == "claude-3-5-sonnet"+++def test_parse_usage_anthropic_non_stream_json() -> None:+ body = json.dumps(+ {+ "model": "claude-3-5-haiku",+ "usage": {"input_tokens": 10, "output_tokens": 20},+ }+ ).encode()+ u = vendors.parse_usage("anthropic", body)+ assert u is not None+ assert u.prompt_tokens == 10+ assert u.completion_tokens == 20+ assert u.total_tokens == 30+++def test_parse_usage_gemini_usage_metadata() -> None:+ body = json.dumps(+ {+ "usageMetadata": {+ "promptTokenCount": 8,+ "candidatesTokenCount": 16,+ "totalTokenCount": 24,+ },+ "modelVersion": "gemini-2.0-flash",+ }+ ).encode()+ u = vendors.parse_usage("gemini", body)+ assert u is not None+ assert u.prompt_tokens == 8+ assert u.completion_tokens == 16+ assert u.total_tokens == 24+ assert u.model == "gemini-2.0-flash"+++def test_parse_usage_miss_returns_none() -> None:+ assert vendors.parse_usage("openai_compatible", b"not json at all") is None+ assert vendors.parse_usage("anthropic", b"") is None+ assert vendors.parse_usage("gemini", b'{"no":"usage"}') is None+++def test_parse_usage_never_raises_on_garbage() -> None:+ # Best-effort: a parse miss is a None, never an exception.+ for vendor in ("openai_compatible", "anthropic", "gemini"):+ assert vendors.parse_usage(vendor, b"\x00\xff\x00") is Nonediff --git a/keyproxy/tokens.py b/keyproxy/tokens.pynew file mode 100644index 0000000000..d412850c8a--- /dev/null+++ b/keyproxy/tokens.py@@ -0,0 +1,118 @@+"""Per-user token store: issue / verify / list / revoke.++Security contract (§6):+ - The plaintext token is returned exactly once, at issue time. Only the+ SHA-256 hex of the plaintext is persisted; the plaintext is unrecoverable+ afterwards.+ - :meth:`TokenStore.verify` compares with :func:`hmac.compare_digest`+ (constant-time) and fails closed for missing / unknown / revoked tokens.+ - Revocation is instant: a revoked token's ``revoked_at`` is set and every+ subsequent :meth:`verify` returns ``None``.+"""++from __future__ import annotations++import hashlib+import hmac+import secrets+import time+from dataclasses import dataclass+from uuid import uuid4++from .store import Store++# Issued plaintext tokens carry a recognizable, non-secret prefix so they can+# be spotted in client config; the entropy lives in the random suffix.+_TOKEN_PREFIX = "kp_"+_TOKEN_ENTROPY_BYTES = 32 # 256 bits+++def _sha256_hex(value: str) -> str:+ return hashlib.sha256(value.encode("utf-8")).hexdigest()+++@dataclass(frozen=True)+class IssuedToken:+ """The one-time result of issuing a token."""++ id: str+ label: str+ plaintext: str+++class TokenStore:+ def __init__(self, store: Store) -> None:+ self._store = store++ # ------------------------------------------------------------------+ # Issue+ # ------------------------------------------------------------------++ def issue(self, label: str) -> IssuedToken:+ """Create a new token; return its plaintext exactly once."""+ token_id = str(uuid4())+ plaintext = _TOKEN_PREFIX + secrets.token_urlsafe(_TOKEN_ENTROPY_BYTES)+ self._store.execute(+ "INSERT INTO tokens (id, label, token_sha256, created_at, "+ "revoked_at) VALUES (?, ?, ?, ?, NULL)",+ (token_id, label, _sha256_hex(plaintext), int(time.time())),+ )+ return IssuedToken(id=token_id, label=label, plaintext=plaintext)++ # ------------------------------------------------------------------+ # Verify (constant-time, fail-closed)+ # ------------------------------------------------------------------++ def verify(self, plaintext: str | None) -> str | None:+ """Return the token id for a valid, non-revoked token, else ``None``.++ Constant-time comparison on the SHA-256 hex. Looks the candidate up by+ its hash (an indexed equality match) and then constant-time-compares to+ guard against any storage-layer timing leak.+ """+ if not plaintext:+ return None+ candidate_hash = _sha256_hex(plaintext)+ row = self._store.query_one(+ "SELECT id, token_sha256, revoked_at FROM tokens "+ "WHERE token_sha256 = ?",+ (candidate_hash,),+ )+ if row is None:+ return None+ if not hmac.compare_digest(str(row["token_sha256"]), candidate_hash):+ return None+ if row["revoked_at"] is not None:+ return None+ return str(row["id"])++ # ------------------------------------------------------------------+ # List / revoke+ # ------------------------------------------------------------------++ def list(self) -> list[dict[str, object]]:+ """All tokens (active and revoked), newest first. No plaintext."""+ rows = self._store.query_all(+ "SELECT id, label, token_sha256, created_at, revoked_at "+ "FROM tokens ORDER BY created_at DESC, id DESC"+ )+ return [dict(r) for r in rows]++ def revoke(self, token_id: str) -> bool:+ """Revoke a token by id. Returns ``False`` if the id is unknown.++ Idempotent: re-revoking an already-revoked token returns ``True``+ (it remains revoked) but does not move the timestamp.+ """+ cur = self._store.execute(+ "UPDATE tokens SET revoked_at = ? "+ "WHERE id = ? AND revoked_at IS NULL",+ (int(time.time()), token_id),+ )+ if cur.rowcount > 0:+ return True+ # Either unknown id, or already revoked — distinguish the two.+ exists = self._store.query_one(+ "SELECT 1 FROM tokens WHERE id = ?", (token_id,)+ )+ return exists is not Nonediff --git a/keyproxy/vendors.py b/keyproxy/vendors.pynew file mode 100644index 0000000000..35b6436d09--- /dev/null+++ b/keyproxy/vendors.py@@ -0,0 +1,274 @@+"""The ONLY per-vendor knowledge in the proxy.++Three concerns live here and nowhere else:++1. ``PROVIDER_VENDORS`` — the ``provider_id -> (vendor, default_base_url)``+ map. This is the wire contract shared with the client; it gets the+ anti-drift parity treatment (see ``tests/test_parity.py``).+2. Credential rules per *vendor* — how to read the inbound per-user token from+ the request, and how to place the real vendor key on the outbound request.+3. Usage parsing per *vendor* — best-effort token-count extraction from a+ buffered response body (JSON or SSE). A parse miss returns ``None`` and+ never raises.++Adding a provider that uses an existing vendor is a one-line edit to+``PROVIDER_VENDORS``. Adding a genuinely new vendor wire shape touches the three+dispatch tables below.+"""++from __future__ import annotations++import json+from dataclasses import dataclass++# --------------------------------------------------------------------------+# provider_id -> (vendor, default real base url) — THE WIRE CONTRACT+# --------------------------------------------------------------------------++PROVIDER_VENDORS: dict[str, tuple[str, str]] = {+ "claude-api": ("anthropic", "https://api.anthropic.com"),+ "openai": ("openai_compatible", "https://api.openai.com/v1"),+ "openrouter": ("openai_compatible", "https://openrouter.ai/api/v1"),+ "grok": ("openai_compatible", "https://api.x.ai/v1"),+ "gemini": ("gemini", "https://generativelanguage.googleapis.com"),+ "groq-api": ("openai_compatible", "https://api.groq.com/openai/v1"),+}++# The set of vendors the credential / usage dispatch tables understand.+KNOWN_VENDORS: frozenset[str] = frozenset(+ {"openai_compatible", "anthropic", "gemini"}+)+++def resolve_provider(provider_id: str) -> tuple[str, str] | None:+ """``provider_id -> (vendor, default_base_url)`` or ``None`` if unknown."""+ return PROVIDER_VENDORS.get(provider_id)+++# --------------------------------------------------------------------------+# inbound credential extraction (read the per-user token off the request)+# --------------------------------------------------------------------------+++def _bearer(value: str | None) -> str | None:+ if not value:+ return None+ prefix = "bearer "+ if value.lower().startswith(prefix):+ return value[len(prefix):].strip() or None+ # Some clients send the raw token in Authorization without the scheme.+ return value.strip() or None+++def extract_inbound_token(+ vendor: str,+ headers: dict[str, str],+ *,+ query: dict[str, str],+) -> str | None:+ """Read the inbound per-user token per the vendor's credential rule.++ ``headers`` keys are treated case-insensitively by the caller (it lowercases+ them); this function assumes lowercase keys.+ """+ if vendor == "openai_compatible":+ return _bearer(headers.get("authorization"))+ if vendor == "anthropic":+ return (headers.get("x-api-key") or "").strip() or None+ if vendor == "gemini":+ header = (headers.get("x-goog-api-key") or "").strip()+ if header:+ return header+ return (query.get("key") or "").strip() or None+ return None+++# --------------------------------------------------------------------------+# outbound credential placement (set the real vendor key, drop the inbound one)+# --------------------------------------------------------------------------+++def place_outbound_credential(+ vendor: str,+ *,+ headers: dict[str, str],+ query: dict[str, str],+ real_key: str,+) -> tuple[dict[str, str], dict[str, str]]:+ """Return (headers, query) with the real vendor credential set in place.++ The caller has already stripped all inbound auth headers (header hygiene);+ this only *sets* the real credential. ``headers`` / ``query`` are mutated+ and also returned for convenience.+ """+ if vendor == "openai_compatible":+ headers["authorization"] = f"Bearer {real_key}"+ elif vendor == "anthropic":+ headers["x-api-key"] = real_key+ elif vendor == "gemini":+ headers["x-goog-api-key"] = real_key+ # Never forward an inbound ?key= (the proxy token) to the vendor.+ query.pop("key", None)+ return headers, query+++# --------------------------------------------------------------------------+# usage parsing (best-effort)+# --------------------------------------------------------------------------+++@dataclass(frozen=True)+class ParsedUsage:+ model: str | None+ prompt_tokens: int | None+ completion_tokens: int | None+ total_tokens: int | None+++def _iter_sse_data_objects(body: bytes) -> list[dict]:+ """Yield JSON objects from SSE ``data:`` lines; ignore non-JSON lines."""+ objects: list[dict] = []+ try:+ text = body.decode("utf-8", errors="strict")+ except UnicodeDecodeError:+ return objects+ for raw_line in text.splitlines():+ line = raw_line.strip()+ if not line.startswith("data:"):+ continue+ payload = line[len("data:"):].strip()+ if not payload or payload == "[DONE]":+ continue+ try:+ obj = json.loads(payload)+ except (json.JSONDecodeError, ValueError):+ continue+ if isinstance(obj, dict):+ objects.append(obj)+ return objects+++def _try_whole_json(body: bytes) -> dict | None:+ try:+ obj = json.loads(body.decode("utf-8", errors="strict"))+ except (UnicodeDecodeError, json.JSONDecodeError, ValueError):+ return None+ return obj if isinstance(obj, dict) else None+++def _parse_openai_usage(body: bytes) -> ParsedUsage | None:+ candidates: list[dict] = []+ whole = _try_whole_json(body)+ if whole is not None:+ candidates.append(whole)+ candidates.extend(_iter_sse_data_objects(body))++ model: str | None = None+ usage: dict | None = None+ for obj in candidates:+ if isinstance(obj.get("model"), str):+ model = obj["model"]+ if isinstance(obj.get("usage"), dict):+ usage = obj["usage"]+ if usage is None:+ return None+ return ParsedUsage(+ model=model,+ prompt_tokens=_as_int(usage.get("prompt_tokens")),+ completion_tokens=_as_int(usage.get("completion_tokens")),+ total_tokens=_as_int(usage.get("total_tokens")),+ )+++def _parse_anthropic_usage(body: bytes) -> ParsedUsage | None:+ model: str | None = None+ input_tokens: int | None = None+ output_tokens: int | None = None++ def absorb(obj: dict) -> None:+ nonlocal model, input_tokens, output_tokens+ msg = obj.get("message")+ if isinstance(msg, dict):+ if isinstance(msg.get("model"), str):+ model = msg["model"]+ mu = msg.get("usage")+ if isinstance(mu, dict):+ if (v := _as_int(mu.get("input_tokens"))) is not None:+ input_tokens = v+ if (v := _as_int(mu.get("output_tokens"))) is not None:+ output_tokens = v+ if isinstance(obj.get("model"), str):+ model = obj["model"]+ u = obj.get("usage")+ if isinstance(u, dict):+ if (v := _as_int(u.get("input_tokens"))) is not None:+ input_tokens = v+ # message_delta carries the final cumulative output count.+ if (v := _as_int(u.get("output_tokens"))) is not None:+ output_tokens = v++ whole = _try_whole_json(body)+ if whole is not None:+ absorb(whole)+ for obj in _iter_sse_data_objects(body):+ absorb(obj)++ if input_tokens is None and output_tokens is None:+ return None+ total = None+ if input_tokens is not None and output_tokens is not None:+ total = input_tokens + output_tokens+ return ParsedUsage(+ model=model,+ prompt_tokens=input_tokens,+ completion_tokens=output_tokens,+ total_tokens=total,+ )+++def _parse_gemini_usage(body: bytes) -> ParsedUsage | None:+ candidates: list[dict] = []+ whole = _try_whole_json(body)+ if whole is not None:+ candidates.append(whole)+ candidates.extend(_iter_sse_data_objects(body))++ model: str | None = None+ meta: dict | None = None+ for obj in candidates:+ if isinstance(obj.get("modelVersion"), str):+ model = obj["modelVersion"]+ if isinstance(obj.get("usageMetadata"), dict):+ meta = obj["usageMetadata"]+ if meta is None:+ return None+ return ParsedUsage(+ model=model,+ prompt_tokens=_as_int(meta.get("promptTokenCount")),+ completion_tokens=_as_int(meta.get("candidatesTokenCount")),+ total_tokens=_as_int(meta.get("totalTokenCount")),+ )+++def parse_usage(vendor: str, body: bytes) -> ParsedUsage | None:+ """Best-effort usage parse for a buffered body; never raises."""+ try:+ if vendor == "openai_compatible":+ return _parse_openai_usage(body)+ if vendor == "anthropic":+ return _parse_anthropic_usage(body)+ if vendor == "gemini":+ return _parse_gemini_usage(body)+ except Exception: # noqa: BLE001 — metering must never fail the request+ return None+ return None+++def _as_int(value: object) -> int | None:+ if isinstance(value, bool):+ return None+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ return int(value)+ return None