#!/usr/bin/env bash
# codex-run - resilient headless OpenAI Codex CLI runner for Linux and macOS. Counterpart of agy-run / copilot-fusion-run.
# Requirements: bash 3.2+, python3, git, the `codex` CLI (npm install -g @openai/codex), signed in by you (`codex login`).
#
# Usage (run in the FOREGROUND of a background shell job; never nohup/&/disown):
#   codex-run -t TAG -p PROMPT_FILE [-C WORKDIR] [-o OUTDIR] [-m MODEL] [-e EFFORT] [-T PRINT_TIMEOUT_S] [-r MAX_RESUMES]
#             [-n] [-b BOT] [-j JOB] [-u NOTIFY_URL] [-B CODEX_BINARY] [-D SIMULATE_DROP_AFTER_S]
#   -m  model (default gpt-6.2-sol)   -e  reasoning effort low|medium|high|xhigh   -T  seconds before outer kill (default 3600, 0 = none)
#   -n  approval_policy="on-request" instead of "never" (hangs unattended if Codex asks)   -D  test hook: kill attempt 1 after N s
# What it runs (documented, never --yolo):
#   new run : codex exec --json --sandbox workspace-write -c approval_policy="never" --ignore-user-config -C <workdir> -m <model>
#             --color never --output-last-message <file> [-c model_reasoning_effort=<e>]   (prompt on stdin via `-`)
#   resume  : codex exec resume <thread_id> --json --ignore-user-config -m <model> -c sandbox_mode="workspace-write"
#             -c approval_policy="never" --color never --output-last-message <file> -   (resume takes no -s/-C; cwd = workdir)
#   --ignore-user-config keeps your interactive ~/.codex/config.toml (plugins, MCP servers, notify hooks) out of unattended runs.
#   Auth still comes from CODEX_HOME (default ~/.codex); this script never reads or prints it.
# Behaviour: network/stream drops resume the same thread after ~10/20/40 s; 429s back off ~60..480 s; a print timeout resumes once;
#   auth errors stop the run. Output dir default $HOME/codex-runs: TAG.aN.jsonl, TAG.aN.cli.log, TAG.aN.last.txt, TAG.usage.json,
#   TAG.done, plus RUNSUMMARY and EXIT lines on stdout. Earlier files for a tag move to TAG.prev-<timestamp>/.
# Optional webhook: CODEX_NOTIFY_URL, CODEX_NOTIFY_SECRET or CODEX_NOTIFY_SECRET_FILE, CODEX_NOTIFY_HEADER (default X-Webhook-Secret).
# It does not take the build lock; tell the agent to run heavy builds as `buildlock <command>`.
set -u
TAG=""; PROMPT=""; MODEL=gpt-6.2-sol; WD=$PWD; OUT=""; TMO=3600; MAXRES=3; EFFORT=""; NOSKIP=0; SIMDROP=0
BOT=${CODEX_BOT:-${AGY_BOT:-$(id -un 2>/dev/null || echo bot)}}; JOB=""; NURL=${CODEX_NOTIFY_URL:-${AGY_NOTIFY_URL:-}}; CBIN=${CODEX_PATH:-}
usage() { sed -n '2,21p' "$0"; exit "${1:-2}"; }
while [ $# -gt 0 ]; do
  case "$1" in
    -t|--tag) TAG=$2; shift 2;; -p|--prompt) PROMPT=$2; shift 2;; -m|--model) MODEL=$2; shift 2;; -C|--workdir) WD=$2; shift 2;;
    -o|--outdir) OUT=$2; shift 2;; -T|--print-timeout) TMO=$2; shift 2;; -r|--max-resumes) MAXRES=$2; shift 2;; -e|--effort) EFFORT=$2; shift 2;;
    -n|--no-skip-permissions) NOSKIP=1; shift;; -b|--bot) BOT=$2; shift 2;; -j|--job) JOB=$2; shift 2;; -u|--notify-url) NURL=$2; shift 2;;
    -B|--codex-path) CBIN=$2; shift 2;; -D|--simulate-drop-after) SIMDROP=$2; shift 2;; -h|--help) usage 0;;
    *) echo "codex-run: unknown option $1" >&2; usage 2;;
  esac
done
fail() { echo "codex-run: $*"; echo "EXIT 1"; exit 1; }
[ -n "$TAG" ] && [ -n "$PROMPT" ] || usage 2
command -v python3 >/dev/null 2>&1 || fail "python3 is required"
[ -n "$CBIN" ] || CBIN=$(command -v codex 2>/dev/null || true)
[ -n "$CBIN" ] && [ -x "$CBIN" ] || fail "codex not found (npm install -g @openai/codex, make sure it is on PATH, or pass -B /path/to/codex)"
[ -f "$PROMPT" ] || fail "prompt file not found: $PROMPT"
WD=$(cd "$WD" 2>/dev/null && pwd) || fail "workdir not found"
[ -n "$OUT" ] || OUT=$HOME/codex-runs
mkdir -p "$OUT" && OUT=$(cd "$OUT" && pwd) || fail "cannot create outdir"
[ -n "$JOB" ] || JOB=$TAG
export NODE_OPTIONS=${NODE_OPTIONS:---max-old-space-size=3072}
[ "${NODE_ENV:-}" = production ] && unset NODE_ENV
APPROVAL=never; [ "$NOSKIP" = 1 ] && APPROVAL=on-request
[ "$TMO" != 0 ] && [ "$TMO" -lt 3600 ] && echo "codex-run: warning: print-timeout ${TMO}s < 3600s"

rm -f "$OUT/$TAG.done"
if ls "$OUT/$TAG".a[0-9]* "$OUT/$TAG.usage.json" >/dev/null 2>&1; then
  PREV="$OUT/$TAG.prev-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$PREV"
  for f in "$OUT/$TAG".a[0-9]* "$OUT/$TAG.usage.json"; do [ -e "$f" ] && mv "$f" "$PREV/"; done
  echo "codex-run: previous $TAG files moved to $PREV"
fi
HEAD0=$(git -C "$WD" rev-parse HEAD 2>/dev/null || true)
CONT='Your previous turn was cut off by a network error or time limit. First check git status and git log to see what is already done; do NOT redo committed work. Then continue the original task to completion and end with the required summary and final commit SHA.'

PY=$(mktemp "${TMPDIR:-/tmp}/cdr.XXXXXX") || fail "mktemp failed"
trap 'rm -f "$PY"' EXIT
cat > "$PY" <<'PYEOF'
import json, os, re, shlex, signal, subprocess, sys, time

def read_events(log, last_msg):
    r = dict(conv=None, text="", last="", step=dict(input=0, cached=0, output=0, reasoning=0), ok_turn=False, failed_turn=False)
    if os.path.exists(last_msg):
        try: r["last"] = open(last_msg, encoding="utf-8", errors="replace").read()
        except Exception: pass
    if not os.path.exists(log): return r
    bits = []
    for l in open(log, encoding="utf-8", errors="replace").read().splitlines():
        if l.startswith("EXIT "): continue
        obj = None
        if l.startswith("{"):
            try: obj = json.loads(l)
            except Exception: obj = None
        if isinstance(obj, dict):
            t = str(obj.get("type") or "")
            if t == "thread.started" and obj.get("thread_id"): r["conv"] = str(obj["thread_id"])
            elif obj.get("thread_id") and not r["conv"]: r["conv"] = str(obj["thread_id"])
            if t == "turn.completed":
                r["ok_turn"] = True
                u = obj.get("usage") or {}
                for k, src in (("input", "input_tokens"), ("cached", "cached_input_tokens"), ("output", "output_tokens"), ("reasoning", "reasoning_output_tokens")):
                    r["step"][k] += int(u.get(src) or 0)
            if t == "turn.failed": r["failed_turn"] = True
            item = obj.get("item") or {}
            if t == "item.completed" and item.get("type") == "agent_message" and item.get("text"): r["last"] = str(item["text"])
            msg = None
            err = obj.get("error")
            if err:
                if isinstance(err, str): msg = err
                else: msg = " ".join(str(x) for x in (err.get("message"), err.get("code"), json.dumps(err)) if x)
            if obj.get("message"): msg = ("%s %s" % (msg, obj["message"])) if msg else str(obj["message"])
            if t in ("error", "turn.failed"): bits.append(msg or l)
        elif re.search(r"(?i)error:|ERROR|rate limit|429|unauthoriz|unauthenticated|not logged", l): bits.append(l)
    r["text"] = " ".join(bits)
    if not r["last"]: r["last"] = r["text"]
    return r

def classify(ev, sim, rc, err_text):
    e = (ev["text"] + " " + err_text).lower()
    if sim: return "NETWORK"
    if re.search(r"not logged|unauthenticated|unauthoriz|auth(?:entication)? (?:required|failed|error)|invalid api key|no api key", e): return "AUTH"
    if re.search(r"resource_exhausted|code 429|\b429\b|rate[_\s-]?limit|too many requests", e): return "QUOTA"
    if re.search(r"print timeout|timed? out after", e): return "PRINT_TIMEOUT"
    if re.search(r"summarization|connection timed out|network issue|stream was interrupted|connection reset|\beof\b|i/o timeout|unavailable|unexpected eof|broken pipe|temporarily unavailable|transport error|error sending request|connection aborted", e): return "NETWORK"
    if rc == 0 and not ev["failed_turn"]: return "OK"
    if rc == 0 and ev["ok_turn"] and ev["last"]: return "OK"
    if ev["ok_turn"] and ev["last"] and ev["failed_turn"]: return "OK_STICKY"
    return "KILLED_OR_OTHER"

def cmd_run():
    # run TIMEOUT CWD STDINFILE OUTFILE ERRFILE -- cmd...   exit 124 on timeout; kills the whole process group
    to, cwd, sin, out, err = int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6]
    cmd = sys.argv[8:]
    p = subprocess.Popen(cmd, cwd=cwd, stdin=open(sin, "rb"), stdout=open(out, "wb"), stderr=open(err, "wb"), start_new_session=True)
    def kill_group(*_):
        try: os.killpg(p.pid, signal.SIGTERM)
        except Exception: pass
        time.sleep(3)
        try: os.killpg(p.pid, signal.SIGKILL)
        except Exception: pass
        sys.exit(143)
    signal.signal(signal.SIGTERM, kill_group); signal.signal(signal.SIGINT, kill_group); signal.signal(signal.SIGHUP, kill_group)
    try: rc = p.wait(timeout=to if to > 0 else None)
    except subprocess.TimeoutExpired:
        for sig in (signal.SIGTERM, signal.SIGKILL):
            try: os.killpg(p.pid, sig)
            except Exception: pass
            try: p.wait(timeout=15); break
            except Exception: pass
        sys.exit(124)
    sys.exit(rc if rc >= 0 else 128 - rc)

def cmd_analyze():
    # analyze LOG LASTMSG RC SIM OUTERKILL ERRFILE
    log, lm, rc, sim, outer, errf = sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5] == "1", sys.argv[6] == "1", sys.argv[7]
    ev = read_events(log, lm)
    et = open(errf, encoding="utf-8", errors="replace").read() if os.path.exists(errf) else ""
    cls = classify(ev, sim, rc, et)
    if outer and cls not in ("AUTH", "QUOTA", "OK", "OK_STICKY"): cls = "PRINT_TIMEOUT"
    print("CLS=%s" % cls); print("NCONV=%s" % shlex.quote(ev["conv"] or ""))

def price(m):
    # OpenAI API standard short-context list prices, USD per 1M tokens: (input, cached input, output). Reasoning is billed as output.
    # Prices change: re-check https://developers.openai.com/api/docs/pricing and edit this table.
    m = m.lower()
    table = [("gpt-6.2-astra", (8.00, 0.40, 40.00)), ("gpt-6.2-sol", (2.00, 0.10, 10.00)), ("gpt-6-astra", (10.00, 1.00, 50.00)),
             ("gpt-6.1-sol", (2.00, 0.10, 10.00)), ("gpt-6.1-terra", (1.00, 0.05, 5.00)), ("gpt-6-luna", (0.10, 0.01, 0.50)),
             ("gpt-6-sol", (2.00, 0.20, 10.00)), ("gpt-5.6-sol", (4.00, 0.40, 20.00)), ("gpt-5.6-terra", (2.00, 0.20, 12.00)),
             ("gpt-5.6-luna", (0.20, 0.02, 1.20))]
    for k, v in table:
        if k in m: return v
    return (2.00, 0.10, 10.00)

def cmd_summary():
    a = json.loads(sys.argv[2])
    out, tag, attempt, wd = a["out"], a["tag"], a["attempt"], a["workdir"]
    tot = dict(input=0, cached=0, output=0, reasoning=0); atts = []; resp = ""
    for i in range(1, attempt + 1):
        f = os.path.join(out, "%s.a%d.jsonl" % (tag, i)); lm = os.path.join(out, "%s.a%d.last.txt" % (tag, i))
        ev = read_events(f, lm)
        for k in tot: tot[k] += ev["step"][k]
        if ev["last"]: resp = ev["last"]
        atts.append(dict(log=f, usage=dict(ev["step"]), status="SUCCESS" if ev["ok_turn"] else ("FAILED_TURN" if ev["failed_turn"] else "NO_RESULT"), error=ev["text"][:300]))
    pr = price(a["model"])
    uncached = max(0, tot["input"] - tot["cached"])
    usd = round((uncached * pr[0] + tot["cached"] * pr[1] + (tot["output"] + tot["reasoning"]) * pr[2]) / 1e6, 4)
    def git(*args):
        try: return subprocess.run(["git", "-C", wd] + list(args), capture_output=True, text=True, timeout=30).stdout.strip()
        except Exception: return ""
    commit = None
    cands = re.findall(r"(?i)(?:sha|commit)[^0-9a-f\n]{0,40}\b([0-9a-f]{7,40})\b", resp)[::-1] + re.findall(r"\b[0-9a-f]{7,40}\b", resp)
    for c in cands:
        full = git("rev-parse", "--verify", "-q", c + "^{commit}")
        if full: commit = full; break
    head1 = git("rev-parse", "HEAD")
    if not commit and head1 and head1 != a["head0"]: commit = head1
    warn = a["warn"] or None
    doc = dict(bot=a["bot"], job=a["job"], tag=tag, model=a["model"], effort=a["effort"] or None, status=a["final"], warning=warn, conversation_id=a["conv"] or None,
               start=a["start"], end=a["end"], attempts=atts, tokens=tot, usd=usd, commit=commit,
               price_per_1m=dict(input=pr[0], cached=pr[1], output_reasoning=pr[2]),
               note="OpenAI API standard short-context list prices (https://developers.openai.com/api/docs/pricing). input_tokens treated as inclusive of cached_input_tokens. Long-context rates are higher. ChatGPT-plan sign-in usage may be included in the subscription rather than billed at these API rates.",
               flags="exec --json --sandbox workspace-write -c approval_policy=never --ignore-user-config; resume uses -c sandbox_mode=workspace-write (no -s/-C on resume)",
               response_tail=resp[-600:])
    up = os.path.join(out, tag + ".usage.json")
    json.dump(doc, open(up, "w"), indent=2)
    summ = dict(bot=a["bot"], job=a["job"], tag=tag, model=a["model"], status=a["final"], warning=warn, conversation_id=a["conv"] or None, start=a["start"], end=a["end"], tokens=tot, usd=usd, commit=commit)
    print("RUNSUMMARY " + json.dumps(summ, separators=(",", ":")) + " usage_json=" + up)
    notified = None; url = a["notify_url"]
    if url:
        import urllib.request, urllib.error
        secret = os.environ.get("CODEX_NOTIFY_SECRET") or os.environ.get("AGY_NOTIFY_SECRET")
        if not secret:
            sf = os.environ.get("CODEX_NOTIFY_SECRET_FILE") or os.environ.get("AGY_NOTIFY_SECRET_FILE")
            if sf:
                try: secret = open(sf).read().strip()
                except Exception: print("[codex-run] notify: cannot read secret file")
        hdr = os.environ.get("CODEX_NOTIFY_HEADER") or os.environ.get("AGY_NOTIFY_HEADER") or "X-Webhook-Secret"
        headers = {"Content-Type": "application/json"}
        if secret: headers[hdr] = secret
        body = json.dumps(dict(bot=a["bot"], job=a["job"], model=a["model"], status=a["final"], tokens=tot, cost_usd=usd, commit=commit,
                               log_path=os.path.join(out, "%s.a%d.jsonl" % (tag, attempt)), usage_json=up, warning=warn)).encode()
        for i in range(3):
            try:
                r = urllib.request.urlopen(urllib.request.Request(url, data=body, headers=headers, method="POST"), timeout=20); notified = "ok %d" % r.status; break
            except urllib.error.HTTPError as e: notified = "http %d" % e.code
            except Exception as e: notified = "error " + type(e).__name__
            if i < 2: time.sleep(5 * 3 ** i)
        m = re.match(r"(https?://[^/]+)", url)
        print("[codex-run] notify %s/... -> %s" % (m.group(1) if m else "?", notified))
    open(os.path.join(out, tag + ".done"), "w").write(json.dumps(dict(status=a["final"], finished=time.strftime("%Y-%m-%dT%H:%M:%S%z"), usage_json=up, notified=notified)) + "\n")

{"run": cmd_run, "analyze": cmd_analyze, "summary": cmd_summary}[sys.argv[1]]()
PYEOF

ts() { date '+%Y-%m-%d %H:%M:%S %z'; }
CONV=""; attempt=0; resumes=0; quota=0; ptres=0; FINAL=UNKNOWN; WARN=""
START_TS=$(ts)
while :; do
  attempt=$((attempt+1))
  LOG="$OUT/$TAG.a$attempt.jsonl"; ERR="$OUT/$TAG.a$attempt.err"; CLOG="$OUT/$TAG.a$attempt.cli.log"
  LM="$OUT/$TAG.a$attempt.last.txt"; SIN="$OUT/$TAG.a$attempt.stdin.txt"
  if [ -n "$CONV" ]; then printf '%s' "$CONT" > "$SIN"; else cp "$PROMPT" "$SIN"; fi
  args=(exec)
  [ -n "$CONV" ] && args+=(resume "$CONV")
  args+=(--json --ignore-user-config --color never --model "$MODEL" -c "approval_policy=\"$APPROVAL\"")
  if [ -n "$CONV" ]; then args+=(-c 'sandbox_mode="workspace-write"'); else args+=(--sandbox workspace-write -C "$WD"); fi
  [ -n "$EFFORT" ] && args+=(-c "model_reasoning_effort=\"$EFFORT\"")
  args+=(--output-last-message "$LM" -)
  echo "[codex-run] $(ts) attempt=$attempt model=$MODEL conv=${CONV:-new} approval=$APPROVAL log=$LOG"
  printf 'exe=%s cwd=%s\nargs=%s\n' "$CBIN" "$WD" "${args[*]}" > "$CLOG"
  LIMIT=0; SIM=0; OUTER=0
  if [ "$SIMDROP" -gt 0 ] && [ "$attempt" = 1 ]; then LIMIT=$SIMDROP; elif [ "$TMO" -gt 0 ]; then LIMIT=$((TMO+120)); fi
  python3 "$PY" run "$LIMIT" "$WD" "$SIN" "$LOG" "$ERR" -- "$CBIN" "${args[@]}"; rc=$?
  if [ "$rc" = 124 ] && [ "$LIMIT" -gt 0 ]; then
    if [ "$SIMDROP" -gt 0 ] && [ "$attempt" = 1 ]; then SIM=1; echo "[codex-run] TEST: simulated drop after ${SIMDROP}s"; else OUTER=1; echo "[codex-run] outer kill at print-timeout+120s"; fi
  fi
  if [ -s "$ERR" ]; then cat "$ERR" >> "$CLOG"; cat "$ERR" >> "$LOG"; fi   # stderr merged so classification and humans see it
  echo "EXIT $rc" >> "$LOG"; echo "EXIT $rc" >> "$CLOG"
  [ -e "$ERR" ] || : > "$ERR"
  eval "$(python3 "$PY" analyze "$LOG" "$LM" "$rc" "$SIM" "$OUTER" "$ERR")"
  [ -n "$NCONV" ] && CONV=$NCONV
  echo "[codex-run] $(ts) attempt=$attempt rc=$rc class=$CLS conv=$CONV"
  case "$CLS" in
    OK) FINAL=OK; break;;
    OK_STICKY) FINAL=OK; WARN='codex reported a failed turn but returned a completed turn and a final message'; break;;
    AUTH) FINAL=FAILED_AUTH; WARN='Codex is not signed in or the session expired. On this machine run: codex login   (or: codex login --device-auth)'; break;;
    NETWORK) if [ -z "$CONV" ] || [ "$resumes" -ge "$MAXRES" ]; then FINAL=FAILED_NETWORK; break; fi
             resumes=$((resumes+1)); s=$((10 * (1 << (resumes-1)) + RANDOM % 10)); echo "[codex-run] network drop; resume $resumes/$MAXRES in ${s}s"; sleep $s;;
    QUOTA) if [ -z "$CONV" ] || [ "$quota" -ge 4 ]; then FINAL=FAILED_QUOTA; break; fi
           s=$((60 * (1 << quota) + RANDOM % 15)); quota=$((quota+1)); echo "[codex-run] 429; backoff ${s}s then resume"; sleep $s;;
    PRINT_TIMEOUT) if [ -z "$CONV" ] || [ "$ptres" = 1 ]; then FINAL=FAILED_PRINT_TIMEOUT; break; fi
                   ptres=1; echo "[codex-run] print timeout; resuming once"; sleep 5;;
    *) FINAL="FAILED_$CLS"; break;;
  esac
done
END_TS=$(ts)
SUMARG=$(python3 -c '
import json,sys
k=["out","tag","attempt","final","bot","job","model","effort","workdir","head0","conv","start","end","warn","notify_url"]
d=dict(zip(k,sys.argv[1:])); d["attempt"]=int(d["attempt"]); print(json.dumps(d))' "$OUT" "$TAG" "$attempt" "$FINAL" "$BOT" "$JOB" "$MODEL" "$EFFORT" "$WD" "$HEAD0" "$CONV" "$START_TS" "$END_TS" "$WARN" "$NURL")
python3 "$PY" summary "$SUMARG"
if [ "$FINAL" = OK ]; then echo "EXIT 0"; exit 0; else echo "EXIT 1"; exit 1; fi
