Skip to content

xonika9/agent-skills / skills/x9-codex-imagegen

x9-codex-imagegen

Verified

Use when an agent outside Codex, such as Claude Code or OpenCode on any model, should generate or edit a raster image through the user's Codex subscription — «сгенерируй картинку через Codex», «нарисуй иллюстрацию», "generate an image with Codex". Do not use inside a Codex session, where Codex's own imagegen skill applies, or for editable diagrams, crops, resizes, or other edits made locally without generation, or delegating non-image work to Codex.

FileKindSize
SKILL.mdskill md5.1 KB
references/onboarding.jsonconfig1.2 KB
scripts/codex_image.pyscript16.0 KB
scripts/test_codex_image.pyscript12.0 KB

scripts/codex_image.py

View on GitHub
#!/usr/bin/env python3
"""Generate one image with Codex's built-in image tool and verify the PNG.

Runs one `codex exec` turn. By default Codex receives a brief and shapes the
prompt with its own imagegen skill; with --verbatim it passes the given prompt
to the image tool unchanged. Image validity is decided by the file, not by Codex's
reply: the PNG signature and IHDR header are read from disk. When Codex
generated an image but did not save it, the newest PNG from that thread's
generated_images folder is recovered instead of generating again.

Prints one JSON object. Exit code 0 only for status "ok"; a verified PNG
without its final prompt is "incomplete" and remains available at --out.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import shutil
import signal
import socket
import struct
import subprocess
import sys
import tempfile
import time
import zlib
from pathlib import Path
from urllib.parse import urlsplit

PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
NETWORK_ERROR = re.compile(r"error sending request|network error|stream disconnected", re.I)
FINAL_PROMPT = re.compile(r"FINAL_PROMPT:\s*(.+)", re.S)
# A network that drops connections silent for ~30 s makes the image tool fail
# only after several reconnects; transient faults usually fail within seconds.
IDLE_CUT_AFTER = 150.0
# Only the image tool's own failures count from stderr: other Codex connections
# (MCP servers, analytics) log "error sending request" during the same outages.
IMAGE_TOOL_ERROR = re.compile(r"image generation failed:[^\n]*")
# The image tool cannot use a SOCKS proxy, so only an HTTP proxy is accepted.
PROXY_ENV = "X9_CODEX_IMAGE_PROXY"

BRIEF_TASK = """Use your imagegen skill with the built-in image generation tool to create the image described in the brief between the markers.
Save the final image as a PNG at {out}. {replace}Do not edit any other file.
Do not use the CLI or API fallback and never draw the image another way. If the built-in tool fails, reply FAILED=<exact error>.
End your reply with a line FINAL_PROMPT: followed by the prompt of the saved image.
<<<BRIEF
{text}
BRIEF>>>
"""

VERBATIM_TASK = """Call your built-in image generation tool exactly once with the prompt between the markers, verbatim.
Save the final image as a PNG at {out}. {replace}Do not edit any other file.
If the tool fails, reply FAILED=<exact error> and do nothing else; never draw the image another way.
<<<PROMPT
{text}
PROMPT>>>
"""


def png_info(path: Path) -> tuple[int, int, bool] | None:
    """Validate PNG chunks, checksums and raster layout without another dependency."""
    try:
        data = path.read_bytes()
        if data[:8] != PNG_SIGNATURE:
            return None
        offset, header, compressed, palette, ended = 8, None, bytearray(), False, False
        while offset < len(data):
            if offset + 12 > len(data):
                return None
            size = struct.unpack(">I", data[offset:offset + 4])[0]
            kind = data[offset + 4:offset + 8]
            end = offset + 12 + size
            if end > len(data):
                return None
            content = data[offset + 8:end - 4]
            if zlib.crc32(kind + content) != struct.unpack(">I", data[end - 4:end])[0]:
                return None
            if header is None and kind != b"IHDR":
                return None
            if kind == b"IHDR":
                if header is not None or size != 13:
                    return None
                header = struct.unpack(">IIBBBBB", content)
            elif kind == b"PLTE":
                if not size or size % 3 or size > 768:
                    return None
                palette = True
            elif kind == b"IDAT":
                compressed.extend(content)
            elif kind == b"IEND":
                if size or end != len(data):
                    return None
                ended = True
                break
            offset = end
        if not header or not compressed or not ended:
            return None
        width, height, depth, color, compression, filtering, interlace = header
        depths = {0: (1, 2, 4, 8, 16), 2: (8, 16), 3: (1, 2, 4, 8),
                  4: (8, 16), 6: (8, 16)}
        if (not width or not height or depth not in depths.get(color, ()) or compression
                or filtering or interlace not in (0, 1) or (color == 3 and not palette)):
            return None
        decoder = zlib.decompressobj()
        raw = decoder.decompress(bytes(compressed)) + decoder.flush()
        if not decoder.eof or decoder.unused_data:
            return None
        channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[color]
        passes = ((0, 0, 1, 1),) if interlace == 0 else (
            (0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4),
            (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
        position = 0
        for x, y, dx, dy in passes:
            columns = max(0, (width - x + dx - 1) // dx)
            rows = max(0, (height - y + dy - 1) // dy)
            if not columns or not rows:
                continue
            row_size = (columns * channels * depth + 7) // 8 + 1
            for _ in range(rows):
                if position + row_size > len(raw) or raw[position] > 4:
                    return None
                position += row_size
        return (width, height, color in (4, 6)) if position == len(raw) else None
    except (OSError, struct.error, zlib.error):
        return None


def parse_events(jsonl: str) -> tuple[str | None, list[str], list[str]]:
    thread_id, messages, errors = None, [], []
    for line in jsonl.splitlines():
        try:
            event = json.loads(line)
        except json.JSONDecodeError:
            continue
        if not isinstance(event, dict):
            continue
        kind = event.get("type")
        if kind == "thread.started":
            thread_id = event.get("thread_id")
        elif kind == "item.completed":
            item = event.get("item") or {}
            if item.get("type") == "agent_message" and item.get("text"):
                messages.append(item["text"])
            elif item.get("type") == "error" and item.get("message"):
                errors.append(item["message"])
        elif kind in ("error", "turn.failed"):
            detail = event.get("message") or (event.get("error") or {}).get("message")
            errors.append(str(detail or event))
    return thread_id, messages, errors


def classify(text: str) -> str:
    """Return the status for a run that produced no image."""
    return "network_error" if NETWORK_ERROR.search(text) else "failed"


def displayed_proxy(url: str) -> str:
    """Keep proxy credentials in the child environment, outside JSON and logs."""
    return re.sub(r"(://)[^/]*@", r"\1", url, count=1)


def proxy_problem(url: str) -> str | None:
    try:
        parts = urlsplit(url)
        port = parts.port
    except ValueError as error:
        return f"invalid proxy URL: {error}"
    if parts.scheme != "http" or not parts.hostname or not port:
        return "expected http://host:port"
    try:
        socket.create_connection((parts.hostname, port), timeout=5).close()
    except OSError as error:
        return f"not reachable ({error})"
    return None


STOP_SIGNALS = [getattr(signal, name) for name in ("SIGTERM", "SIGINT", "SIGHUP") if hasattr(signal, name)]


class Interrupted(Exception):
    pass


def raise_interrupted(signum: int, _frame: object) -> None:
    raise Interrupted(signal.Signals(signum).name)


def ignore_stop_signals() -> None:
    for sig in STOP_SIGNALS:
        signal.signal(sig, signal.SIG_IGN)


def stop_group(proc: subprocess.Popen) -> None:
    """Stop Codex with everything it started; the npm `codex` wrapper cannot forward SIGKILL."""
    if not hasattr(os, "killpg"):
        proc.kill()
    else:
        try:
            os.killpg(proc.pid, signal.SIGTERM)
            proc.wait(timeout=10)
        except (ProcessLookupError, subprocess.TimeoutExpired):
            pass
        try:
            os.killpg(proc.pid, signal.SIGKILL)  # whatever ignored SIGTERM or outlived the leader
        except ProcessLookupError:
            pass
    proc.wait()


def recover(codex_home: Path, thread_id: str | None, started: float, out: Path) -> Path | None:
    if not thread_id:
        return None
    folder = codex_home / "generated_images" / thread_id
    candidates = [p for p in folder.glob("*.png") if p.stat().st_mtime >= started - 1]
    if not candidates:
        return None
    source = max(candidates, key=lambda p: p.stat().st_mtime)
    shutil.copyfile(source, out)
    return source


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--brief-file", required=True, type=Path,
                        help="what to create; Codex shapes the prompt unless --verbatim")
    parser.add_argument("--verbatim", action="store_true", help="pass the file to the image tool unchanged")
    parser.add_argument("--out", required=True, type=Path, help="destination .png path")
    parser.add_argument("--root", type=Path, help="Codex working root; must contain --out (default: its folder)")
    parser.add_argument("--image", action="append", default=[], type=Path, help="reference image (repeatable)")
    parser.add_argument("--effort", default="medium", help="model_reasoning_effort for the Codex turn")
    parser.add_argument("--timeout", type=float, default=900.0, help="seconds before the run is stopped")
    parser.add_argument("--log-dir", type=Path, help="where run.jsonl and run.err go (default: new temp dir)")
    parser.add_argument("--overwrite", action="store_true", help="allow replacing an existing --out file")
    parser.add_argument("--codex", default="codex", help="codex executable")
    args = parser.parse_args()

    out = args.out.expanduser().resolve()
    root = (args.root.expanduser().resolve() if args.root else out.parent)
    log_dir = args.log_dir.expanduser().resolve() if args.log_dir else Path(tempfile.mkdtemp(prefix="codex-image-"))
    result: dict[str, object] = {"out": str(out), "root": str(root), "log_dir": str(log_dir)}

    def finish(status: str, **extra: object) -> int:
        result.update(status=status, **extra)
        print(json.dumps(result, ensure_ascii=False))
        return 0 if status == "ok" else 1

    if out.suffix.lower() != ".png":
        return finish("usage_error", error="--out must end with .png")
    if not out.is_relative_to(root):
        return finish("usage_error", error="--out must be inside --root, or workspace-write cannot copy it")
    if out.exists() and not args.overwrite:
        return finish("usage_error", error="--out already exists; pass --overwrite only if replacing it was requested")
    try:
        text = args.brief_file.expanduser().read_bytes().decode("utf-8")
        if not args.verbatim:
            text = text.strip()
    except (OSError, UnicodeError) as error:
        return finish("usage_error", error=f"cannot read brief: {error}")
    marker = "PROMPT>>>" if args.verbatim else "BRIEF>>>"
    if not text.strip() or marker in text:
        return finish("usage_error", error=f"brief is empty or contains the {marker} marker")
    for image in args.image:
        if not image.is_file():
            return finish("usage_error", error=f"reference image not found: {image}")

    env = None
    proxy = os.environ.get(PROXY_ENV, "").strip()
    if proxy:
        problem = proxy_problem(proxy)
        if problem:
            return finish("proxy_unreachable", error=f"{PROXY_ENV}={displayed_proxy(proxy)}: {problem}")
        env = dict(os.environ, HTTPS_PROXY=proxy, HTTP_PROXY=proxy)
        result["proxy"] = displayed_proxy(proxy)

    out.parent.mkdir(parents=True, exist_ok=True)
    log_dir.mkdir(parents=True, exist_ok=True)
    command = [args.codex, "exec", "--skip-git-repo-check", "-C", str(root), "-s", "workspace-write",
               "-c", f'model_reasoning_effort="{args.effort}"', "--ephemeral", "--json"]
    for image in args.image:
        command += ["-i", str(image.expanduser().resolve())]
    command.append("-")

    replace = "Replacing the existing file there is explicitly requested. " if out.exists() else ""
    task = (VERBATIM_TASK if args.verbatim else BRIEF_TASK).format(out=out, replace=replace, text=text)
    original_stat = out.stat() if out.exists() else None
    original_signature = (original_stat.st_ino, original_stat.st_size,
                          original_stat.st_mtime_ns, original_stat.st_ctime_ns) if original_stat else None
    started = time.time()
    timed_out = False
    with (log_dir / "run.jsonl").open("w") as stdout, (log_dir / "run.err").open("w") as stderr:
        try:
            proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, text=True,
                                    env=env, start_new_session=hasattr(os, "killpg"))
        except FileNotFoundError:
            return finish("failed", error=f"codex executable not found: {args.codex}")
        except OSError as error:
            return finish("failed", error=f"cannot start codex executable {args.codex}: {error}")
        # Codex runs in its own process group, so a caller's stop signal must be passed on here.
        previous = {sig: signal.signal(sig, raise_interrupted) for sig in STOP_SIGNALS}
        try:
            proc.communicate(task, timeout=args.timeout)
            exit_code: int | None = proc.returncode
        except subprocess.TimeoutExpired:
            ignore_stop_signals()
            stop_group(proc)
            exit_code, timed_out = None, True
        except Interrupted as stop:
            ignore_stop_signals()
            stop_group(proc)
            return finish("interrupted", elapsed_seconds=round(time.time() - started, 1),
                          error=f"stopped by {stop}; the whole Codex run was terminated")
        finally:
            for sig, handler in previous.items():
                signal.signal(sig, handler)
    elapsed = round(time.time() - started, 1)

    thread_id, messages, errors = parse_events((log_dir / "run.jsonl").read_text(errors="replace"))
    last = messages[-1] if messages else None
    final_prompt = FINAL_PROMPT.search(last or "")
    if args.verbatim:
        final_prompt_text: str | None = text  # exactly what the image tool received
    else:
        final_prompt_text = final_prompt.group(1).strip() if final_prompt else None
    result.update(elapsed_seconds=elapsed, thread_id=thread_id, codex_exit=exit_code, last_message=last,
                  final_prompt=final_prompt_text)

    def output_was_written() -> bool:
        try:
            current = out.stat()
        except OSError:
            return False
        signature = (current.st_ino, current.st_size, current.st_mtime_ns, current.st_ctime_ns)
        return current.st_mtime >= started - 1 and signature != original_signature

    def fresh_png() -> tuple[int, int, bool] | None:
        return png_info(out) if output_was_written() else None

    source = "codex-copy"
    if fresh_png() is None:
        if output_was_written():
            return finish("failed", error="Codex wrote a file at --out that is not a PNG")
        codex_home = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex"))
        recovered = recover(codex_home, thread_id, started, out)
        source = f"recovered:{recovered}" if recovered else ""
    info = fresh_png()
    if info:
        if not final_prompt_text:
            return finish("incomplete", source=source, width=info[0], height=info[1], has_alpha=info[2],
                          error="PNG produced, but final prompt is unavailable; deliver it without generating again")
        return finish("ok", source=source, width=info[0], height=info[1], has_alpha=info[2])

    if timed_out:
        return finish("failed", error=f"timed out after {args.timeout:g}s")
    tool_errors = list(dict.fromkeys(IMAGE_TOOL_ERROR.findall((log_dir / "run.err").read_text(errors="replace"))))
    failure_text = "\n".join(errors + messages + tool_errors).strip()
    status = classify(failure_text)
    if status == "network_error":
        result["idle_cut_suspected"] = elapsed >= IDLE_CUT_AFTER
    return finish(status, error=failure_text or f"no image produced; see {log_dir / 'run.err'}")


if __name__ == "__main__":
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall