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.sh

View on GitHub
#!/usr/bin/env bash
# pixeltamer_codex.sh — generate images via the codex CLI's built-in image_gen tool.
#
# Uses your logged-in ChatGPT subscription instead of an OpenAI API key.
#
# Two invocation patterns are tried in sequence:
#   1. Clean numbered task list  (codex's reasoning loop tends to handle this well)
#   2. Augmented "force tool use" prompt as a fallback if pattern 1 doesn't
#      produce an image (some codex versions need the explicit nudge)
#
# Usage:
#   pixeltamer_codex.sh -p "<prompt>" -o <output.png|output.gif> [--size WxH] [--quality low|medium|high|auto] [-n N]
#
# Exit codes: 0 success, 2 bad usage, 127 codex not installed/wedged,
#             124 codex timed out, 1 generation failed.
#
# env:
#   PIXELTAMER_CODEX_TIMEOUT     per-invocation timeout in seconds (default 360)
#   PIXELTAMER_CODEX_KILL_GRACE  seconds between SIGTERM and SIGKILL (default 5)

set -euo pipefail

prog="$(basename "$0")"

# This script runs standalone as well as via the dispatcher, so it cannot borrow
# the dispatcher's helpers. _have used to live only there, which silently
# disabled every `_have node` guard here: the alpha gate returned early and
# --json claimed node was missing on a machine that has it. Both looked fine in
# tests because the test harness defined _have itself.
_have() { command -v "$1" >/dev/null 2>&1; }

# Same trap as _have: this is a standalone script, so it cannot rely on the
# dispatcher having exported anything. `set -u` turns a borrowed name into a
# hard failure at the worst possible moment — after the image was generated and
# paid for, while publishing it.
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Whether we're in JSON mode has to be known before the first thing that can
# fail, which is argument validation — so it's a pre-scan, not a parse result.
json_mode=0
for _arg in "$@"; do [[ "$_arg" == "--json" ]] && json_mode=1; done

# Every failure exit goes through here. In JSON mode that means one object on
# stdout, which is the contract; otherwise the prose this script always printed.
# node builds the envelope so no path or message is escaped by hand.
_bail() {
  local code="$1" retryable="$2" status="$3"; shift 3
  if (( json_mode == 1 )); then
    if _have node; then
      node "${BASH_SOURCE[0]%/*}/lib/emit-json.mjs" error generate codex 0 \
        "$code" "$retryable" "$*"
    else
      printf '{"schema_version":1,"ok":false,"command":"generate","backend":"codex","error":{"code":"internal_error","message":"node is required for --json","retryable":"no"}}\n'
    fi
  else
    echo "$prog: $*" >&2
  fi
  exit "$status"
}

usage() {
  cat >&2 <<EOF
usage: $prog -p "<prompt>" -o <output.png|output.gif> [--size WxH] [--quality Q] [-n N] [-i FILE]... [--reasoning E] [--debug]

required:
  -p, --prompt PROMPT     image description (quote it)
  -o, --out PATH          where to save the output (PNG or animated GIF);
                          auto-suffixed -01, -02 when n>1

optional:
  --size WxH              e.g. 1024x1024, 1536x1024, 1024x1536, auto (default: auto)
  --quality Q             low | medium | high | auto (default: auto)
  -n, --count N           number of images, 1-10 (default: 1)
  --frames N              animated GIF frame count, 2-16 (GIF output only;
                          best-effort — codex assembles the animation itself)
  --frame-ms MS           per-frame duration in ms, 20-2000 (GIF output only;
                          best-effort — verified after the run, drift is reported)
  -i, --image FILE        reference image to attach for character/style consistency.
                          Pass once per file; codex's image_gen will use them as
                          visual context. Repeatable (use -i twice for two images).
  --reasoning E           codex reasoning effort: low | medium | high (default: medium)
  --debug                 keep codex log on success and print its path

env:
  CODEX_BIN               override the codex executable (default: codex)
  PIXELTAMER_CODEX_SHELLLESS=1
                          shellless image-only child — required in containers
                          where nested codex can't build its bwrap sandbox
EOF
  exit 2
}

# --- arg parsing -------------------------------------------------------------

prompt=""
out=""
size="auto"
quality="auto"
count=1
frames=""
frame_ms=""
reasoning="medium"
debug=0
background=""
started_ms=$(( $(date +%s) * 1000 ))
images=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    -p|--prompt)    prompt="${2:-}"; shift 2 ;;
    -o|--out)       out="${2:-}"; shift 2 ;;
    --size)         size="${2:-}"; shift 2 ;;
    --quality)      quality="${2:-}"; shift 2 ;;
    -n|--count)     count="${2:-}"; shift 2 ;;
    --frames)       frames="${2:-}"; shift 2 ;;
    --frame-ms)     frame_ms="${2:-}"; shift 2 ;;
    -i|--image)     images+=("${2:-}"); shift 2 ;;
    --reasoning)    reasoning="${2:-}"; shift 2 ;;
    --background)   background="${2:-}"; shift 2 ;;
    --json)         json_mode=1; shift ;;
    --debug)        debug=1; shift ;;
    -h|--help)      usage ;;
    *)              (( json_mode == 1 )) && _bail invalid_argument no 2 "unknown arg: $1"
                    echo "$prog: unknown arg: $1" >&2; usage ;;
  esac
done

[[ -z "$prompt" ]] && { (( json_mode == 1 )) && _bail invalid_argument no 2 "--prompt required"; echo "$prog: --prompt required" >&2; usage; }
case "$background" in
  ""|transparent|opaque|auto) ;;
  *) (( json_mode == 1 )) && _bail invalid_argument no 2 "--background must be transparent, opaque or auto"
     echo "$prog: --background must be transparent, opaque or auto" >&2; usage ;;
esac
[[ -z "$out" ]] && { (( json_mode == 1 )) && _bail invalid_argument no 2 "--out required"; echo "$prog: --out required" >&2; usage; }
[[ "$count" =~ ^[0-9]+$ ]] || { echo "$prog: -n must be a positive integer" >&2; usage; }
(( count >= 1 && count <= 10 )) || { echo "$prog: -n must be 1-10" >&2; usage; }
[[ -z "$frames" || "$frames" =~ ^[0-9]+$ ]] || { echo "$prog: --frames must be an integer" >&2; usage; }
if [[ -n "$frames" ]]; then (( frames >= 2 && frames <= 16 )) || { echo "$prog: --frames must be 2-16" >&2; usage; }; fi
[[ -z "$frame_ms" || "$frame_ms" =~ ^[0-9]+$ ]] || { echo "$prog: --frame-ms must be an integer" >&2; usage; }
if [[ -n "$frame_ms" ]]; then (( frame_ms >= 20 && frame_ms <= 2000 )) || { echo "$prog: --frame-ms must be 20-2000" >&2; usage; }; fi

# Pre-flight contract checks. Both fire BEFORE codex is invoked: these combos
# cannot be honoured on this backend, and a hard usage error beats burning a
# paid generation to discover it.
out_ext_early="${out##*.}"
if [[ -n "$frames" || -n "$frame_ms" ]]; then
  if [[ "$out_ext_early" != "gif" ]]; then
    (( json_mode == 1 )) && _bail invalid_argument no 2 "--frames/--frame-ms require a .gif output path"
    echo "$prog: --frames/--frame-ms require a .gif output path (-o *.gif)" >&2; usage
  fi
fi
if [[ "$out_ext_early" == "gif" && "$background" == "transparent" ]]; then
  (( json_mode == 1 )) && _bail invalid_argument no 2 "--background transparent is not verified for GIF output on codex; use --backend api"
  echo "$prog: --background transparent is not verified for GIF output on the codex backend: GIF transparency is binary palette transparency, and the transparency clause would request PNG alpha that GIF cannot carry. Use --backend api instead." >&2; usage
fi

# Validate every reference image exists and resolve to absolute paths so codex
# can find them regardless of where it cd's into. Bail fast on a missing file
# rather than discovering it 60s into a codex run.
image_args=()
if (( ${#images[@]} > 0 )); then
  for img in "${images[@]}"; do
    [[ -z "$img" ]] && { echo "$prog: -i/--image given an empty path" >&2; exit 2; }
    [[ -f "$img" ]] || { (( json_mode == 1 )) && _bail input_not_found no 2 "reference image not found: $img"; echo "$prog: reference image not found: $img" >&2; exit 2; }
    abs_img="$(cd "$(dirname "$img")" && pwd)/$(basename "$img")"
    image_args+=(-i "$abs_img")
  done
fi

# --- preflight: codex installed and logged in -------------------------------

CODEX="${CODEX_BIN:-codex}"

if ! command -v "$CODEX" >/dev/null 2>&1; then
  cat >&2 <<EOF
$prog: codex CLI not found on PATH.
  install: npm install -g @openai/codex   (or brew install codex on macOS)
  then:    codex login
EOF
  exit 127
fi

# --- timeout / process-group machinery --------------------------------------

# Distinct exit code for "codex stalled and we put it down". coreutils `timeout`
# uses 124 for the same thing, so we borrow it. Callers MUST treat it apart from
# a plain failure: a stalled image tool won't un-stall on a pushier prompt, so
# the clean->forced fallback skips retry on this code (else one stall becomes
# two and the hang doubles).
readonly EXIT_TIMEOUT=124

# How long a single codex invocation may run before we kill it. 360s is roomy
# for GPT Image generation (normal gens land in 30-90s) and far short of the 71-minute
# orphan that prompted this.
CODEX_TIMEOUT="${PIXELTAMER_CODEX_TIMEOUT:-360}"
[[ "$CODEX_TIMEOUT" =~ ^[0-9]+$ ]] || { echo "$prog: PIXELTAMER_CODEX_TIMEOUT must be an integer (seconds)" >&2; exit 2; }
# Grace between SIGTERM and SIGKILL when reaping a stalled codex.
KILL_GRACE="${PIXELTAMER_CODEX_KILL_GRACE:-5}"
[[ "$KILL_GRACE" =~ ^[0-9]+$ ]] || { echo "$prog: PIXELTAMER_CODEX_KILL_GRACE must be an integer (seconds)" >&2; exit 2; }

# system perl is guaranteed on macOS (/usr/bin/perl) and near-universal on
# Linux. We use it to drop codex into its OWN process group via setpgid(0,0) so
# the watchdog can signal the whole tree: codex is a Node launcher that spawns a
# child binary and forwards SIGTERM but CANNOT forward SIGKILL, so killing only
# the direct PID can orphan grandchildren. `setsid` would be simpler but macOS
# doesn't ship it; bash `set -m` job control is shell-global state that
# misbehaves in non-interactive scripts. perl needs no Homebrew. If perl is
# somehow absent we still time out — just on the direct PID only.
PERL_BIN="$(command -v perl 2>/dev/null || true)"

# _wd_signal PID SIG — signal PID's process group when we own it (perl set it up
# and ps confirms pgid == pid), else just the PID. Confirming pgid first avoids
# the nightmare of `kill -SIG -PID` landing on the caller's own group.
_wd_signal() {
  local pid="$1" sig="$2" pgid=""
  if [[ -n "$PERL_BIN" ]]; then
    pgid="$(ps -o pgid= -p "$pid" 2>/dev/null | tr -d ' ')"
    if [[ -n "$pgid" && "$pgid" == "$pid" ]]; then
      kill -"$sig" -"$pid" 2>/dev/null || true
      return 0
    fi
  fi
  kill -"$sig" "$pid" 2>/dev/null || true
}

# run_with_watchdog SECONDS CMD [ARG...]
# Runs CMD in its own process group and kills the whole group if it outlives
# SECONDS. Returns CMD's own exit code, or $EXIT_TIMEOUT if the watchdog fired.
# Redirect at the call site as usual — CMD inherits the redirections
# (e.g. `run_with_watchdog 360 codex exec <prompt >log 2>&1`).
run_with_watchdog() {
  local timeout_s="$1"; shift

  # Marker file: the watchdog touches it iff it actually fired. Its presence
  # after the wait is how we tell "timed out" from "codex failed on its own".
  local marker
  marker="$(mktemp "${TMPDIR:-/tmp}/pixeltamer-timeout.XXXXXX")"
  rm -f "$marker"

  # NOTE the explicit `<&0`: when job control is off (every non-interactive
  # script), bash redirects an `&` command's stdin from /dev/null unless the
  # redirection is explicit ON the backgrounded command. Our call-site
  # `<"$promptfile"` is on the function, not this `&`, so without `<&0` codex
  # would read an empty prompt. `<&0` forwards the inherited fd0 (the prompt
  # file) and defeats the /dev/null default.
  if [[ -n "$PERL_BIN" ]]; then
    "$PERL_BIN" -e 'use POSIX; setpgid(0,0); exec @ARGV or die "exec failed: $!\n"' "$@" <&0 &
  else
    "$@" <&0 &
  fi
  local child_pid=$!

  # Watchdog polls once a second so it exits promptly when codex finishes (no
  # lingering long sleep). Only after the full budget elapses does it mark+kill.
  (
    waited=0
    while [ "$waited" -lt "$timeout_s" ]; do
      kill -0 "$child_pid" 2>/dev/null || exit 0
      sleep 1
      waited=$(( waited + 1 ))
    done
    kill -0 "$child_pid" 2>/dev/null || exit 0
    # Accepted micro-race: if codex exits on its own in the sliver between this
    # check and the marker write, we'll report a timeout for a run that just
    # finished. The window is sub-millisecond against a 360s budget, and the only
    # cost is one spurious "timed out" the caller can retry — not worth the
    # complexity of distinguishing "we killed it" from "it died at the buzzer".
    : > "$marker"
    _wd_signal "$child_pid" TERM
    sleep "$KILL_GRACE"
    _wd_signal "$child_pid" KILL
  ) &
  local watchdog_pid=$!

  # `wait` only returns once codex is truly dead, so we never retire the
  # watchdog mid-grace and let codex survive.
  local rc=0
  wait "$child_pid" 2>/dev/null || rc=$?

  kill "$watchdog_pid" 2>/dev/null || true
  wait "$watchdog_pid" 2>/dev/null || true

  if [[ -f "$marker" ]]; then
    rm -f "$marker"
    return "$EXIT_TIMEOUT"
  fi
  rm -f "$marker"
  return "$rc"
}

# --- preflight: codex logged in (with its own short timeout) -----------------

# Even `codex login status` can hang if the codex daemon is wedged, so it gets
# the same watchdog on a short leash.
login_log="$(mktemp "${TMPDIR:-/tmp}/pixeltamer-login.XXXXXX")"
login_rc=0
run_with_watchdog 30 "$CODEX" login status >"$login_log" 2>&1 || login_rc=$?
if (( login_rc == EXIT_TIMEOUT )); then
  echo "$prog: 'codex login status' timed out after 30s — codex may be wedged." >&2
  rm -f "$login_log"
  exit 127
fi
# Trust the exit code first. Any non-timeout, non-zero exit (crash, network
# error, unknown state) means we can't confirm login — don't fall through to
# string-matching the output, which could accept a broken state whose text
# happens to contain "logged in".
if (( login_rc != 0 )); then
  echo "$prog: 'codex login status' failed (exit $login_rc). Run: codex login" >&2
  tail -n 30 "$login_log" >&2
  rm -f "$login_log"
  exit 127
fi
# Exit 0 but still parse the text: codex prints "Logged in"/"Not logged in" and
# returns 0 either way. Reject "not logged in" explicitly — it contains the
# substring "logged in", so a bare `grep "logged in"` would wrongly accept it.
if grep -qi "not logged in" "$login_log" || ! grep -qi "logged in" "$login_log"; then
  echo "$prog: codex is not logged in. Run: codex login" >&2
  rm -f "$login_log"
  exit 127
fi
rm -f "$login_log"

# --- output paths ------------------------------------------------------------

# Resolve absolute output path. If the parent dir doesn't exist, create it.
out_dir="$(dirname "$out")"
mkdir -p "$out_dir"
out_dir="$(cd "$out_dir" && pwd)"
out_base="$(basename "$out")"
out_stem="${out_base%.*}"
out_ext="${out_base##*.}"
[[ "$out_ext" == "$out_base" ]] && out_ext="png"
# GIF targets get a prompt-level format clause and a publish-time magic check;
# see the animated GIF section below.
is_gif=0
[[ "$out_ext" == "gif" ]] && is_gif=1

# Shellless children have no shell, so the sprite-sheet + ImageMagick assembly
# the GIF route relies on cannot happen — the cache would only ever hold a
# still PNG and the publish gate would (correctly) refuse it. Reject up front
# instead of burning a codex run on output we would have to throw away.
if (( is_gif == 1 )) && [[ "${PIXELTAMER_CODEX_SHELLLESS:-}" == "1" ]]; then
  echo "$prog: GIF output is not available in shellless mode: the shellless child cannot run ImageMagick to assemble frames. Drop PIXELTAMER_CODEX_SHELLLESS or use a .png target." >&2
  exit 2
fi

# final_paths: where the caller actually wants the PNG(s).
# work_paths:  per-process temp siblings IN the same directory. codex writes
#              here; on success we atomically mv into place. Two reasons:
#                - same-dir mv is a true atomic rename. A temp in TMPDIR would
#                  NOT be — this repo lives on /Volumes/MyEXT while TMPDIR sits
#                  on the boot volume, so that mv would silently degrade to
#                  copy+unlink (non-atomic, and a reader could see a partial).
#                - concurrent gens to the same -o stop clobbering each other:
#                  every run owns a $$-tagged temp, so nobody's rm deletes
#                  someone else's just-written file. That was the old race.
final_paths=()
work_paths=()
if (( count == 1 )); then
  final_paths+=("$out_dir/${out_stem}.${out_ext}")
  work_paths+=("$out_dir/.${out_stem}.tmp.$$.${out_ext}")
else
  for i in $(seq 1 "$count"); do
    final_paths+=("$(printf "%s/%s-%02d.%s" "$out_dir" "$out_stem" "$i" "$out_ext")")
    work_paths+=("$(printf "%s/.%s-%02d.tmp.%s.%s" "$out_dir" "$out_stem" "$i" "$$" "$out_ext")")
  done
fi
# No pre-clean of final_paths — that was the clobber bug. work_paths are
# $$-unique, so run_codex cleans those itself, race-free.

# Fail fast if a target is an existing directory — a later `mv file dir/` would
# move the PNG INTO it and we'd print the dir as if it were the image. (Publish
# re-checks this too, but bailing here avoids a wasted codex call.)
for fp in "${final_paths[@]}"; do
  [[ -d "$fp" ]] && { echo "$prog: output path is a directory: $fp" >&2; exit 2; }
done

# --- transparency -------------------------------------------------------------

# Codex has no `background` parameter to set. What it DOES have is a model that
# produces a real alpha channel when the prompt asks for one — verified: a
# prompt-only request came back RGBA, 78% fully transparent, clean cutout.
#
# (Worth knowing why this isn't done the obvious way: the OAuth Responses
# transport accepts a `background` field in its schema and then rejects the
# value — "Transparent background is not supported for this model." The
# parameter is refused; the prompt is honoured. Two different layers.)
#
# So `--background transparent` here rewrites the prompt instead of setting a
# flag. That mutation is announced on stderr — silently editing someone's prompt
# is not a thing this script should do quietly.
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."

_apply_background_to_prompt() {
  case "$background" in
    transparent)
      prompt="$prompt

$TRANSPARENCY_CLAUSE"
      echo "$prog: note — codex has no background parameter, so --background transparent appends transparency instructions to your prompt instead. Anything in the prompt describing a backdrop, surface or cast shadow will override it." >&2
      ;;
    opaque)
      # Nothing to do — opaque is what codex returns by default.
      ;;
  esac
}

_apply_background_to_prompt

# --- animated GIF -------------------------------------------------------------

# What actually happens here (observed on codex-cli 0.161, 2026-11-06): codex
# has no GIF parameters to set, and its image_gen tool returns a STILL. Given
# a clause like the one below, codex's reasoning loop generates a multi-frame
# sprite sheet as a still PNG, then assembles the animated GIF itself with
# local tooling (observed: ImageMagick crop/resize/-set delay/-loop 0) before
# saving it to the requested path. So this works, but it depends on codex
# having the technique and the tools available on this machine — and the
# publish-time structural gate below exists precisely because a still PNG
# saved at the .gif path is a real failure mode.
GIF_CLAUSE=""
if (( is_gif == 1 )); then
  GIF_CLAUSE="FORMAT REQUIREMENT: the output must be an ANIMATED GIF with multiple frames, not a single still image. The motion must loop smoothly — the last frame flows back into the first with no visible jump."
  if [[ -n "$frames" ]]; then GIF_CLAUSE+=" Use exactly $frames frames."; fi
  if [[ -n "$frame_ms" ]]; then GIF_CLAUSE+=" Show each frame for ${frame_ms} milliseconds."; fi
fi
if [[ -n "$GIF_CLAUSE" ]]; then
  prompt="$prompt

$GIF_CLAUSE"
fi

# Post-generation gate. Prompt-driven transparency is a request, not a contract,
# so the result gets measured rather than assumed.
#
# The cheap check — does the PNG declare an alpha channel — is not enough, and
# that is the entire lesson of this feature: a file can be RGBA with every
# single pixel opaque, which is exactly what you get when the prompt talked the
# model into painting a backdrop. It passes every header check and fails the
# only thing you wanted.
#
# So this decodes pixels (via lib/image-dimensions.mjs, stdlib zlib, no deps)
# and treats "you asked for transparent and got none" as a failure, not a note.
# The file is left on disk — it cost a generation and may still be useful — but
# the exit status says the contract was not met.
_alpha_gate() {
  [[ "$background" == "transparent" ]] || return 0
  local f="$1"
  [[ -f "$f" ]] || return 0
  if [[ "$f" == *.gif ]]; then
    echo "$prog: note — automatic alpha measurement is PNG-only; verify the GIF's transparency manually before compositing." >&2
    return 0
  fi
  _have node || return 0   # gate needs node; silence beats a false failure

  local pct
  pct="$(node -e "
import('$script_dir/lib/image-dimensions.mjs').then(m => {
  const r = m.readAlphaCoverage(process.argv[1]);
  console.log(r === null ? 'unreadable' : r.transparentPct);
}).catch(() => console.log('unreadable'));
" "$f" 2>/dev/null)"

  case "$pct" in
    unreadable|"")
      echo "$prog: note — could not measure alpha on $f; verify it yourself before compositing." >&2
      return 0
      ;;
  esac

  # Below 1% transparent means the subject fills the frame or, far more likely,
  # the model painted a background. Either way it is not a usable cutout.
  if awk -v p="$pct" 'BEGIN { exit !(p < 1.0) }'; then
    echo "$prog: FAILED — you asked for a transparent background but $f is ${pct}% transparent." >&2
    echo "$prog: the prompt almost certainly described a backdrop, surface or cast shadow, which overrides the request. See references/transparency.md." >&2
    echo "$prog: the file was kept at $f in case it is still useful." >&2
    return 1
  fi
  return 0
}

# --- prompt builders ---------------------------------------------------------

# Pattern 1: clean numbered task list. Codex's reasoning loop tends to
# invoke image_gen naturally with this shape, no forcing required.
build_clean_prompt() {
  local target_block=""
  if (( count == 1 )); then
    target_block="6. Save the image to '${work_paths[0]}'."
  else
    local lines="6. Save the images to these exact paths in order:"
    for i in "${!work_paths[@]}"; do
      lines+=$'\n'"   $(( i + 1 )). ${work_paths[$i]}"
    done
    target_block="$lines"
  fi
  local ref_note=""
  if (( ${#images[@]} > 0 )); then
    ref_note=$'\n''0. Attached to this message are '"${#images[@]}"' reference image(s). Look at them and treat them as the visual style and character anchor for the new image — match the character design, color palette, lighting, and proportions you see there. Do not literally copy or paste the references; generate a new composition that visibly belongs to the same visual world.'
  fi
  cat <<EOF
Perform the following tasks:${ref_note}
1. Use the built-in image_gen tool to generate $count image(s).
2. Prompt: $prompt
3. Size: $size
4. Quality: $quality
5. Count: $count
$target_block
7. After saving, print only the absolute file path(s), one per line.
EOF
}

# Pattern 2: augmented "force tool use". Adds explicit guardrails so codex
# doesn't fabricate a PNG via Python or curl when pattern 1 misfires.
build_forced_prompt() {
  local target_block=""
  if (( count == 1 )); then
    target_block="Save the image to this exact path: ${work_paths[0]}"
  else
    target_block="Save the images to these exact paths, in order:"
    for i in "${!work_paths[@]}"; do
      target_block+=$'\n'"  $(( i + 1 )). ${work_paths[$i]}"
    done
  fi
  local ref_note=""
  if (( ${#images[@]} > 0 )); then
    ref_note=$'\n\n''REFERENCES: '"${#images[@]}"' image(s) are attached to this message. Use them as the visual anchor — match the character design, palette, lighting, and proportions. Generate a new composition in the same visual world; do not literally copy them.'
  fi
  cat <<EOF
Use your image_generation tool to create $count image(s).${ref_note}

PROMPT: $prompt
SIZE: $size
QUALITY: $quality
COUNT: $count

Requirements:
- You MUST call the image_generation tool. This is non-negotiable.
- Do NOT write a Python script, shell out to curl, or fabricate the image file any other way.
- ${target_block}
- Reply with only the absolute path(s) of the saved image file(s), one per line. Nothing else.
EOF
}

# True when the first bytes of file $1 match the requested output format.
# Used by the cache-recovery scan so a PNG sprite sheet can never land in a
# .gif slot (or vice versa).
_cache_file_matches_format() {
  local f="$1" sig
  if (( is_gif == 1 )); then
    sig="$(head -c 6 "$f" 2>/dev/null | LC_ALL=C tr -d '\0')"
    [[ "$sig" == "GIF87a" || "$sig" == "GIF89a" ]]
  else
    sig="$(head -c 4 "$f" 2>/dev/null | LC_ALL=C tr -d '\0')"
    [[ "$sig" == $'\x89PNG' ]]
  fi
}

# Shellless variant for containerized runs (PIXELTAMER_CODEX_SHELLLESS=1):
# the child has no shell and no file tools, so it cannot save to a target
# path — image_gen drops the PNG in ~/.codex/generated_images/ and the
# parent's recovery scan publishes it. Asking the child to save anywhere
# would burn reasoning turns on capabilities it was never given.
build_shellless_prompt() {
  cat <<EOF
Generate $count image(s) with your built-in image_gen tool.
PROMPT: $prompt
SIZE: $size
QUALITY: $quality
COUNT: $count
You have no shell and no file tools. image_gen saves each result automatically; do not try to copy or move files.
Print only the absolute path(s) of the saved PNG(s), one per line.
EOF
}


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

run_codex() {
  local prompt_text="$1"
  local log promptfile start_marker
  log="$(mktemp "${TMPDIR:-/tmp}/pixeltamer-codex.XXXXXX")"
  promptfile="$(mktemp "${TMPDIR:-/tmp}/pixeltamer-prompt.XXXXXX")"
  # start_marker's mtime == run start. The recovery scan below uses it to
  # ignore cache images left by OTHER (concurrent) runs.
  start_marker="$(mktemp "${TMPDIR:-/tmp}/pixeltamer-start.XXXXXX")"

  # Feed the prompt via a file (`codex exec` reads stdin when the positional
  # prompt is omitted) instead of `printf | codex`. Same delivery, but codex is
  # now a single process we can background and group-kill — the right-hand side
  # of a pipeline is awkward to signal cleanly. This still keeps the prompt off
  # the positional args, which matters because `-i/--image` greedily eats the
  # next positional.
  # The `${arr[@]+"${arr[@]}"}` idiom expands to nothing when the array is empty
  # and to its elements when it isn't — needed on macOS bash 3.2, which trips
  # `set -u` on a bare empty-array expansion.
  printf '%s' "$prompt_text" > "$promptfile"

  # Clean our own work paths. Race-free: they're $$-tagged, so no other process
  # shares them — the whole reason we write to temps.
  for p in "${work_paths[@]}"; do rm -f "$p"; done

  local rc=0
  if [[ "${PIXELTAMER_CODEX_SHELLLESS:-}" == "1" ]]; then
    # Containerized runs: a nested codex can't build its bwrap sandbox (the
    # container's seccomp profile blocks unshare), and image generation never
    # needed the shell anyway. A shellless child has no sandbox to initialize,
    # so bwrap never runs. The PNG lands in ~/.codex/generated_images/ and the
    # recovery scan below publishes it. See docs/dev-docs/troubleshooting.md.
    run_with_watchdog "$CODEX_TIMEOUT" \
        "$CODEX" exec \
            --skip-git-repo-check \
            --ignore-user-config \
            -s read-only \
            -c 'features.shell_tool=false' \
            -c 'features.unified_exec=false' \
            -c 'features.image_generation=true' \
            -c "model_reasoning_effort=\"${reasoning}\"" \
            ${image_args[@]+"${image_args[@]}"} \
        <"$promptfile" >"$log" 2>&1 || rc=$?
  else
  run_with_watchdog "$CODEX_TIMEOUT" \
      "$CODEX" exec \
          --skip-git-repo-check \
          -s workspace-write \
          -c "model_reasoning_effort=\"${reasoning}\"" \
          ${image_args[@]+"${image_args[@]}"} \
      <"$promptfile" >"$log" 2>&1 || rc=$?
  fi

  rm -f "$promptfile"

  if (( rc == EXIT_TIMEOUT )); then
    echo "$prog: codex timed out after ${CODEX_TIMEOUT}s (raise PIXELTAMER_CODEX_TIMEOUT to change)." >&2
    tail -n 30 "$log" >&2
    echo "(full log: $log)" >&2   # always keep the log on a timeout
    # codex was killed mid-write — sweep any partial work temp it left behind.
    rm -f "$start_marker" "${work_paths[@]}"
    return "$EXIT_TIMEOUT"
  fi

  if (( rc != 0 )); then
    echo "$prog: codex exec failed (last 30 log lines):" >&2
    tail -n 30 "$log" >&2
    echo "(full log: $log)" >&2
    rm -f "$start_marker" "${work_paths[@]}"
    return 1
  fi

  # Did codex actually drop the requested image file(s) at the work paths?
  local missing=0
  for p in "${work_paths[@]}"; do
    [[ -f "$p" ]] || missing=1
  done

  if (( missing == 1 )); then
    # Last-ditch recovery: codex sometimes saves to ~/.codex/generated_images/
    # without copying to the requested paths. Recovery CANNOT attribute cache
    # files to runs: the -newer start-marker filter excludes stale artifacts
    # but a concurrent run finishing after our start is indistinguishable, so
    # a scanned file may belong to someone else's prompt. That's why the scan
    # is opt-in (PIXELTAMER_CODEX_RECOVER=1) by default — shellless mode is
    # the exception: the child has no file tools, so recovery is the ONLY
    # way anything gets published, and refusing it would strand every
    # containerized run.
    # When enabled, the byte check below plus the publish gate still keep a
    # wrong-format file from ever landing.
    #
    # Cache layout: codex-cli 0.161 nests artifacts as exec-<uuid>.<ext> inside
    # UUID directories; older versions wrote flat ig_<ts>.png files — filename
    # shapes churn across builds, so the scan matches any file with the
    # requested extension and relies on the timestamp guard for correctness.
    local cache="$HOME/.codex/generated_images"
    local recover_wanted="${PIXELTAMER_CODEX_RECOVER:-0}"
    [[ "${PIXELTAMER_CODEX_SHELLLESS:-}" == "1" ]] && recover_wanted=1
    if [[ -d "$cache" && "$recover_wanted" == "1" ]]; then
      local found latest
      # Collect candidates first and guard the empty case explicitly: GNU xargs
      # runs `ls -t` with NO args (listing the cwd) on empty input, which could
      # then publish an arbitrary file. BSD xargs doesn't, but we don't rely on
      # the difference. Cache filenames churn across codex builds (ig_<ts>.png
      # once, exec-<uuid>.<ext> now); only the extension matters, so match any
      # file with the requested one. No newlines in codex UUID names, so a
      # newline-delimited list is safe here.
      local ext_glob='*.png'
      (( is_gif == 1 )) && ext_glob='*.gif'
      found="$(find "$cache" -type f -name "$ext_glob" -newer "$start_marker" 2>/dev/null)"
      latest=""
      if [[ -n "$found" ]]; then
        latest="$(printf '%s\n' "$found" | tr '\n' '\0' | xargs -0 ls -t 2>/dev/null | head -n 20)"
      fi
      if [[ -n "$latest" ]]; then
        # Fill ONLY the missing slots, newest candidate first. An existing work
        # file is codex's own genuine output and must never be clobbered by a
        # cache artifact; and each candidate's bytes are checked against the
        # requested format before it may land in a slot.
        local i src
        for i in "${!work_paths[@]}"; do
          [[ -f "${work_paths[$i]}" ]] && continue
          while IFS= read -r src; do
            [[ -n "$src" ]] || continue
            if _cache_file_matches_format "$src"; then
              cp "$src" "${work_paths[$i]}"
              break
            fi
          done <<< "$latest"
        done
        missing=0
        for p in "${work_paths[@]}"; do
          [[ -f "$p" ]] || missing=1
        done
      fi
    fi
  fi

  rm -f "$start_marker"

  if (( missing == 1 )); then
    echo "$prog: codex finished but expected image file(s) not found." >&2
    tail -n 30 "$log" >&2
    echo "(full log: $log)" >&2
    rm -f "${work_paths[@]}"
    return 1
  fi

  # Every work file exists — publish them. Each mv is checked EXPLICITLY: run_codex
  # is called in an `|| rc=$?` context, which disables `set -e` inside the
  # function, so an unchecked failed mv would slip through to a false "ok".
  # Validate-all-first shrinks the partial-batch window, but per-file mv can't be
  # transactional across multiple outputs — a mid-batch failure leaves a mixed
  # set. We detect and report that rather than claim success; a staged-dir
  # transaction would be overkill for an image-gen tool.
  for p in "${work_paths[@]}"; do
    [[ -f "$p" ]] || { echo "$prog: internal: work file vanished before publish: $p" >&2; rm -f "${work_paths[@]}"; return 1; }
  done
  # Format sanity gate: a .gif target must be a complete, multi-frame GIF.
  # codex's GIF route is agent-assembled (sprite sheet + local ImageMagick),
  # so still PNGs saved at the .gif path, single-frame GIFs and truncated
  # files are all real failure modes — publishing any of them would poison
  # downstream consumers. node + lib/gif-inspect.mjs is REQUIRED here: a
  # 6-byte signature can't distinguish a still from an animation, so without
  # node the gate fails loudly instead of claiming a structure-verified win.
  if (( is_gif == 1 )); then
    for p in "${work_paths[@]}"; do
      if _have node; then
        verdict="$(node -e "
import('$script_dir/lib/gif-inspect.mjs').then(m => {
  const r = m.inspectGifFile(process.argv[1]);
  if (r === null) { console.log('UNREADABLE'); return; }
  if (!r.ok) { console.log('BAD ' + r.reason + ' (frames seen: ' + r.frames + ')'); return; }
  if (r.frames < 2) { console.log('BAD static — ' + r.frames + ' frame, not animated'); return; }
  const notes = [];
  const wantFrames = parseInt(process.argv[2], 10);
  const wantMs = parseInt(process.argv[3], 10);
  if (Number.isFinite(wantFrames) && r.frames !== wantFrames) {
    notes.push('requested ' + wantFrames + ' frames, got ' + r.frames);
  }
  if (Number.isFinite(wantMs) && !(r.delaysMs.length && r.delaysMs.every((x) => x === wantMs))) {
    notes.push('delays differ from requested ' + wantMs + 'ms per frame');
  }
  console.log(notes.length ? 'OK-NOTE ' + notes.join('; ') : 'OK');
}).catch(() => console.log('UNREADABLE'));
" "$p" "$frames" "$frame_ms" 2>/dev/null)"
        case "$verdict" in
          OK)
            ;;
          OK-NOTE\ *)
            echo "$prog: note — ${verdict#OK-NOTE } ($p)." >&2
            ;;
          UNREADABLE|"")
            echo "$prog: note — could not structurally inspect $p; verify it by hand." >&2
            ;;
          *)
            echo "$prog: FAILED — $p is not a usable animated GIF ($verdict)." >&2
            rm -f "${work_paths[@]}"
            return 1
            ;;
        esac
      else
        echo "$prog: FAILED — $p needs structural GIF verification but node is not installed." >&2
        echo "  Install node (https://nodejs.org) or verify the GIF by hand, then move it into place yourself." >&2
        ls -la "$p" >&2
        return 1
      fi
    done
  fi
  for i in "${!work_paths[@]}"; do
    # Reject a directory at the target — `mv file dir/` would move INTO it and we
    # would then print the dir path as if it were the PNG.
    if [[ -d "${final_paths[$i]}" ]]; then
      echo "$prog: output path is a directory, refusing to publish: ${final_paths[$i]}" >&2
      rm -f "${work_paths[@]}"
      return 1
    fi
    if ! mv -f "${work_paths[$i]}" "${final_paths[$i]}" || [[ ! -f "${final_paths[$i]}" ]]; then
      echo "$prog: failed to publish ${final_paths[$i]}" >&2
      rm -f "${work_paths[@]}"
      return 1
    fi
  done

  if (( debug == 1 )); then
    echo "$prog: log preserved at $log" >&2
  else
    rm -f "$log"
  fi
  return 0
}

# Try pattern 1 (clean). On a plain failure, fall back to pattern 2 (forced).
# On a TIMEOUT, do NOT fall back: a stalled image tool won't un-stall for a
# pushier prompt, and retrying would just burn another full timeout — that's
# the "one stall becomes two" double-hang we're specifically avoiding.
rc=0
if [[ "${PIXELTAMER_CODEX_SHELLLESS:-}" == "1" ]]; then
  run_codex "$(build_shellless_prompt)" || rc=$?
else
  run_codex "$(build_clean_prompt)" || rc=$?
fi
if (( rc == 0 )); then
  used="clean"
elif (( rc == EXIT_TIMEOUT )); then
  exit "$EXIT_TIMEOUT"
else
  echo "$prog: clean pattern produced no image — retrying with augmented prompt..." >&2
  rc=0
  if [[ "${PIXELTAMER_CODEX_SHELLLESS:-}" == "1" ]]; then
    run_codex "$(build_shellless_prompt)" || rc=$?
  else
    run_codex "$(build_forced_prompt)" || rc=$?
  fi
  if (( rc == 0 )); then
    used="forced"
  elif (( rc == EXIT_TIMEOUT )); then
    exit "$EXIT_TIMEOUT"
  else
    exit 1
  fi
fi

# Transparency is prompt-driven here, so verify rather than assume. A failure
# here is a real failure: the caller asked for a cutout and did not get one.
alpha_failures=0
for p in "${final_paths[@]}"; do _alpha_gate "$p" || alpha_failures=$((alpha_failures + 1)); done

# stdout is either a clean list of paths, or exactly one JSON object. Status
# always goes to stderr so it can never contaminate either shape.
if (( json_mode == 1 )); then
  if ! _have node; then
    printf '{"schema_version":1,"ok":false,"command":"generate","backend":"codex","error":{"code":"internal_error","message":"node is required for --json","retryable":"no"}}\n'
    exit 1
  fi
  # The emitter re-measures alpha and applies the transparency postcondition
  # itself, so ok/false here comes from the same rule the API path uses.
  if [[ "$background" == "transparent" ]]; then
    node "$script_dir/lib/emit-json.mjs" ok generate codex \
      "$(( $(date +%s) * 1000 - started_ms ))" --transparent-requested "${final_paths[@]}"
  else
    node "$script_dir/lib/emit-json.mjs" ok generate codex \
      "$(( $(date +%s) * 1000 - started_ms ))" "${final_paths[@]}"
  fi
  (( alpha_failures > 0 )) && exit 1
  exit 0
fi

for p in "${final_paths[@]}"; do echo "$p"; done

# Paths are still printed — the files exist and were paid for — but exit status
# carries whether the transparency contract was actually met.
if (( alpha_failures > 0 )); then
  exit 1
fi
echo "$prog: ok (pattern: $used)" >&2
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