Skip to content

gabelul/pixeltamer-gpt-image-skill

pixeltamer

Flagged

Generate, edit, and compose images with GPT Image 2.6, including transparent PNGs with a real alpha channel. Three backends — OpenAI API key (full feature set), codex CLI on your ChatGPT subscription (agent-driven, no key needed), or the direct ChatGPT image route on the same subscription token (--backend codex-images, PNG-only, opt-in). Four modes — one-shot generate, edit or inpaint an existing image, multi-reference composition (up to 16 inputs blended into one), and multi-image batch with verification. Use when the user asks to make an image, generate a poster, draw a mockup, design an icon or sticker, create an ad creative, build an infographic, blend reference images, edit or inpaint an existing image, or produce a cutout asset with a transparent background — "transparent PNG", "no background", "alpha channel", "works on any background". Not for: stripping the background off an existing image you want to keep (that's rembg or ImageMagick, not a generator); file operations that don't change the picture (compression, format conversion, resizing); reading, describing or OCRing an image; video.

scripts/pixeltamer_codex_oauth.py

View on GitHub
#!/usr/bin/env python3
"""pixeltamer_codex_oauth.py — codex-OAuth backend for edit + compose modes.

Bypasses the codex CLI and POSTs directly to the Codex Responses API
(POST <chatgpt-base>/backend-api/codex/responses) using ChatGPT OAuth
credentials from ~/.codex/auth.json. Lets pixeltamer's codex backend do
edit + multi-reference compose without an OpenAI API key — capability
proven in gallery #8 with byte-perfect text fidelity on a dense
infographic.

Reads ~/.codex/config.toml the same way `codex exec` does, so users with
local proxies or load balancers (e.g. `[model_providers.codex-lb]`
pointing at 127.0.0.1) keep working — we honor whatever `chatgpt_base_url`
or model_provider `base_url` they have configured. Fall back to upstream
chatgpt.com if no override.

Subcommands:
  generate   text -> image (no input image attached)
  edit       1 source image + prompt that names what to change/preserve
  compose    2-16 reference images, blended into one output

Auth:
  ~/.codex/auth.json         — Bearer access_token + ChatGPT-Account-ID
  ~/.codex/installation_id   — optional, sent as x-codex-installation-id
  ~/.codex/config.toml       — model_provider resolution for proxy users

Notes:
  - Mask-based inpainting is NOT supported here. The Responses API doesn't
    take a mask parameter. Pixeltamer's `edit --mask` still routes through
    the API backend.
  - Token refresh depends on who owns the auth. Against upstream chatgpt.com
    we hold the token, so a 401 token_expired triggers one in-memory refresh
    and one retry (auth.json is never written — it's codex's file). Against a
    proxy or load balancer, auth is its job: we surface the 401 and point at
    the proxy rather than fighting whichever account it has in play.
  - `-n N` for parallel variants is NOT supported on this backend. Codex
    sessions are sequential. Use the API backend for batch generation.

No third-party dependencies — urllib only. Requires Python 3.11+ for
tomllib (config parsing). Falls back gracefully if tomllib is missing
(uses upstream chatgpt.com URL, may break for proxy users).

Exit codes: 0 success, 2 bad usage, 127 codex auth missing, 1 generation failed.
"""
from __future__ import annotations

import argparse
import base64
import json
import mimetypes
import os
import random
import re
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path

# --------------------------------------------------------------------------- constants

# Default upstream — used when no proxy is configured. The Codex Responses API
# lives at /backend-api/codex/responses on chatgpt.com.
UPSTREAM_BASE = "https://chatgpt.com/backend-api/codex"

# Codex's public OAuth client. Refreshing an access token is a plain
# grant_type=refresh_token POST; the client is public by design (it ships in a
# CLI), so there's no secret here to protect.
REFRESH_ENDPOINT = "https://auth.openai.com/oauth/token"
REFRESH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"

# The chat model that wraps the image_generation tool. Different from the
# service-selected GPT Image model — this one orchestrates the tool call.
#
# Model choice. The historical bug this block replaces: a hardcoded
# "gpt-5.4" that ChatGPT-account endpoints reject (model_not_found) while
# codex CLI ran the same account fine — a stale orchestrator id here is a
# guaranteed 400.
#
# Probe log (2026-11-06, two passes, text completions only unless noted):
# ACCEPTED on this account (stream:true required): gpt-6.1-terra (also
# verified driving a real image_generation edit with alpha output),
# gpt-5.6-luna, gpt-5.6-terra, gpt-6-luna, gpt-6-astra. NOT supported:
# gpt-6.1-luna, gpt-6-terra, everything 5.5/5.4, all -mini and -xhigh
# variants, bare "luna"/"terra". This is what THIS account accepted that
# day — not a pricing table; relative cost is unmeasured. The default is
# the user's pick (terra family), deliberately NOT the config.toml
# flagship (gpt-6-astra): the orchestrator request sets reasoning to null
# and emits one image_generation tool call, so it's a token trickle either
# way. NOTE: this governs only the OAuth edit/compose transport; the
# `pixeltamer_codex.sh` generation wrapper shells out to `codex exec`,
# which uses the account's configured model and has no model flag here.
# Override with PIXELTAMER_RESPONSES_MODEL.
DEFAULT_RESPONSES_MODEL = "gpt-6.1-terra"


def resolve_responses_model() -> str:
    """Pick the orchestrator chat model for the Responses transport.

    Resolution: PIXELTAMER_RESPONSES_MODEL env > DEFAULT_RESPONSES_MODEL
    (user-selected terra model, verified accepted AND verified driving a
    real image_generation edit on this account).
    Deliberately does NOT read ~/.codex/config.toml — that holds the
    account's flagship (gpt-6-astra) and the orchestrator doesn't need it.

    @returns model id string
    """
    override = os.environ.get("PIXELTAMER_RESPONSES_MODEL")
    if override:
        return override
    return DEFAULT_RESPONSES_MODEL

# Free-form client identifier sent in the `originator` header. Helps OpenAI
# distinguish pixeltamer traffic from raw Codex CLI traffic.
ORIGINATOR = "pixeltamer"

# Output format the image_generation tool produces. PNG keeps fidelity for
# text-heavy outputs (most of pixeltamer's job). JPEG / WebP would lose
# typography sharpness on dense infographics.
OUTPUT_FORMAT = "png"

# Sizes this Codex Responses transport accepts. The service selects its GPT Image model; the
# "auto" sentinel lets the model pick based on the input. For edits we
# usually want to match the source aspect ratio, so default is "auto".
SUPPORTED_SIZES = (
    "auto",
    "1024x1024",
    "1024x1536",
    "1536x1024",
    "2048x2048",
    "2048x1152",
    "3840x2160",
    "2160x3840",
)

# Codex saves auth state under ~/.codex/. Three files we read.
CODEX_DIR = Path.home() / ".codex"
AUTH_PATH = CODEX_DIR / "auth.json"
INSTALL_PATH = CODEX_DIR / "installation_id"
CONFIG_PATH = CODEX_DIR / "config.toml"


# --------------------------------------------------------------------------- auth + config

def load_codex_session() -> dict:
    """Read ~/.codex/auth.json and ~/.codex/installation_id.

    Returns a dict with access_token, account_id, installation_id, auth_mode.
    Exits with code 127 if auth.json is missing or malformed — the user needs
    to run `codex login` before pixeltamer's codex-OAuth backend can do
    anything.
    """
    if not AUTH_PATH.exists():
        sys.exit(
            f"pixeltamer_codex_oauth: {AUTH_PATH} not found. "
            f"Run `codex login` first."
        )

    try:
        auth = json.loads(AUTH_PATH.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"pixeltamer_codex_oauth: {AUTH_PATH} is not valid JSON: {e}")

    tokens = auth.get("tokens") or {}
    access_token = (tokens.get("access_token") or "").strip()
    account_id = (tokens.get("account_id") or "").strip()
    if not access_token or not account_id:
        sys.exit(
            f"pixeltamer_codex_oauth: {AUTH_PATH} missing tokens.access_token "
            f"or tokens.account_id. Run `codex login` again."
        )

    installation_id = None
    if INSTALL_PATH.exists():
        installation_id = INSTALL_PATH.read_text(encoding="utf-8").strip() or None

    return {
        "access_token": access_token,
        "refresh_token": (tokens.get("refresh_token") or "").strip() or None,
        "account_id": account_id,
        "installation_id": installation_id,
        "auth_mode": auth.get("auth_mode"),
    }


def resolve_base_url() -> str:
    """Resolve which base URL to POST to, mirroring codex CLI's resolution.

    Reads ~/.codex/config.toml. If `model_provider` is set at top level and a
    matching `[model_providers.<name>]` block has `base_url`, use that.
    Otherwise fall back to upstream chatgpt.com.

    Honoring this is critical for users with a local proxy or load balancer
    (e.g. `[model_providers.codex-lb]` with base_url = "http://127.0.0.1:..."
    that handles auth refresh, rate limiting, multi-account fallback).
    Hardcoding chatgpt.com would break those setups silently.
    """
    if not CONFIG_PATH.exists():
        return UPSTREAM_BASE

    try:
        import tomllib  # Python 3.11+ stdlib
    except ImportError:
        # No TOML parser available — fall back to upstream. Users on Python
        # 3.10 or older with a proxy will need to upgrade Python.
        return UPSTREAM_BASE

    try:
        config = tomllib.loads(CONFIG_PATH.read_text(encoding="utf-8"))
    except Exception:
        return UPSTREAM_BASE

    provider_name = config.get("model_provider")
    if not provider_name:
        return UPSTREAM_BASE

    provider = (config.get("model_providers") or {}).get(provider_name) or {}
    return provider.get("base_url") or UPSTREAM_BASE


def is_upstream(url: str) -> bool:
    """Are we talking to ChatGPT directly, or to somebody's proxy?

    This is the question that decides whether refreshing our token is helpful or
    harmful, so it gets its own function rather than being inlined at the call
    site.
    """
    return url.startswith(UPSTREAM_BASE)


def refresh_access_token(refresh_token: str) -> str | None:
    """Trade a refresh token for a fresh access token. In memory only.

    Deliberately does NOT write the result back to ~/.codex/auth.json. That file
    belongs to the codex CLI, and rotating the token underneath it risks breaking
    a login we don't own. The cost of not persisting is one extra refresh on the
    next invocation, which is a fine trade against corrupting someone's session.

    @param refresh_token - the refresh_token from auth.json
    @returns a fresh access token, or None if the refresh was refused
    """
    body = json.dumps({
        "client_id": REFRESH_CLIENT_ID,
        "grant_type": "refresh_token",
        "refresh_token": refresh_token,
    }).encode("utf-8")
    request = urllib.request.Request(
        REFRESH_ENDPOINT, data=body, method="POST",
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=60) as response:
            payload = json.loads(response.read().decode("utf-8"))
    except Exception:
        # Refresh failing is a normal outcome (expired refresh token, network,
        # OAuth outage). The caller falls back to the `codex login` hint.
        return None
    return (payload.get("access_token") or "").strip() or None


# --------------------------------------------------------------------------- image encoding

def encode_image_data_url(path: Path) -> str:
    """File path -> data URL the Responses API accepts as input_image.

    Format is `data:<mime>;base64,<encoded>`. The model treats the URL as if
    it were a real image attachment and uses it as either the edit source
    (one image) or a compose reference (multiple images).
    """
    if not path.exists():
        sys.exit(f"pixeltamer_codex_oauth: image not found: {path}")
    mime, _ = mimetypes.guess_type(str(path))
    mime = mime or "image/png"
    encoded = base64.b64encode(path.read_bytes()).decode("ascii")
    return f"data:{mime};base64,{encoded}"


# --------------------------------------------------------------------------- request building

def build_request(
    *,
    session: dict,
    prompt: str,
    images: list[Path],
    size: str,
) -> tuple[str, dict, dict]:
    """Construct the (url, headers, body) tuple for a Responses API call.

    Same shape works for generate / edit / compose — the difference is just
    whether `images` is empty (generate), one (edit), or many (compose).
    The `image_generation` tool is requested unconditionally; the model
    decides whether to use input images as edit source vs compose references
    based on the prompt's instructions.

    For multi-reference compose, the prompt should use role labels
    ("PRIMARY SOURCE is image 1; image 2 is style reference") so the model
    knows which input controls what. Without role labels, the model may
    average the references rather than treating one as the structural anchor.
    """
    base_url = resolve_base_url()
    url = f"{base_url.rstrip('/')}/responses"

    headers = {
        "Authorization": f"Bearer {session['access_token']}",
        "ChatGPT-Account-ID": session["account_id"],
        "Content-Type": "application/json",
        "Accept": "text/event-stream",
        "originator": ORIGINATOR,
        "session_id": str(uuid.uuid4()),
    }

    content: list[dict] = [{"type": "input_text", "text": prompt}]
    for img_path in images:
        content.append({
            "type": "input_image",
            "image_url": encode_image_data_url(img_path),
        })

    tool_spec: dict = {"type": "image_generation", "output_format": OUTPUT_FORMAT}
    # Only set size if the caller specified one explicitly; "auto" lets the
    # model pick which is usually correct for edits (matches source aspect).
    if size and size != "auto":
        tool_spec["size"] = size

    body = {
        "model": resolve_responses_model(),
        "instructions": "",
        "input": [
            {"type": "message", "role": "user", "content": content}
        ],
        "tools": [tool_spec],
        "tool_choice": "auto",
        "parallel_tool_calls": False,
        "reasoning": None,
        "store": False,
        "stream": True,
        "include": ["reasoning.encrypted_content"],
    }
    if session.get("installation_id"):
        body["client_metadata"] = {"x-codex-installation-id": session["installation_id"]}

    return url, headers, body


# --------------------------------------------------------------------------- SSE parsing

def parse_sse_stream(raw_text: str) -> list[dict]:
    """Split a Server-Sent Events response text into [{event, data}] dicts.

    Events are separated by blank lines (one or more \\n\\n). Each event has
    one or more `event:` and `data:` lines. We only keep events whose data
    is JSON-parseable; control events with non-JSON data are dropped.
    """
    normalized = raw_text.replace("\r\n", "\n")
    blocks = [b.strip() for b in re.split(r"\n\n+", normalized) if b.strip()]
    events: list[dict] = []
    for block in blocks:
        event_type = "message"
        data_lines: list[str] = []
        for line in block.splitlines():
            if not line or line.startswith(":"):
                continue
            if line.startswith("event:"):
                event_type = line[6:].strip()
            elif line.startswith("data:"):
                data_lines.append(line[5:].lstrip())
        data_text = "\n".join(data_lines)
        if not data_text:
            continue
        try:
            events.append({"event": event_type, "data": json.loads(data_text)})
        except json.JSONDecodeError:
            continue
    return events


def extract_image_b64(events: list[dict]) -> str | None:
    """Find the base64-encoded PNG in the parsed SSE events.

    Preferred source: `response.output_item.done` events where the item is an
    `image_generation_call` with a non-empty `result`. Fallback: the most
    recent `response.image_generation_call.partial_image` event's
    `partial_image_b64` (sometimes the final-result event is missing but a
    partial got through).
    """
    for event in reversed(events):
        data = event.get("data") or {}
        if data.get("type") == "response.output_item.done":
            item = data.get("item") or {}
            if item.get("type") == "image_generation_call" and item.get("result"):
                return item["result"]
    for event in reversed(events):
        data = event.get("data") or {}
        if data.get("type") == "response.image_generation_call.partial_image":
            partial = data.get("partial_image_b64")
            if partial:
                return partial
    return None


# --------------------------------------------------------------------------- retry

# Error codes we treat as transient infra failures and worth retrying. Hit on
# response.failed events when OpenAI's internal pipeline drops mid-generation
# (the image backend's WS dies, the codex-lb proxy hits a capacity wall,
# a worker times out). All of these are "try again in a moment, it'll probably
# work" — distinct from 4xx (bad request, never going to work) or "model
# declined to call the tool" (retrying won't change its mind on the same input).
RETRIABLE_FAILURE_CODES = frozenset({
    "websocket_error",
    "server_error",
    "rate_limit_exceeded",
    "service_unavailable",
})


def _failure_code(events: list[dict]) -> str | None:
    """If a response.failed event is present, return its error.code; else None.

    Used after a stream completes without producing an image to distinguish
    transient infra failures (retriable) from silent tool-declines (not). The
    error payload sometimes lives at data.response.error and sometimes at
    data.error depending on upstream version — check both.
    """
    for ev in reversed(events):
        d = ev.get("data") or {}
        if d.get("type") == "response.failed":
            err = (d.get("response") or {}).get("error") or d.get("error") or {}
            code = err.get("code")
            if isinstance(code, str):
                return code
    return None


def _backoff_seconds(attempt: int) -> float:
    """Exponential backoff with ±25% jitter. attempt is 0-indexed.

    attempt=0 → ~2s, attempt=1 → ~4s, attempt=2 → ~8s. Jitter spreads
    concurrent retries so a thundering-herd doesn't slam the proxy in lockstep
    after a shared upstream blip.
    """
    base = 2.0 * (2 ** attempt)
    jitter = base * 0.25 * (2 * random.random() - 1)
    return max(0.1, base + jitter)


# --------------------------------------------------------------------------- runner

def run_one(*, prompt: str, images: list[Path], size: str, out: Path, debug: bool,
            max_retries: int = 2) -> Path:
    """Orchestrate one logical generation: build the request, send it (with
    retry on transient infra failures), parse SSE, save the PNG.

    Retries on: HTTP 5xx, urllib URLError (connection drops), and SSE
    response.failed events whose error.code is in RETRIABLE_FAILURE_CODES
    (websocket_error, server_error, rate_limit_exceeded, service_unavailable).
    These are the OpenAI/codex-lb-side blips that don't reflect a problem
    with the request — the internal image-generation WS dropped mid-generation,
    a worker timed out, the load balancer hit a wall. Retrying tends to work.

    Does NOT retry on: HTTP 4xx (we did something wrong — bad shape, bad
    token, no quota), token_expired specifically (special-case so the user
    gets the `codex login` hint immediately), or stream-completed-without-
    image-and-without-response.failed (the model silently declined to call
    the tool — retrying with the same prompt won't change its mind).

    max_retries=N gives N retries on top of the initial attempt (so
    max_retries=2 → up to 3 total attempts). Set max_retries=0 to disable.
    """
    session = load_codex_session()
    url, headers, body = build_request(
        session=session, prompt=prompt, images=images, size=size,
    )
    request_data = json.dumps(body).encode("utf-8")
    # One refresh per run. A second 401 after refreshing means something other
    # than expiry, and looping on it would just burn quota.
    refreshed_once = False

    last_response_text = ""
    # `budget` counts transient-failure retries. A token refresh grants one extra
    # pass rather than spending one, because an expired token is not a transient
    # failure and `--max-retries 0` must still get its single refresh-and-retry.
    budget = max_retries + 1
    attempt = -1
    while attempt + 1 < budget:
        attempt += 1
        request = urllib.request.Request(
            url, data=request_data, headers=headers, method="POST",
        )

        try:
            with urllib.request.urlopen(request, timeout=300) as response:
                response_text = response.read().decode("utf-8", errors="replace")
        except urllib.error.HTTPError as error:
            body_preview = error.read().decode("utf-8", errors="replace")[:1500]
            # Token expired. What to do about it depends entirely on who owns
            # the auth, and that's decided by where we're POSTing:
            #
            #   proxy / load balancer  — it owns auth, rotation and refresh. Our
            #     copy of the token is not necessarily even the account it wants
            #     to use, so minting a fresh one and retrying fights it. Surface
            #     the error and point at the proxy.
            #   upstream chatgpt.com   — we're holding the token, so it's on us.
            #     One refresh, one retry, in memory. Matches codex's own
            #     behaviour and recovers silently.
            if error.code == 401 and "token_expired" in body_preview:
                if not is_upstream(url):
                    sys.exit(
                        "pixeltamer_codex_oauth: 401 token_expired from "
                        f"{url}.\n"
                        "That's a proxy/load-balancer endpoint, so auth is its "
                        "job, not ours — refreshing our own token would fight "
                        "whichever account it has in play. Check the proxy is "
                        "running and its accounts are healthy."
                    )
                if refreshed_once or not session.get("refresh_token"):
                    sys.exit(
                        "pixeltamer_codex_oauth: codex access_token expired and "
                        "could not be refreshed. Run `codex login` to mint a "
                        "fresh one."
                    )
                print(
                    "pixeltamer_codex_oauth: access token expired; refreshing "
                    "and retrying once.",
                    file=sys.stderr,
                )
                new_token = refresh_access_token(session["refresh_token"])
                refreshed_once = True
                if not new_token:
                    sys.exit(
                        "pixeltamer_codex_oauth: token refresh was refused. "
                        "The refresh token has probably expired too — run "
                        "`codex login`."
                    )
                # In-memory only: auth.json is codex's file, not ours.
                session["access_token"] = new_token
                headers["Authorization"] = f"Bearer {new_token}"
                budget += 1  # the refreshed retry is extra, not deducted
                continue
            # 5xx is the proxy / upstream having a moment — back off and try again.
            if 500 <= error.code < 600 and attempt < max_retries:
                wait = _backoff_seconds(attempt)
                print(
                    f"pixeltamer_codex_oauth: HTTP {error.code} {error.reason}; "
                    f"retrying in {wait:.1f}s "
                    f"(attempt {attempt + 2}/{max_retries + 1})",
                    file=sys.stderr,
                )
                time.sleep(wait)
                continue
            # 4xx or out-of-retries — surface immediately.
            sys.exit(
                f"pixeltamer_codex_oauth: HTTP {error.code} {error.reason}\n"
                f"Response body:\n{body_preview}"
            )
        except urllib.error.URLError as error:
            # Connection-level failure (DNS, TCP, TLS, read timeout). Always
            # retriable up to the cap — these are pure transport issues.
            if attempt < max_retries:
                wait = _backoff_seconds(attempt)
                print(
                    f"pixeltamer_codex_oauth: connection error ({error}); "
                    f"retrying in {wait:.1f}s "
                    f"(attempt {attempt + 2}/{max_retries + 1})",
                    file=sys.stderr,
                )
                time.sleep(wait)
                continue
            sys.exit(f"pixeltamer_codex_oauth: connection error: {error}")

        last_response_text = response_text
        events = parse_sse_stream(response_text)
        image_b64 = extract_image_b64(events)

        if image_b64:
            out.parent.mkdir(parents=True, exist_ok=True)
            out.write_bytes(base64.b64decode(image_b64))

            if debug:
                # Quick event summary so the caller can see what happened.
                event_types: dict[str, int] = {}
                for ev in events:
                    t = (ev.get("data") or {}).get("type", "?")
                    event_types[t] = event_types.get(t, 0) + 1
                print(f"[debug] {len(events)} SSE events:", file=sys.stderr)
                for t, n in sorted(event_types.items(), key=lambda x: -x[1]):
                    print(f"[debug]   {n:3} × {t}", file=sys.stderr)

            return out

        # No image. Was it a retriable infra failure (response.failed with a
        # known transient code), or a silent decline?
        failure_code = _failure_code(events)
        if failure_code in RETRIABLE_FAILURE_CODES and attempt < max_retries:
            wait = _backoff_seconds(attempt)
            print(
                f"pixeltamer_codex_oauth: response.failed code={failure_code}; "
                f"retrying in {wait:.1f}s "
                f"(attempt {attempt + 2}/{max_retries + 1})",
                file=sys.stderr,
            )
            time.sleep(wait)
            continue

        # Out of retries, or non-retriable absence-of-image. Save the raw SSE
        # for diagnosis and exit with the same messages as the pre-retry code.
        debug_path = out.parent / f"{out.stem}.debug-response.txt"
        out.parent.mkdir(parents=True, exist_ok=True)
        debug_path.write_text(response_text, encoding="utf-8")
        if failure_code:
            sys.exit(
                f"pixeltamer_codex_oauth: response.failed code={failure_code} "
                f"after {attempt + 1} attempt(s).\n"
                f"Raw SSE saved to: {debug_path}"
            )
        sys.exit(
            f"pixeltamer_codex_oauth: response stream completed without an "
            f"image_generation_call result.\n"
            f"Raw SSE saved to: {debug_path}\n"
            f"Likely causes: (a) the model declined to call image_generation, "
            f"(b) the response shape changed upstream, or (c) the request "
            f"was rejected silently."
        )

    # Safety: loop fell through without returning or exiting. Shouldn't be
    # reachable given the structure above (every branch either continues,
    # returns, or sys.exits) but belt-and-suspenders for future edits.
    sys.exit(
        f"pixeltamer_codex_oauth: exhausted {max_retries + 1} attempts "
        f"without success. Last response captured ({len(last_response_text)} bytes)."
    )


# --------------------------------------------------------------------------- subcommand handlers

def cmd_generate(args: argparse.Namespace) -> int:
    """text -> image. Reference images are optional."""
    images = [Path(p) for p in (args.image or [])]
    out = run_one(
        prompt=_apply_background(args, "generate"),
        images=images,
        size=args.size,
        out=Path(args.out),
        debug=args.debug,
        max_retries=args.max_retries,
    )
    print(out.resolve())
    _verify_transparency(args, out)
    return 0


def _warn_size_ignored(args: argparse.Namespace, mode: str) -> None:
    """
    Say out loud that --size won't be honoured, instead of quietly returning something else.

    The Responses API honours `size` for text-to-image but drops it the moment there's an input
    image — you get the input's aspect back at whatever resolution it feels like. Callers building
    a pipeline on top will size their downstream crop off a number that never arrives, so a note
    buried in --help isn't enough.
    """
    if args.size and args.size != "auto":
        print(
            f"pixeltamer_codex_oauth: warning — --size {args.size} is not honoured for {mode} on "
            "the codex backend; output follows the input image's aspect. Resize downstream, or "
            "use --backend api where /v1/images/edits accepts a size.",
            file=sys.stderr,
        )


def cmd_edit(args: argparse.Namespace) -> int:
    """1 source image + prompt -> edited image."""
    if not args.image or len(args.image) != 1:
        sys.exit("pixeltamer_codex_oauth: edit requires exactly one -i/--image")
    _warn_size_ignored(args, "edit")
    out = run_one(
        prompt=_apply_background(args, "edit"),
        images=[Path(args.image[0])],
        size=args.size,
        out=Path(args.out),
        debug=args.debug,
        max_retries=args.max_retries,
    )
    print(out.resolve())
    _verify_transparency(args, out)
    return 0


def cmd_compose(args: argparse.Namespace) -> int:
    """2-16 reference images + prompt -> composed image."""
    if not args.image or not (2 <= len(args.image) <= 16):
        sys.exit("pixeltamer_codex_oauth: compose requires 2-16 -i/--image")
    _warn_size_ignored(args, "compose")
    out = run_one(
        prompt=_apply_background(args, "compose"),
        images=[Path(p) for p in args.image],
        size=args.size,
        out=Path(args.out),
        debug=args.debug,
        max_retries=args.max_retries,
    )
    print(out.resolve())
    _verify_transparency(args, out)
    return 0


# Prompt text appended when --background transparent is requested. The Responses
# transport refuses a background PARAMETER, but prompt-driven alpha demonstrably
# survives edits and compositions (measured 2026-11-06: a codex edit asking for
# transparency came back with a real alpha channel — 62% transparent pixels,
# maxAlpha 255). Wording mirrors TRANSPARENCY_CLAUSE in pixeltamer_codex.sh so
# both codex transports ask for the same thing.
TRANSPARENCY_CLAUSE = (
    "Output the subject as an isolated element on a fully transparent background "
    "with a real PNG alpha channel. No backdrop, no background colour, no "
    "rectangle, no plinth, no surface, no cast shadow, no vignette, no "
    "watermark. Crisp alpha edges, no halo, no matte fringe."
)


def _apply_background(args: argparse.Namespace, mode: str) -> str:
    """Translate --background into what this transport can actually honour.

    transparent -> the prompt clause (the transport has no background param;
    the prompt is the only lever, and it works). opaque/auto -> refused: this
    transport exposes no background control at all, so pretending the flag did
    something would be a lie.

    @param args - parsed args (reads .background, .prompt)
    @param mode - subcommand name, for error messages
    @returns the effective prompt to send
    """
    background = getattr(args, "background", None)
    if background == "transparent":
        print(
            "pixeltamer_codex_oauth: note — the Responses transport has no "
            "background parameter, so --background transparent appends "
            "transparency instructions to your prompt instead. Backdrop "
            "wording in the prompt will override it.",
            file=sys.stderr,
        )
        return f"{args.prompt}\n\n{TRANSPARENCY_CLAUSE}"
    if background in ("opaque", "auto"):
        sys.exit(
            f"pixeltamer_codex_oauth: --background {background} is not honoured "
            f"on the codex backend (no such control on the Responses "
            f"transport). Drop the flag, or use --backend api."
        )
    return args.prompt


def _verify_transparency(args: argparse.Namespace, out: Path) -> None:
    """Post-run alpha check for --background transparent.

    Shells out to the shared node reader (same one the API client uses) so
    "transparent" means the same thing on every backend. Failures follow the
    API client's postcondition behaviour: the file stays on disk, the exit
    code says the run failed. No node on PATH -> says so honestly and skips
    the check rather than pretending it ran.

    @param args - parsed args (reads .background)
    @param out - the saved output path
    """
    if getattr(args, "background", None) != "transparent":
        return
    helper = Path(__file__).resolve().parent / "lib" / "image-dimensions.mjs"
    if not helper.is_file():
        print(
            "pixeltamer_codex_oauth: warning — alpha verification helper not "
            "found; transparency NOT verified.",
            file=sys.stderr,
        )
        return
    script = (
        "import(process.argv[1]).then(m => {"
        "const c = m.readAlphaCoverage(process.argv[2]);"
        "process.stdout.write(JSON.stringify(c));"
        "}).catch(() => process.stdout.write('null'));"
    )
    try:
        import subprocess
        proc = subprocess.run(
            ["node", "-e", script, str(helper), str(out)],
            capture_output=True, text=True, timeout=60,
        )
        coverage = json.loads(proc.stdout or "null")
    except Exception:
        coverage = None
    if coverage is None:
        print(
            "pixeltamer_codex_oauth: warning — could not measure alpha "
            "(node missing or unreadable file); transparency NOT verified.",
            file=sys.stderr,
        )
        return
    transparent_pct = coverage.get("transparentPct")
    if transparent_pct is None:
        print(
            "pixeltamer_codex_oauth: warning — output has no alpha channel "
            "data; transparency NOT verified.",
            file=sys.stderr,
        )
        return
    if transparent_pct < 1:
        sys.exit(
            f"pixeltamer_codex_oauth: FAILED transparency postcondition — "
            f"output is only {transparent_pct}% transparent. The model "
            f"probably painted a backdrop despite the instructions. File "
            f"left at {out}; retry with stronger isolation wording or use "
            f"--backend api."
        )


# --------------------------------------------------------------------------- main

# Per-subcommand wording for the two flags whose behaviour actually differs by mode.
# Sharing one help string across generate/edit/compose used to tell `edit` its -i was
# repeatable, which it never was.
_IMAGE_HELP = {
    "generate": "optional reference image; repeatable (-i a -i b -i c)",
    "edit": "source image to edit; exactly one",
    "compose": "reference image; repeatable, 2-16 (-i a -i b -i c)",
}
_SIZE_HELP = {
    "generate": "output size (default auto)",
    "edit": "output size — NOT honoured on this backend; the Responses API returns "
            "the input image's aspect regardless. Resize downstream.",
    "compose": "output size — NOT honoured on this backend; the Responses API returns "
               "the input images' aspect regardless. Resize downstream.",
}


def _add_common_flags(p: argparse.ArgumentParser, mode: str = "generate") -> None:
    p.add_argument("-p", "--prompt", required=True, help="image description (quote it)")
    p.add_argument("-o", "--out", required=True, help="output PNG path")
    p.add_argument("-i", "--image", action="append", help=_IMAGE_HELP[mode])
    p.add_argument("--size", default="auto",
                   choices=SUPPORTED_SIZES,
                   help=_SIZE_HELP[mode])
    p.add_argument("--quality",
                   choices=("low", "medium", "high", "auto"),
                   default="high",
                   help="quality dial — accepted for CLI parity with API "
                        "backend, but Responses API doesn't expose this knob "
                        "directly; flag is recorded but not currently sent")
    p.add_argument("--background", choices=("transparent", "opaque", "auto"),
                   help="transparent appends a transparency clause to the "
                        "prompt and alpha-verifies the result (the Responses "
                        "transport has no background parameter); opaque/auto "
                        "are refused")
    p.add_argument("--debug", action="store_true",
                   help="print SSE event summary on stderr")
    p.add_argument("--max-retries", type=int, default=2,
                   help="retries on transient infra failures "
                        "(websocket_error, server_error, HTTP 5xx, connection "
                        "drops). Default 2 (= up to 3 total attempts). "
                        "Set 0 to disable retries.")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="pixeltamer_codex_oauth",
        description="Codex-OAuth backend for pixeltamer edit + compose modes.",
    )
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_gen = sub.add_parser("generate", help="text -> image")
    _add_common_flags(p_gen, "generate")
    p_gen.set_defaults(func=cmd_generate)

    p_edit = sub.add_parser("edit", help="1 source image + prompt -> edited image")
    _add_common_flags(p_edit, "edit")
    p_edit.set_defaults(func=cmd_edit)

    p_comp = sub.add_parser("compose", help="2-16 references + prompt -> composed")
    _add_common_flags(p_comp, "compose")
    p_comp.set_defaults(func=cmd_compose)

    args = parser.parse_args(argv)
    return args.func(args)


if __name__ == "__main__":
    sys.exit(main())
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall