Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

feat(gen): every provider call reads its address from SPRITE_GEN_<PROVIDER>_BASE_URL at the request, URLs a provider hands back are fetched through it, and SPRITE_GEN_LOGINS=off runs every call on its API key

Soohong Kim055b496f3679
diff --git a/sprite_gen/audio/provider.py b/sprite_gen/audio/provider.py
index 4019b21..2b4e55b 100644
--- a/sprite_gen/audio/provider.py
+++ b/sprite_gen/audio/provider.py
@@ -8,11 +8,10 @@ import re
from urllib.error import HTTPError
from urllib.request import Request, urlopen
-from sprite_gen.gen import retry
+from sprite_gen.gen import address, retry
from sprite_gen.gen.base import announce_api_billing, env_api_key
from sprite_gen.gen.xai import error_body, NO_ANSWER
-BASE = 'https://api.elevenlabs.io/v1'
AUTH_ENV = 'ELEVENLABS_API_KEY'
FORMAT = 'mp3_44100_128'
SAFE_CODES = frozenset({'system_busy', 'too_many_concurrent_requests', 'quota_exceeded',
@@ -58,7 +57,7 @@ def _code(body):
def generate(document):
key = credential()
- req = Request(f"{BASE}/{document['endpoint']}?output_format={document['output_format']}",
+ req = Request(address.url('elevenlabs', f"/{document['endpoint']}?output_format={document['output_format']}"),
data=json.dumps(document['body']).encode(),
headers={'xi-api-key': key, 'Content-Type': 'application/json'}, method='POST')
diff --git a/sprite_gen/gen/address.py b/sprite_gen/gen/address.py
new file mode 100644
index 0000000..4412703
--- /dev/null
+++ b/sprite_gen/gen/address.py
@@ -0,0 +1,76 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Where each provider sprite-gen calls is: its address, read from the environment at every call.
+
+sprite-gen calls four providers over HTTP itself, with no SDK: OpenAI, xAI, Anthropic and ElevenLabs. Each has one
+base address, the documented API root with its version path, and one environment variable that replaces it,
+`SPRITE_GEN_<PROVIDER>_BASE_URL`. Unset, empty or blank is the documented address, so nothing changes for anyone who
+sets none. The variable is read when a request is made, never at import, so a process that sets it after importing
+the engine is followed. Any other value must be an http:// or https:// address with no query or fragment, or the
+call is refused naming the variable.
+
+A URL a provider hands back to be fetched (a finished clip from xAI, a Message Batch's results file from Anthropic)
+points at the provider's own hosts. With the provider's variable set it is fetched through the same base:
+`GET <base>/sprite-gen/fetch?url=<the URL, percent-encoded>`, with the headers it would have carried, so a relay
+that forwards the provider's API forwards it too. Without the variable it is fetched where it points, as before.
+
+Every direct provider call builds its URL here (docs/gen.md "Provider addresses" lists them):
+`openai_provider` (images, vision), `xai` callers `grok_provider` (images), `facing_vision.grok_inspect` (vision)
+and `video` (generations, extensions, edits, polls, the clip's download), `anthropic_api` (messages, batches, the
+results file) and `sprite_gen.audio.provider` (sound). The subscription logins (`codex`, `claude`) are the binaries'
+own network and do not read these variables; `SPRITE_GEN_LOGINS=off` turns them off (`base.logins_on`).
+"""
+from __future__ import annotations
+
+import os
+import urllib.parse
+from dataclasses import dataclass
+from typing import Mapping
+
+
+@dataclass(frozen=True)
+class Provider:
+ name: str
+ env: str # the variable that replaces `default`
+ default: str # the documented API root, version path included
+
+
+PROVIDERS = {provider.name: provider for provider in (
+ Provider("openai", "SPRITE_GEN_OPENAI_BASE_URL", "https://api.openai.com/v1"),
+ Provider("xai", "SPRITE_GEN_XAI_BASE_URL", "https://api.x.ai/v1"),
+ Provider("anthropic", "SPRITE_GEN_ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"),
+ Provider("elevenlabs", "SPRITE_GEN_ELEVENLABS_BASE_URL", "https://api.elevenlabs.io/v1"),
+)}
+FETCH_PATH = "/sprite-gen/fetch"
+
+
+def _named(provider: str, env: Mapping[str, str] | None) -> str | None:
+ """The base the variable names, trailing slash dropped, or None where it is unset or blank."""
+ variable = PROVIDERS[provider].env
+ named = ((os.environ if env is None else env).get(variable) or "").strip()
+ if not named:
+ return None
+ split = urllib.parse.urlsplit(named)
+ if split.scheme not in ("http", "https") or not split.hostname or split.query or split.fragment:
+ raise SystemExit(f"{variable}={named!r}: name an http:// or https:// address with no query or fragment "
+ f"(the provider's API root, version path included: {PROVIDERS[provider].default}), "
+ "or leave it unset")
+ return named.rstrip("/")
+
+
+def base(provider: str, *, env: Mapping[str, str] | None = None) -> str:
+ """The base address `provider`'s calls go to now: its variable, or the documented address."""
+ return _named(provider, env) or PROVIDERS[provider].default
+
+
+def url(provider: str, path: str, *, env: Mapping[str, str] | None = None) -> str:
+ """The URL of `path` (from `/`, query included) on `provider`'s base."""
+ return base(provider, env=env) + path
+
+
+def fetched(provider: str, returned: str, *, env: Mapping[str, str] | None = None) -> str:
+ """Where to fetch `returned`, a URL `provider` handed back: through the variable's base when it is set, else as
+ it is."""
+ named = _named(provider, env)
+ if named is None:
+ return returned
+ return f"{named}{FETCH_PATH}?url={urllib.parse.quote(returned, safe='')}"
diff --git a/sprite_gen/gen/anthropic_api.py b/sprite_gen/gen/anthropic_api.py
index 30bcbc2..3f4e6b6 100644
--- a/sprite_gen/gen/anthropic_api.py
+++ b/sprite_gen/gen/anthropic_api.py
@@ -43,10 +43,9 @@ import urllib.request
from dataclasses import dataclass
from typing import Any, Callable
-from . import refusal, retry
+from . import address, refusal, retry
from .xai import NO_ANSWER, error_body, no_answer_reason
-API_BASE = "https://api.anthropic.com/v1"
API_VERSION = "2023-06-01"
AUTH_ENV = "ANTHROPIC_API_KEY"
MODEL = "claude-opus-5-5"
@@ -259,7 +258,8 @@ def stream_message(token: str, body: dict[str, Any], *, sleep: Sleep = time.slee
data = json.dumps({**body, "stream": True}).encode("utf-8")
timeout = READ_TIMEOUT_SECONDS if timeout is None else timeout
started = time.monotonic()
- response = _open(lambda: _request("POST", API_BASE + "/messages", token, data, accept="text/event-stream"),
+ response = _open(lambda: _request("POST", address.url("anthropic", "/messages"), token, data,
+ accept="text/event-stream"),
token, timeout=timeout, sleep=sleep, label=label)
request_id = response.headers.get("request-id")
state = _Stream()
@@ -321,7 +321,7 @@ def submit_batch(token: str, requests: list[tuple[str, dict[str, Any]]], *, slee
label: str = "pixel-draw") -> dict[str, Any]:
"""Create one Message Batch of `(custom_id, params)` and return the batch object."""
body = {"requests": [{"custom_id": custom_id, "params": params} for custom_id, params in requests]}
- batch = _json_call("POST", API_BASE + "/messages/batches", token, body, sleep=sleep, label=label)
+ batch = _json_call("POST", address.url("anthropic", "/messages/batches"), token, body, sleep=sleep, label=label)
if not isinstance(batch, dict) or not isinstance(batch.get("id"), str):
raise ApiError("pixel-draw: the batch answer names no batch id")
return batch
@@ -330,8 +330,8 @@ def submit_batch(token: str, requests: list[tuple[str, dict[str, Any]]], *, slee
def get_batch(token: str, batch_id: str, *, sleep: Sleep = time.sleep, label: str = "pixel-draw",
deadline: float | None = None) -> dict[str, Any]:
"""The batch object; a refused read is asked again within `deadline` (the wait for the batch)."""
- batch = _json_call("GET", f"{API_BASE}/messages/batches/{batch_id}", token, None, sleep=sleep, label=label,
- deadline=deadline)
+ batch = _json_call("GET", address.url("anthropic", f"/messages/batches/{batch_id}"), token, None, sleep=sleep,
+ label=label, deadline=deadline)
if not isinstance(batch, dict):
raise ApiError("pixel-draw: the batch status answer is not an object")
return batch
@@ -360,6 +360,8 @@ def batch_results(token: str, batch: dict[str, Any], *, sleep: Sleep = time.slee
url = batch.get("results_url")
if not isinstance(url, str) or not url:
raise ApiError(f"pixel-draw: batch {batch.get('id')} has ended but names no results_url")
+ # Anthropic's own host: through the Anthropic base when SPRITE_GEN_ANTHROPIC_BASE_URL is set (`address.fetched`).
+ url = address.fetched("anthropic", url)
response = _open(lambda: _request("GET", url, token, None, accept="application/binary"),
token, timeout=120.0, sleep=sleep, label=label, method="GET", deadline=deadline)
try:
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
index cbfafbe..c88ea1d 100644
--- a/sprite_gen/gen/base.py
+++ b/sprite_gen/gen/base.py
@@ -111,6 +111,23 @@ def env_api_key(name: str, env: Mapping[str, str] | None = None, *, who: str, al
return None
+# Whether a subscription login may be read (docs/gen.md "Subscription logins off"): `on` where unset or empty, the
+# order every provider keeps (the login first, the key only without one); `off` reads none of them — the grok login
+# file, `codex login status`, `claude auth status` — so every call runs on its API key, as in a container that holds a
+# key and no login. Anything else is refused, not read as either.
+LOGINS_ENV = "SPRITE_GEN_LOGINS"
+LOGINS_OFF = f"subscription logins are off here ({LOGINS_ENV}=off)"
+
+
+def logins_on(env: Mapping[str, str] | None = None) -> bool:
+ """Whether a subscription login may be read here (`LOGINS_ENV`, in `env`, default `os.environ`)."""
+ named = (os.environ if env is None else env).get(LOGINS_ENV) or "on"
+ if named not in ("on", "off"):
+ raise SystemExit(f"{LOGINS_ENV}={named!r}: name off (every provider call on its API key, no subscription "
+ "login read) or on (the default), or leave it unset")
+ return named == "on"
+
+
def provider_binary(name: str) -> str:
"""Resolve a provider CLI through PATH, including Windows PATHEXT shims.
diff --git a/sprite_gen/gen/claude_login.py b/sprite_gen/gen/claude_login.py
index 6e66e7a..feaf618 100644
--- a/sprite_gen/gen/claude_login.py
+++ b/sprite_gen/gen/claude_login.py
@@ -47,7 +47,7 @@ from dataclasses import dataclass, field
from typing import Any, Callable, Mapping
from . import anthropic_api as api
-from .base import env_api_key, provider_binary, provider_subprocess_env
+from .base import LOGINS_ENV, env_api_key, logins_on, provider_binary, provider_subprocess_env
BINARY = "claude"
AUTH_SOURCE_LOGIN = "claude-login"
@@ -119,15 +119,21 @@ def login(env: Mapping[str, str] | None = None, *, run: Run = subprocess.run) ->
def resolve_credential(*, batch: bool = False, env: Mapping[str, str] | None = None,
run: Run = subprocess.run) -> Credential:
- """The subscription login first; `ANTHROPIC_API_KEY` only when no login is here, or for a Message
- Batch, which only the API runs. Neither is a refusal naming both."""
- if not batch:
+ """The subscription login first; `ANTHROPIC_API_KEY` only when no login is here, for a Message Batch, which
+ only the API runs, or with SPRITE_GEN_LOGINS=off, which asks the binary nothing. Neither is a refusal naming
+ both."""
+ asks = not batch and logins_on(env)
+ if asks:
found = login(env, run=run)
if found is not None:
return Credential(AUTH_SOURCE_LOGIN, login=found)
key = env_api_key(api.AUTH_ENV, env, who="pixel-draw")
if key:
return Credential(AUTH_SOURCE_API_KEY, token=key)
+ if not batch and not asks:
+ raise SystemExit(f"pixel-draw: no Claude credential — {LOGINS_ENV}=off reads no subscription login and "
+ f"{api.AUTH_ENV} is not set.\n export {api.AUTH_ENV}=<your Claude Console API key> "
+ f"(platform.claude.com/settings/keys), or unset {LOGINS_ENV} to draw on your Claude subscription.")
if batch:
raise SystemExit(f"pixel-draw: --batch is Anthropic's Message Batches API, which runs on {api.AUTH_ENV} "
f"only, and it is not set.\n export {api.AUTH_ENV}=<your Claude Console API key>, or "
diff --git a/sprite_gen/gen/codex_provider.py b/sprite_gen/gen/codex_provider.py
index ed7b4ef..42c8a42 100644
--- a/sprite_gen/gen/codex_provider.py
+++ b/sprite_gen/gen/codex_provider.py
@@ -36,11 +36,13 @@ from pathlib import Path
from .base import (
GEN_TIMEOUT_SECONDS,
+ LOGINS_OFF,
TRANSPARENCY_NATIVE,
announce_api_billing,
GenRequest,
GenTimeoutError,
ProviderRun,
+ logins_on,
provider_binary,
provider_subprocess_env,
verify_png,
@@ -99,7 +101,10 @@ def codex_login() -> CodexLogin:
"""How `codex` is signed in here, by `codex login status`: exit 0 and "ChatGPT" in what it
says is the subscription; exit 0 otherwise is signed in with an API key. No CLI, a probe that
fails or does not answer, and a non-zero exit are not usable, with the reason. What the CLI
- says is never repeated: an API-key login can name its key."""
+ says is never repeated: an API-key login can name its key. With SPRITE_GEN_LOGINS=off codex is
+ not asked and is not usable: its login is all it runs on."""
+ if not logins_on():
+ return CodexLogin(None, LOGINS_OFF)
binary = provider_binary("codex")
try:
completed = subprocess.run([binary, "login", "status"], capture_output=True, text=True, encoding="utf-8",
@@ -398,6 +403,9 @@ class CodexProvider:
f"codex-gen: {flag} is not carried into codex image_gen; "
"drop it or use --provider openai"
)
+ if not logins_on():
+ raise SystemExit(f"codex-gen: {LOGINS_OFF}; codex runs on its own login only — "
+ "name --provider openai or grok, which run on an API key")
codex_home = _resolve_codex_home()
if not codex_home.is_dir():
raise SystemExit(
diff --git a/sprite_gen/gen/facing_vision.py b/sprite_gen/gen/facing_vision.py
index 4fbc486..2e71ce7 100644
--- a/sprite_gen/gen/facing_vision.py
+++ b/sprite_gen/gen/facing_vision.py
@@ -84,7 +84,7 @@ def codex_inspect(path: Path, workdir: Path, *, prompt: str = INSPECTION_PROMPT,
def grok_inspect(path: Path, *, credential=None, call=None, prompt: str = INSPECTION_PROMPT,
detail: str = "low", label: str = FACING_LABEL) -> tuple[str, dict]:
- from . import xai
+ from . import address, xai
from .base import announce_api_billing
credential = credential or xai.resolve_credential()
if credential.source == xai.AUTH_SOURCE_API_KEY:
@@ -92,7 +92,7 @@ def grok_inspect(path: Path, *, credential=None, call=None, prompt: str = INSPEC
# The question's time limit is the transport's read timeout, from its first send: the waits before a
# refused one goes again count in it (`retry`), and each send reads only what is left of it.
send, deadline = call or xai.http_json, time.monotonic() + xai.HTTP_TIMEOUT_SECONDS
- status, reply, _sends = xai.post(lambda *a: send(*a, deadline=deadline), xai.API_BASE + "/responses",
+ status, reply, _sends = xai.post(lambda *a: send(*a, deadline=deadline), address.url("xai", "/responses"),
credential.token, request_body(path, GROK_MODEL, prompt=prompt, detail=detail),
who="grok", label=_tag(label), deadline=deadline)
text, metadata = response_text(status, reply, label=label)
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
index cbfb99e..f49f1da 100644
--- a/sprite_gen/gen/grok_provider.py
+++ b/sprite_gen/gen/grok_provider.py
@@ -17,7 +17,7 @@ from pathlib import Path
from PIL import Image, UnidentifiedImageError
-from . import refusal, retry, xai
+from . import address, refusal, retry, xai
from .base import (
GEN_TIMEOUT_SECONDS,
RESOLUTIONS,
@@ -149,7 +149,7 @@ class GrokProvider:
# refused request goes again count in it (`retry`), and each send reads only what is left of it.
deadline = started + GEN_TIMEOUT_SECONDS
status, reply, sends = xai.post(lambda *a: xai.http_json(*a, timeout=GEN_TIMEOUT_SECONDS, deadline=deadline),
- xai.API_BASE + endpoint, credential.token, body, who="grok", label="gen",
+ address.url("xai", endpoint), credential.token, body, who="grok", label="gen",
deadline=deadline)
# The provider's code goes in front, format-checked; the body it sent goes
# last, as received, with keys and URL query strings masked (refusal.said).
diff --git a/sprite_gen/gen/openai_provider.py b/sprite_gen/gen/openai_provider.py
index a45d324..9c81468 100644
--- a/sprite_gen/gen/openai_provider.py
+++ b/sprite_gen/gen/openai_provider.py
@@ -41,7 +41,7 @@ from typing import Any
from PIL import Image, UnidentifiedImageError
-from . import refusal, retry
+from . import address, refusal, retry
from .xai import NO_ANSWER, error_body, read_whole, time_left
from .base import (
GEN_TIMEOUT_SECONDS,
@@ -54,7 +54,6 @@ from .base import (
publish_png,
)
-API_BASE = "https://api.openai.com/v1"
AUTH_ENV = "OPENAI_API_KEY"
AUTH_SOURCE_API_KEY = AUTH_ENV
@@ -299,7 +298,7 @@ class OpenAIProvider:
token = resolve_credential()
announce_api_billing(self.name, AUTH_ENV, f" ({label}).")
data = json.dumps(body).encode("utf-8")
- status, reply, _headers, _asks = _ask(API_BASE + "/responses", token, data, "application/json")
+ status, reply, _headers, _asks = _ask(address.url("openai", "/responses"), token, data, "application/json")
text, metadata = vision.response_text(status, reply, label=label)
return text, {**metadata, "auth_source": AUTH_SOURCE_API_KEY, "transport": "openai-api"}
@@ -319,7 +318,7 @@ class OpenAIProvider:
f" (model={fields['model']}, quality={fields['quality']}, size={fields['size']}).",
)
started = time.monotonic()
- status, reply, headers, asks = _ask(API_BASE + endpoint, token, data, content_type)
+ status, reply, headers, asks = _ask(address.url("openai", endpoint), token, data, content_type)
# The provider's code (and the moderation stage) go in front, format-checked;
# the body the provider sent goes last, as received, with keys and URL
# query strings masked (refusal.said).
diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.py
index 78e2073..a78dca5 100644
--- a/sprite_gen/gen/video.py
+++ b/sprite_gen/gen/video.py
@@ -60,12 +60,12 @@ from typing import Any, Callable
from sprite_gen.spec.runio import atomic_write_text, refuse_overlap
from sprite_gen.util.cli_kwargs import namespace_from_kwargs
-from . import prompt_parts, refusal, retry
+from . import address, prompt_parts, refusal, retry
from .base import announce_api_billing, print_json
from .facing import FACINGS, validate as validate_facing
from sprite_gen.video import facing as facing_mod
from .xai import (
- API_BASE, AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,
+ AUTH_ENV, AUTH_SOURCE_API_KEY, AUTH_SOURCE_GROK_LOGIN,
HTTP_TIMEOUT_SECONDS, GROK_REFRESH_COMMAND, GROK_REFRESH_WHERE, GROK_LOGIN_COMMAND,
NO_ANSWER, Credential, HttpCall, TransportError, resolve_credential, http_json, no_answer, post,
read_whole, rejected_fix, time_left,
@@ -197,8 +197,9 @@ def http_download(url: str, token: str, *, deadline: float | None = None) -> byt
"""The clip's bytes, read whole — by `deadline` (a `time.monotonic()` instant) when one is given: each
wait is cut to what is left of it (xai.read_whole). An error status raises DownloadRefused; a download
that gets no answer it can read whole — the connection failed or timed out, the body broke on the way,
- the deadline came — raises xai.TransportError, its words in `reason`."""
- request = urllib.request.Request(url)
+ the deadline came — raises xai.TransportError, its words in `reason`. The clip is fetched through the xAI base
+ when SPRITE_GEN_XAI_BASE_URL is set (`address.fetched`), else from `url` itself."""
+ request = urllib.request.Request(address.fetched("xai", url))
try:
try:
with urllib.request.urlopen(request, timeout=time_left(HTTP_TIMEOUT_SECONDS, deadline)) as response:
@@ -530,7 +531,7 @@ def _submit_poll_publish(
# some of the poll timeout, which counts from the first send.
started = time.monotonic()
timeout = POLL_TIMEOUT_SECONDS if poll_timeout is None else poll_timeout
- status, reply, _sends = post(call, f"{API_BASE}/videos/{endpoint}", credential.token, body, who="xai", label=verb,
+ status, reply, _sends = post(call, address.url("xai", f"/videos/{endpoint}"), credential.token, body, who="xai", label=verb,
sleep=sleep, deadline=started + timeout)
if status in (401, 403):
raise SystemExit(
@@ -600,7 +601,7 @@ def _poll_publish(
polls += 1
lost: str | None = None
try:
- http, poll = call("GET", f"{API_BASE}/videos/{request_id}", credential.token, None, deadline=deadline)
+ http, poll = call("GET", address.url("xai", f"/videos/{request_id}"), credential.token, None, deadline=deadline)
except TransportError as failed:
lost, http, poll = failed.reason, None, None
poll_status = poll.get("status") if isinstance(poll, dict) else None
diff --git a/sprite_gen/gen/xai.py b/sprite_gen/gen/xai.py
index 48dc39d..9f4f3da 100644
--- a/sprite_gen/gen/xai.py
+++ b/sprite_gen/gen/xai.py
@@ -2,8 +2,10 @@
"""Shared xAI credentials and JSON transport for direct image/video generation.
The user's Grok subscription login takes precedence over XAI_API_KEY. The key
-is used only when no login file exists. The Grok CLI alone writes/refreshes
-that login. Never spawn an agent or switch sources after a login failure.
+is used only when no login file exists, or when SPRITE_GEN_LOGINS=off reads no
+login (`base.logins_on`). The Grok CLI alone writes/refreshes that login. Never
+spawn an agent or switch sources after a login failure. Where the calls go is
+`address` ("xai"), read at each call.
"""
from __future__ import annotations
@@ -19,9 +21,8 @@ from pathlib import Path
from typing import Any, Callable
from . import refusal, retry
-from .base import env_api_key
+from .base import LOGINS_ENV, env_api_key, logins_on
-API_BASE = "https://api.x.ai/v1"
AUTH_ENV = "XAI_API_KEY"
AUTH_SOURCE_API_KEY = "XAI_API_KEY"
AUTH_SOURCE_GROK_LOGIN = "grok-login"
@@ -105,9 +106,16 @@ def _load_grok_login(auth_path: Path, *, now: datetime) -> Credential:
def resolve_credential(*, env: dict[str, str] | None = None, now: datetime | None = None) -> Credential:
- """Prefer the subscription login; a failed login never switches to API credit."""
+ """Prefer the subscription login; a failed login never switches to API credit. With SPRITE_GEN_LOGINS=off no
+ login is looked for and the key is the one route."""
env = os.environ if env is None else env
now = now or datetime.now(timezone.utc)
+ if not logins_on(env):
+ api_key = env_api_key(AUTH_ENV, env, who="xai")
+ if api_key:
+ return Credential(token=api_key, source=AUTH_SOURCE_API_KEY)
+ raise SystemExit(f"xai: no xAI credential — {LOGINS_ENV}=off reads no grok login and {AUTH_ENV} is not set.\n"
+ f" export {AUTH_ENV}=<your xAI console key>, or unset {LOGINS_ENV} to use a grok login.")
auth_path = grok_home() / "auth.json"
# Only absence allows the API key. Broken links/directories are invalid
# logins too, not permission to switch to another billing source.
diff --git a/tests/gen/test_anthropic_api.py b/tests/gen/test_anthropic_api.py
index 03017fe..9c3f63c 100644
--- a/tests/gen/test_anthropic_api.py
+++ b/tests/gen/test_anthropic_api.py
@@ -53,7 +53,7 @@ def server(monkeypatch):
srv.script, srv.asked = [], []
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
- monkeypatch.setattr(api, "API_BASE", f"http://127.0.0.1:{srv.server_address[1]}/v1")
+ monkeypatch.setenv("SPRITE_GEN_ANTHROPIC_BASE_URL", f"http://127.0.0.1:{srv.server_address[1]}/v1")
yield srv
srv.shutdown()
srv.server_close()
@@ -191,7 +191,8 @@ def test_message_batches(server):
assert sent["path"] == "/v1/messages/batches"
assert [r["custom_id"] for r in sent["body"]["requests"]] == ["c1-gen1", "c2-gen1"]
assert all("stream" not in r["params"] for r in sent["body"]["requests"])
- results_url = api.API_BASE + "/messages/batches/msgbatch_01/results"
+ # The results file is Anthropic's own URL; with the base pointed here it is fetched through it (`address.fetched`).
+ results_url = "https://api.anthropic.com/v1/messages/batches/msgbatch_01/results"
server.script.append(("json", 200, {}, {"id": "msgbatch_01", "processing_status": "ended", "results_url": results_url}))
status = api.get_batch(KEY, batch["id"], sleep=lambda s: None)
message = {"id": "msg_b1", "model": api.MODEL, "stop_reason": "end_turn", "content": [
@@ -203,7 +204,9 @@ def test_message_batches(server):
{"custom_id": "c3-gen1", "result": {"type": "expired"}}]
server.script.append(("raw", 200, {}, "\n".join(json.dumps(l) for l in lines).encode() + b"\n"))
results = api.batch_results(KEY, status, sleep=lambda s: None)
- assert server.asked[-1]["path"] == "/v1/messages/batches/msgbatch_01/results"
+ assert server.asked[-1]["path"] == ("/v1/sprite-gen/fetch?url="
+ "https%3A%2F%2Fapi.anthropic.com%2Fv1%2Fmessages%2Fbatches%2Fmsgbatch_01%2Fresults")
+ assert server.asked[-1]["headers"]["x-api-key"] == KEY
ok = results["c1-gen1"]
assert (ok.text, ok.thinking, ok.mode, ok.batch_id, ok.message_id) == ("```pixels\n```", "rows", "batch", "msgbatch_01", "msg_b1")
assert isinstance(results["c2-gen1"], api.ApiError) and "code=invalid_request_error" in results["c2-gen1"].line
diff --git a/tests/gen/test_logins_off.py b/tests/gen/test_logins_off.py
new file mode 100644
index 0000000..9bcfaa1
--- /dev/null
+++ b/tests/gen/test_logins_off.py
@@ -0,0 +1,157 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`SPRITE_GEN_LOGINS=off` (docs/gen.md "Subscription logins off"): no subscription login is read — the grok login
+file, `codex login status`, `claude auth status` — and every provider call runs on its API key, which keeps its
+own rule (set but empty is refused). Unset or empty is `on`, the order as it was. No binary, no network."""
+from __future__ import annotations
+
+import json
+import subprocess
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+
+from sprite_gen import gen
+from sprite_gen.gen import claude_login, codex_provider, facing_vision, xai
+from sprite_gen.gen.base import CodexUnavailableAsk, GenRequest
+from sprite_gen.workflow.access import probe_access
+
+NOW = datetime(2026, 9, 8, 12, 0, tzinfo=timezone.utc)
+
+
+def _grok_login(tmp_path: Path) -> Path:
+ home = tmp_path / "grokhome"
+ home.mkdir()
+ entry = {"key": "login-token", "expires_at": "2026-09-08T18:00:00Z"}
+ (home / "auth.json").write_text(json.dumps({"https://auth.x.ai::client": entry}), encoding="utf-8")
+ return home
+
+
+def _never(*args, **kwargs):
+ pytest.fail(f"no login may be asked about: {args[0] if args else kwargs}")
+
+
+# --- xAI: the grok login file ------------------------------------------------------------------------------------
+
+
[email protected]("logins", [None, "", "on"])
+def test_logins_on_reads_the_grok_login_before_the_key_as_before(tmp_path, monkeypatch, logins) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ env = {"XAI_API_KEY": "key", **({} if logins is None else {"SPRITE_GEN_LOGINS": logins})}
+ assert xai.resolve_credential(env=env, now=NOW).source == xai.AUTH_SOURCE_GROK_LOGIN
+
+
+def test_logins_off_runs_on_the_key_with_a_login_file_present(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ credential = xai.resolve_credential(env={"SPRITE_GEN_LOGINS": "off", "XAI_API_KEY": "door-token"}, now=NOW)
+ assert credential == xai.Credential("door-token", xai.AUTH_SOURCE_API_KEY)
+
+
+def test_logins_off_never_looks_at_the_grok_home(monkeypatch) -> None:
+ monkeypatch.setenv("GROK_HOME", " ") # read, this is refused (`xai.grok_home`)
+ credential = xai.resolve_credential(env={"SPRITE_GEN_LOGINS": "off", "XAI_API_KEY": "door-token"}, now=NOW)
+ assert credential.source == xai.AUTH_SOURCE_API_KEY
+
+
+def test_logins_off_keeps_the_empty_key_refusal(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ with pytest.raises(SystemExit, match="XAI_API_KEY is set but empty"):
+ xai.resolve_credential(env={"SPRITE_GEN_LOGINS": "off", "XAI_API_KEY": " "}, now=NOW)
+
+
+def test_logins_off_without_a_key_names_both(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ with pytest.raises(SystemExit) as refused:
+ xai.resolve_credential(env={"SPRITE_GEN_LOGINS": "off"}, now=NOW)
+ said = str(refused.value)
+ assert "no xAI credential" in said and "SPRITE_GEN_LOGINS=off" in said and "XAI_API_KEY" in said
+
+
[email protected]("value", ["0", "false", "OFF", "no"])
+def test_another_value_is_refused_not_read_as_on(tmp_path, monkeypatch, value) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ with pytest.raises(SystemExit, match=f"SPRITE_GEN_LOGINS={value!r}"):
+ xai.resolve_credential(env={"SPRITE_GEN_LOGINS": value, "XAI_API_KEY": "k"}, now=NOW)
+
+
+def test_a_grok_vision_check_with_logins_off_runs_on_the_key(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ monkeypatch.setenv("SPRITE_GEN_LOGINS", "off")
+ monkeypatch.setenv("XAI_API_KEY", "door-token")
+ asked = []
+
+ def call(method, url, token, body, *, deadline=None):
+ asked.append(token)
+ return 200, {"output": [{"type": "message", "content": [{"type": "output_text", "text": "right"}]}]}
+
+ image = tmp_path / "still.png"
+ image.write_bytes(b"\x89PNG\r\n\x1a\n")
+ _text, metadata = facing_vision.grok_inspect(image, call=call)
+ assert asked == ["door-token"] and metadata["auth_source"] == xai.AUTH_SOURCE_API_KEY
+
+
+# --- Anthropic: `claude auth status` -----------------------------------------------------------------------------
+
+
+def test_logins_off_never_asks_claude_and_runs_on_the_key() -> None:
+ credential = claude_login.resolve_credential(env={"SPRITE_GEN_LOGINS": "off", "ANTHROPIC_API_KEY": "door-token"},
+ run=_never)
+ assert credential == claude_login.Credential(claude_login.AUTH_SOURCE_API_KEY, token="door-token")
+
+
+def test_logins_on_asks_claude_first_as_before() -> None:
+ signed_in = subprocess.CompletedProcess(["claude"], 0, stdout=json.dumps(
+ {"loggedIn": True, "authMethod": "claude.ai", "subscriptionType": "max"}), stderr="")
+ credential = claude_login.resolve_credential(env={"ANTHROPIC_API_KEY": "key"}, run=lambda *a, **k: signed_in)
+ assert credential.source == claude_login.AUTH_SOURCE_LOGIN
+
+
+def test_logins_off_keeps_the_empty_anthropic_key_refusal() -> None:
+ with pytest.raises(SystemExit, match="ANTHROPIC_API_KEY is set but empty"):
+ claude_login.resolve_credential(env={"SPRITE_GEN_LOGINS": "off", "ANTHROPIC_API_KEY": ""}, run=_never)
+
+
+def test_logins_off_without_an_anthropic_key_names_both() -> None:
+ with pytest.raises(SystemExit) as refused:
+ claude_login.resolve_credential(env={"SPRITE_GEN_LOGINS": "off"}, run=_never)
+ said = str(refused.value)
+ assert "no Claude credential" in said and "SPRITE_GEN_LOGINS=off" in said and "ANTHROPIC_API_KEY" in said
+
+
+# --- OpenAI: codex ------------------------------------------------------------------------------------------------
+
+
+def codex_off(monkeypatch):
+ monkeypatch.setenv("SPRITE_GEN_LOGINS", "off")
+ monkeypatch.setattr(codex_provider.subprocess, "run", _never)
+ monkeypatch.setattr(subprocess, "run", _never)
+
+
+def test_logins_off_codex_is_not_usable_and_says_why(codex_off) -> None:
+ assert codex_provider.codex_login() == codex_provider.CodexLogin(
+ None, "subscription logins are off here (SPRITE_GEN_LOGINS=off)")
+
+
+def test_logins_off_the_default_codex_asks_what_the_user_chose(codex_off, monkeypatch) -> None:
+ monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)
+ monkeypatch.delenv(gen.CODEX_UNAVAILABLE_ENV, raising=False)
+ monkeypatch.setenv("SPRITE_GEN_CONFIG_DIR", "/nonexistent-sprite-gen-config")
+ with pytest.raises(CodexUnavailableAsk) as asked:
+ gen.resolve_default_provider()
+ assert "SPRITE_GEN_LOGINS=off" in asked.value.question["reason"]
+
+
+def test_logins_off_codex_generation_and_its_vision_check_refuse(codex_off, tmp_path) -> None:
+ with pytest.raises(SystemExit, match=r"codex-gen: subscription logins are off here \(SPRITE_GEN_LOGINS=off\)"):
+ codex_provider.CodexProvider().generate(GenRequest("x", tmp_path / "raw.png"), tmp_path)
+ with pytest.raises(SystemExit, match=r"subscription logins are off here \(SPRITE_GEN_LOGINS=off\)"):
+ facing_vision.codex_inspect(tmp_path / "raw.png", tmp_path)
+
+
+def test_logins_off_the_access_check_names_it_for_codex_and_the_key_for_grok(codex_off, monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("GROK_HOME", str(_grok_login(tmp_path)))
+ monkeypatch.setenv("XAI_API_KEY", "door-token")
+ codex = probe_access("codex")
+ assert codex["login"] == "unavailable" and "SPRITE_GEN_LOGINS=off" in codex["reason"]
+ assert probe_access("grok")["billing"] == "api-credit"
diff --git a/tests/gen/test_provider_address.py b/tests/gen/test_provider_address.py
new file mode 100644
index 0000000..38bda26
--- /dev/null
+++ b/tests/gen/test_provider_address.py
@@ -0,0 +1,374 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Where every direct provider call goes (`sprite_gen.gen.address`, docs/gen.md "Provider addresses").
+
+Each provider's calls go to its `SPRITE_GEN_<PROVIDER>_BASE_URL` when it is set — read at the call, so a value set
+after import is followed — and to the documented address when it is unset or empty. A URL the provider hands back
+(a finished clip, a batch's results file) is fetched through the same base. A real local HTTP server stands in for
+the relay; nothing reaches the network."""
+from __future__ import annotations
+
+import ast
+import base64
+import http.server
+import io
+import json
+import socket
+import threading
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from http_answer import Answer
+from sprite_gen import gen
+from sprite_gen.audio import provider as sound_provider
+from sprite_gen.gen import anthropic_api, facing_vision, openai_provider, retry, video, xai
+
+ROOT = Path(__file__).resolve().parents[2]
+URLOPEN = urllib.request.urlopen
+KEY = "door-token"
+MP4 = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64
+CLIP = "https://vidgen.x.ai/v/1.mp4?sig=abc"
+PRIVATE_CLIP = "https://vidgen.x.ai/v/2.mp4" # answered only with the bearer token
+RESULTS = "https://api.anthropic.com/v1/messages/batches/msgbatch_01/results"
+DEFAULTS = {
+ "openai": ("SPRITE_GEN_OPENAI_BASE_URL", "https://api.openai.com/v1"),
+ "xai": ("SPRITE_GEN_XAI_BASE_URL", "https://api.x.ai/v1"),
+ "anthropic": ("SPRITE_GEN_ANTHROPIC_BASE_URL", "https://api.anthropic.com/v1"),
+ "elevenlabs": ("SPRITE_GEN_ELEVENLABS_BASE_URL", "https://api.elevenlabs.io/v1"),
+}
+
+
+def _png(tmp_path: Path) -> Path:
+ path = tmp_path / "still.png"
+ Image.new("RGBA", (8, 8), (255, 120, 0, 255)).save(path)
+ return path
+
+
+def _png_b64(field=(20, 90, 200)) -> str:
+ """A 12x8 picture: a blue block on `field` (magenta for a provider keyed on chroma)."""
+ image = Image.new("RGB", (12, 8), field)
+ for x in range(4, 8):
+ for y in range(2, 6):
+ image.putpixel((x, y), (20, 90, 200))
+ buffer = io.BytesIO()
+ image.save(buffer, format="PNG")
+ return base64.b64encode(buffer.getvalue()).decode()
+
+
+VISION = {"model": "m", "status": "completed",
+ "output": [{"type": "message", "content": [{"type": "output_text", "text": "right"}]}]}
+SSE = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in (
+ {"type": "message_start", "message": {"id": "msg_01", "model": anthropic_api.MODEL, "content": [],
+ "usage": {"input_tokens": 5, "output_tokens": 1}}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "ok"}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 2}},
+ {"type": "message_stop"})).encode()
+
+
+def _answer(method: str, path: str, headers: dict[str, str] | None = None) -> tuple[int, dict[str, str], bytes]:
+ """What the relay answers, by what was asked: each provider's own answer shape."""
+ route = urllib.parse.urlsplit(path)
+ if route.path.endswith("/sprite-gen/fetch"):
+ fetched = urllib.parse.parse_qs(route.query)["url"][0]
+ if fetched == CLIP:
+ return 200, {}, MP4
+ if fetched == PRIVATE_CLIP:
+ return (200, {}, MP4) if (headers or {}).get("authorization") == f"Bearer {KEY}" else (403, {}, b"{}")
+ assert fetched == RESULTS, fetched
+ line = {"custom_id": "c1", "result": {"type": "succeeded", "message": {"id": "msg_b", "content": []}}}
+ return 200, {}, json.dumps(line).encode() + b"\n"
+ answers = {
+ ("POST", "/openai/images/generations"): {"data": [{"b64_json": _png_b64()}]},
+ ("POST", "/openai/responses"): VISION,
+ ("POST", "/xai/images/generations"): {"data": [{"b64_json": _png_b64((255, 0, 255))}]},
+ ("POST", "/xai/responses"): VISION,
+ ("POST", "/xai/videos/generations"): {"request_id": "req-1"},
+ ("GET", "/xai/videos/req-1"): {"status": "done", "video": {"url": CLIP, "duration": 6.0}, "model": "m"},
+ ("POST", "/anthropic/messages/batches"): {"id": "msgbatch_01", "processing_status": "in_progress"},
+ ("GET", "/anthropic/messages/batches/msgbatch_01"): {"id": "msgbatch_01", "processing_status": "ended",
+ "results_url": RESULTS},
+ }
+ if (method, route.path) == ("POST", "/anthropic/messages"):
+ return 200, {"Content-Type": "text/event-stream"}, SSE
+ if (method, route.path) == ("POST", "/elevenlabs/sound-generation"):
+ return 200, {}, b"audio"
+ return 200, {"Content-Type": "application/json"}, json.dumps(answers[(method, route.path)]).encode()
+
+
+class _Relay(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *args) -> None:
+ pass
+
+ def _serve(self) -> None:
+ length = int(self.headers.get("Content-Length") or 0)
+ asked = {name.lower(): value for name, value in self.headers.items()}
+ self.server.seen.append((self.command, self.path, asked, self.rfile.read(length)))
+ status, headers, data = _answer(self.command, self.path, asked)
+ self.send_response(status)
+ for name, value in headers.items():
+ self.send_header(name, value)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ do_GET = do_POST = _serve
+
+
[email protected](autouse=True)
+def loopback_only(monkeypatch):
+ """No connection leaves this machine: a call that goes anywhere but the relay fails here, not at a provider."""
+ connect = socket.create_connection
+
+ def refuse(where, *args, **kwargs):
+ if where[0] != "127.0.0.1":
+ raise ConnectionRefusedError(f"the test reached for {where[0]}")
+ return connect(where, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "create_connection", refuse)
+
+
+def relay(monkeypatch, tmp_path):
+ """A relay on 127.0.0.1 standing in for all four providers, one path prefix each — its address is not set yet."""
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Relay)
+ server.seen = []
+ server.root = f"http://127.0.0.1:{server.server_address[1]}"
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ for name in DEFAULTS:
+ monkeypatch.delenv(DEFAULTS[name][0], raising=False)
+ monkeypatch.setenv(f"{name.upper()}_API_KEY", KEY)
+ monkeypatch.setenv("GROK_HOME", str(tmp_path / "no-login"))
+ monkeypatch.setattr(retry, "_sleep", lambda seconds: pytest.fail("nothing is refused here"))
+ yield server
+ server.shutdown()
+ server.server_close()
+
+
+def _point(monkeypatch, relay, *names: str) -> None:
+ for name in names or DEFAULTS:
+ monkeypatch.setenv(DEFAULTS[name][0], f"{relay.root}/{name}")
+
+
+# Every direct provider call site, run as the engine runs it (`address` names each in its docstring).
+def _openai_image(tmp_path):
+ gen.generate_image("openai", "a blue square", tmp_path / "openai.png")
+
+
+def _openai_vision(tmp_path):
+ openai_provider.OpenAIProvider().inspect_image(_png(tmp_path), tmp_path, "which way?")
+
+
+def _grok_image(tmp_path):
+ gen.generate_image("grok", "a blue square", tmp_path / "grok.png")
+
+
+def _grok_vision(tmp_path):
+ facing_vision.grok_inspect(_png(tmp_path), credential=xai.Credential(KEY, xai.AUTH_SOURCE_API_KEY))
+
+
+def _video(tmp_path, name="clip.mp4"):
+ request = video.VideoRequest(image=_png(tmp_path), prompt="sway", out=tmp_path / name)
+ result = video.generate_video(request, credential=xai.Credential(KEY, xai.AUTH_SOURCE_API_KEY), sleep=lambda s: None)
+ assert result.out.read_bytes() == MP4
+
+
+def _claude_message(tmp_path):
+ assert anthropic_api.stream_message(KEY, {"model": anthropic_api.MODEL, "max_tokens": 8}).text == "ok"
+
+
+def _claude_batch(tmp_path):
+ batch = anthropic_api.submit_batch(KEY, [("c1", {"model": anthropic_api.MODEL, "max_tokens": 8})])
+ ended = anthropic_api.get_batch(KEY, batch["id"])
+ assert set(anthropic_api.batch_results(KEY, ended)) == {"c1"}
+
+
+def _sound(tmp_path):
+ assert sound_provider.generate(sound_provider.request("sfx", "Impact", 3, False))[0] == b"audio"
+
+
+SITES = {
+ "openai-image": (_openai_image, "openai", [("POST", "/openai/images/generations")]),
+ "openai-vision": (_openai_vision, "openai", [("POST", "/openai/responses")]),
+ "grok-image": (_grok_image, "xai", [("POST", "/xai/images/generations")]),
+ "grok-vision": (_grok_vision, "xai", [("POST", "/xai/responses")]),
+ "video": (_video, "xai", [("POST", "/xai/videos/generations"), ("GET", "/xai/videos/req-1"),
+ ("GET", "/xai/sprite-gen/fetch?url=" + urllib.parse.quote(CLIP, safe=""))]),
+ "claude-message": (_claude_message, "anthropic", [("POST", "/anthropic/messages")]),
+ "claude-batch": (_claude_batch, "anthropic", [
+ ("POST", "/anthropic/messages/batches"), ("GET", "/anthropic/messages/batches/msgbatch_01"),
+ ("GET", "/anthropic/sprite-gen/fetch?url=" + urllib.parse.quote(RESULTS, safe=""))]),
+ "elevenlabs-sound": (_sound, "elevenlabs", [("POST", "/elevenlabs/sound-generation?output_format=mp3_44100_128")]),
+}
+
+
[email protected]("site", SITES)
+def test_every_call_goes_to_its_providers_variable(relay, monkeypatch, tmp_path, site) -> None:
+ run, provider, asked = SITES[site]
+ _point(monkeypatch, relay, provider)
+ run(tmp_path)
+ assert [(method, path) for method, path, _headers, _body in relay.seen] == asked
+
+
[email protected]("site", SITES)
+def test_a_variable_for_another_provider_moves_nothing(relay, monkeypatch, tmp_path, site) -> None:
+ run, provider, _asked = SITES[site]
+ _point(monkeypatch, relay, *(name for name in DEFAULTS if name != provider))
+ sent: list[str] = []
+ _capture(monkeypatch, sent)
+ run(tmp_path)
+ assert relay.seen == []
+ assert sent and all(url.startswith(DEFAULTS[provider][1] + "/") or url in (CLIP, RESULTS) for url in sent), sent
+
+
+def _capture(monkeypatch, sent: list[str]) -> None:
+ """Every request any direct transport sends, answered as the relay would, without a connection."""
+ def urlopen(request, *args, **kwargs):
+ url = request if isinstance(request, str) else request.full_url
+ sent.append(url)
+ split = urllib.parse.urlsplit(url)
+ if url in (CLIP, RESULTS):
+ path = "/x/sprite-gen/fetch?url=" + urllib.parse.quote(url, safe="")
+ else:
+ provider = next(name for name, (_env, base) in DEFAULTS.items() if url.startswith(base + "/"))
+ path = f"/{provider}" + split.path[len(urllib.parse.urlsplit(DEFAULTS[provider][1]).path):] + (
+ f"?{split.query}" if split.query else "")
+ status, headers, data = _answer(request.get_method() if not isinstance(request, str) else "GET", path)
+ answer = Answer(data, status=status, headers=headers)
+ return _Lines(answer) if headers.get("Content-Type") == "text/event-stream" else answer
+
+ monkeypatch.setattr(urllib.request, "urlopen", urlopen)
+ monkeypatch.setattr(sound_provider, "urlopen", urlopen)
+
+
+class _Lines(Answer):
+ """An SSE answer read line by line, as `anthropic_api.stream_message` reads one."""
+
+ def __init__(self, answer: Answer) -> None:
+ super().__init__(answer._body.getvalue(), status=answer.status, headers=answer.headers)
+
+ def __iter__(self):
+ return iter(self._body.getvalue().splitlines(keepends=True))
+
+
[email protected]("unset", ["absent", "empty", "blank"])
[email protected]("site", SITES)
+def test_without_a_value_every_call_goes_where_it_went(relay, monkeypatch, tmp_path, site, unset) -> None:
+ run, provider, asked = SITES[site]
+ if unset != "absent":
+ monkeypatch.setenv(DEFAULTS[provider][0], "" if unset == "empty" else " ")
+ sent: list[str] = []
+ _capture(monkeypatch, sent)
+ run(tmp_path)
+ base = DEFAULTS[provider][1]
+ expected = []
+ for _method, path in asked:
+ if "/sprite-gen/fetch?url=" in path:
+ expected.append(urllib.parse.unquote(path.split("?url=", 1)[1]))
+ else:
+ expected.append(base + path[len(f"/{provider}"):])
+ assert sent == expected
+ assert relay.seen == []
+
+
+def test_a_value_set_after_import_is_followed_and_unsetting_it_goes_back(relay, monkeypatch, tmp_path) -> None:
+ """Nothing keeps an address from import: the same process follows the variable as it changes."""
+ sent: list[str] = []
+ _capture(monkeypatch, sent)
+ _video(tmp_path, "first.mp4")
+ assert sent == ["https://api.x.ai/v1/videos/generations", "https://api.x.ai/v1/videos/req-1", CLIP]
+ monkeypatch.setattr(urllib.request, "urlopen", URLOPEN)
+ _point(monkeypatch, relay, "xai")
+ _video(tmp_path, "second.mp4")
+ assert [path for _m, path, _h, _b in relay.seen] == [
+ "/xai/videos/generations", "/xai/videos/req-1", "/xai/sprite-gen/fetch?url=" + urllib.parse.quote(CLIP, safe="")]
+ monkeypatch.delenv("SPRITE_GEN_XAI_BASE_URL")
+ later: list[str] = []
+ _capture(monkeypatch, later)
+ _video(tmp_path, "third.mp4")
+ assert later == sent
+
+
+def test_the_relay_gets_the_bytes_the_provider_would_have(relay, monkeypatch, tmp_path) -> None:
+ """Only the address moves: the method, the path under the base, the body and the headers are what went before."""
+ direct: list[urllib.request.Request] = []
+
+ def keep(request, *args, **kwargs):
+ direct.append(request)
+ return Answer({"data": [{"b64_json": _png_b64()}]})
+
+ monkeypatch.setattr(urllib.request, "urlopen", keep)
+ gen.generate_image("openai", "a blue square", tmp_path / "direct.png")
+ monkeypatch.setattr(urllib.request, "urlopen", URLOPEN)
+ _point(monkeypatch, relay, "openai")
+ gen.generate_image("openai", "a blue square", tmp_path / "relayed.png")
+ (method, path, headers, body), = relay.seen
+ before = direct[0]
+ assert before.full_url == "https://api.openai.com/v1/images/generations"
+ assert (method, path, body) == (before.get_method(), "/openai/images/generations", before.data)
+ assert {name.lower(): value for name, value in before.header_items()}.items() <= headers.items()
+
+
+def test_a_clip_is_downloaded_through_the_relay_with_the_bearer_token_only_when_refused(relay, monkeypatch) -> None:
+ _point(monkeypatch, relay, "xai")
+ assert video.http_download(CLIP, KEY) == MP4
+ assert video.http_download(PRIVATE_CLIP, KEY) == MP4
+ fetch = "/xai/sprite-gen/fetch?url="
+ assert [(method, path, headers.get("authorization")) for method, path, headers, _body in relay.seen] == [
+ ("GET", fetch + urllib.parse.quote(CLIP, safe=""), None),
+ ("GET", fetch + urllib.parse.quote(PRIVATE_CLIP, safe=""), None),
+ ("GET", fetch + urllib.parse.quote(PRIVATE_CLIP, safe=""), f"Bearer {KEY}"),
+ ]
+
+
[email protected]("value", ["127.0.0.1:8080/v1", "ftp://relay/v1", "http:///v1", "http://relay/v1?x=1",
+ "http://relay/v1#frag"])
+def test_a_value_that_is_not_an_http_address_is_refused_naming_the_variable(monkeypatch, value) -> None:
+ from sprite_gen.gen import address
+ monkeypatch.setenv("SPRITE_GEN_OPENAI_BASE_URL", value)
+ with pytest.raises(SystemExit, match=r"SPRITE_GEN_OPENAI_BASE_URL="):
+ address.url("openai", "/responses")
+
+
+def test_a_trailing_slash_is_the_same_base() -> None:
+ from sprite_gen.gen import address
+ env = {"SPRITE_GEN_XAI_BASE_URL": "http://127.0.0.1:9/xai/"}
+ assert address.url("xai", "/videos/req-1", env=env) == "http://127.0.0.1:9/xai/videos/req-1"
+
+
+def test_the_registry_is_the_four_providers_and_their_documented_addresses() -> None:
+ from sprite_gen.gen import address
+ assert {name: (p.env, p.default) for name, p in address.PROVIDERS.items()} == DEFAULTS
+
+
+def _modules() -> list[Path]:
+ return sorted((ROOT / "sprite_gen").rglob("*.py"))
+
+
+def test_no_module_but_the_registry_names_a_provider_address() -> None:
+ """A copy of an address anywhere else would be a call the variable does not move."""
+ hosts = [urllib.parse.urlsplit(base).netloc for _env, base in DEFAULTS.values()]
+ named = [(path.relative_to(ROOT).as_posix(), host) for path in _modules() if path.name != "address.py"
+ for host in hosts if host in path.read_text(encoding="utf-8")]
+ assert named == []
+
+
+def test_no_module_reads_an_address_at_import() -> None:
+ """`address` is called inside functions only: a module-level call would keep the address the import saw."""
+ at_import = []
+ for path in _modules():
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for statement in tree.body:
+ if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ continue
+ for node in ast.walk(statement):
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name) and node.func.value.id == "address"):
+ at_import.append(f"{path.relative_to(ROOT).as_posix()}:{node.lineno}")
+ assert at_import == []
diff --git a/tests/gen/test_video.py b/tests/gen/test_video.py
index 4c827f4..3078ec1 100644
--- a/tests/gen/test_video.py
+++ b/tests/gen/test_video.py
@@ -12,13 +12,14 @@ import os
import re
import socket
import urllib.error
+from dataclasses import replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
import pytest
from PIL import Image
-from sprite_gen.gen import retry, video, xai
+from sprite_gen.gen import address, retry, video, xai
NOW = datetime(2026, 9, 8, 12, 0, tzinfo=timezone.utc)
MP4 = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64
@@ -150,13 +151,13 @@ def test_generate_video_posts_data_url_polls_and_publishes_verified_mp4(tmp_path
)
method, url, token, body = api.calls[0]
- assert (method, url, token) == ("POST", f"{video.API_BASE}/videos/generations", "tok")
+ assert (method, url, token) == ("POST", "https://api.x.ai/v1/videos/generations", "tok")
assert body["model"] == video.DEFAULT_MODEL
assert body["duration"] == 6 and body["resolution"] == "720p" and body["aspect_ratio"] == "1:1"
assert body["generate_audio"] is False
assert body["image"]["url"].startswith("data:image/png;base64,")
assert "output" not in body # no upload_url: the direct call is what works on ZDR teams
- assert api.calls[1][:2] == ("GET", f"{video.API_BASE}/videos/req-1")
+ assert api.calls[1][:2] == ("GET", "https://api.x.ai/v1/videos/req-1")
assert slept == [video.POLL_INTERVAL_SECONDS]
assert api.downloads == ["https://vidgen.x.ai/v/1.mp4"]
assert result.out.read_bytes() == MP4
@@ -517,7 +518,7 @@ def test_a_throttled_poll_asks_the_same_request_again_and_publishes(tmp_path: Pa
result = video.generate_video(_request(tmp_path), credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN),
call=api.call, download=api.download, sleep=slept.append)
assert [call[0] for call in api.calls] == ["POST", "GET", "GET", "GET", "GET"]
- assert {call[1] for call in api.calls[1:]} == {f"{video.API_BASE}/videos/req-1"}
+ assert {call[1] for call in api.calls[1:]} == {"https://api.x.ai/v1/videos/req-1"}
# The wait doubles from the poll interval while the polls are refused; an answer puts it back.
assert slept == [video.POLL_INTERVAL_SECONDS * 2, video.POLL_INTERVAL_SECONDS * 4, video.POLL_INTERVAL_SECONDS]
assert result.out.read_bytes() == MP4
@@ -542,7 +543,7 @@ def test_polls_refused_until_the_poll_timeout_end_naming_the_request_to_ask_agai
call=api.call, download=api.download, sleep=clock.sleep, poll_timeout=300)
assert isinstance(unfinished.value, SystemExit)
assert [call[0] for call in api.calls].count("POST") == 1
- assert {call[1] for call in api.calls[1:]} == {f"{video.API_BASE}/videos/req-1"}
+ assert {call[1] for call in api.calls[1:]} == {"https://api.x.ai/v1/videos/req-1"}
# Doubling, held at the ceiling; the poll at 296 s would wait past the timeout for the next, so it is the last.
assert clock.slept == [8.0, 16.0, 32.0, 60.0, 60.0, 60.0, 60.0]
assert clock.now == 296 and len(api.calls) == 1 + 8
@@ -722,7 +723,7 @@ def test_http_json_names_a_request_that_got_no_answer(monkeypatch, raised, reaso
monkeypatch.setattr(xai.urllib.request, "urlopen", urlopen)
with pytest.raises(xai.TransportError) as lost:
- xai.http_json("GET", f"{xai.API_BASE}/videos/req-1", "t")
+ xai.http_json("GET", "https://api.x.ai/v1/videos/req-1", "t")
assert isinstance(lost.value, SystemExit) and video.TransportError is xai.TransportError
assert str(lost.value) == "xai: request failed or timed out; no automatic retry (the server may have accepted it)"
assert lost.value.reason == reason
@@ -734,7 +735,7 @@ def test_a_poll_that_gets_no_answer_is_asked_again_and_publishes(tmp_path: Path,
result = video.generate_video(_request(tmp_path), credential=video.Credential("t", video.AUTH_SOURCE_GROK_LOGIN),
call=api.call, download=api.download, sleep=slept.append)
assert [call[0] for call in api.calls] == ["POST", "GET", "GET", "GET", "GET", "GET"]
- assert {call[1] for call in api.calls[1:]} == {f"{video.API_BASE}/videos/req-1"}
+ assert {call[1] for call in api.calls[1:]} == {"https://api.x.ai/v1/videos/req-1"}
# A lost poll waits like a refused one, and a refused poll then a lost one are two in a row.
assert slept == [8.0, 4.0, 8.0, 16.0]
assert result.out.read_bytes() == MP4
@@ -818,7 +819,7 @@ def test_resume_polls_the_request_without_a_submission_and_publishes(tmp_path: P
api = _FakeApi(polls=[(429, {"error": "slow down"}), (200, {"status": "pending"}), DONE])
result = _resume(tmp_path, api, credential=video.Credential("xai-console", video.AUTH_SOURCE_API_KEY))
assert [call[0] for call in api.calls] == ["GET", "GET", "GET"]
- assert {call[1] for call in api.calls} == {f"{video.API_BASE}/videos/req-7"}
+ assert {call[1] for call in api.calls} == {"https://api.x.ai/v1/videos/req-7"}
assert result.out == (tmp_path / "clip.mp4").resolve() and result.out.read_bytes() == MP4
payload = result.to_dict()
assert payload["kind"] == "sprite-gen-video-report" and payload["mode"] == "resume"
@@ -1042,12 +1043,13 @@ class _Connection:
@pytest.fixture
def wire(monkeypatch, clock):
"""`wire(*answers)` scripts a _Wire on the test's clock, opens every HTTP connection of the test on it, and
- points every xAI URL of the video module at it."""
+ makes it xAI's own address (the variable unset, so a clip is downloaded from where the poll names it)."""
def serve(*answers: bytes | _Hold | _Trickle) -> _Wire:
server = _Wire(clock, list(answers))
monkeypatch.setattr(http.client.HTTPConnection, "connect", lambda connection: server.connect(connection))
- monkeypatch.setattr(video, "API_BASE", server.base)
+ monkeypatch.delenv("SPRITE_GEN_XAI_BASE_URL", raising=False)
+ monkeypatch.setitem(address.PROVIDERS, "xai", replace(address.PROVIDERS["xai"], default=server.base))
return server
return serve
diff --git a/tests/gen/test_video_modes.py b/tests/gen/test_video_modes.py
index a4e3150..dc6791a 100644
--- a/tests/gen/test_video_modes.py
+++ b/tests/gen/test_video_modes.py
@@ -68,7 +68,7 @@ def test_image_only_body_is_the_pre_modes_snapshot(tmp_path: Path) -> None:
still = _still(tmp_path)
api = _FakeApi()
result = video.generate_video(_gen(tmp_path, image=still, duration=6, resolution="720p"), **api.kw())
- assert api.endpoint == f"{video.API_BASE}/videos/generations"
+ assert api.endpoint == "https://api.x.ai/v1/videos/generations"
assert list(api.body) == ["model", "prompt", "duration", "resolution", "image"]
assert api.body == {
"model": "grok-imagine-video-1.5",
@@ -195,7 +195,7 @@ def test_extend_posts_classic_model_to_extensions_and_inherits_the_rest(tmp_path
# Live 2026-09-13: the poll's video.duration is the seconds ADDED (5), the bytes are 20.04 s.
api = _FakeApi(done={"status": "done", "video": {"url": "https://vidgen.x.ai/v/2.mp4", "duration": 5}, "model": "grok-imagine-video"})
result = video.extend_video(_ext(tmp_path, duration=5), probe=_probe(15.04, 20.04), **api.kw())
- assert api.endpoint == f"{video.API_BASE}/videos/extensions"
+ assert api.endpoint == "https://api.x.ai/v1/videos/extensions"
assert list(api.body) == ["model", "prompt", "duration", "video"]
assert api.body["model"] == "grok-imagine-video" and api.body["duration"] == 5
assert api.body["video"]["url"].startswith("data:video/mp4;base64,")
@@ -249,7 +249,7 @@ def _edit(tmp_path: Path, **overrides) -> video.EditRequest:
def test_edit_posts_classic_model_to_edits_without_duration(tmp_path: Path) -> None:
api = _FakeApi(done={"status": "done", "video": {"url": "https://vidgen.x.ai/v/3.mp4", "duration": 7.71}, "model": "grok-imagine-video"})
result = video.edit_video(_edit(tmp_path), probe=_probe(8.0, 7.71), **api.kw())
- assert api.endpoint == f"{video.API_BASE}/videos/edits"
+ assert api.endpoint == "https://api.x.ai/v1/videos/edits"
assert list(api.body) == ["model", "prompt", "video"]
assert api.body["model"] == "grok-imagine-video"
payload = result.to_dict()