#!/usr/bin/env bash
# agy-run - resilient headless agy runner for Linux and macOS (bash 3.2+, python3). See agy-run.md next to this file.
# Portable: no GNU-only flags (works with macOS BSD date/sed/mv); uses `timeout`/`gtimeout` only when present.
# - auto-resumes the SAME conversation (--conversation <id>) on network / context-summarization drops (up to -r times)
# - 429 / RESOURCE_EXHAUSTED: backoff 60s, 120s, 240s, ... then resume
# - print-timeout hit: resume once with a "continue from git state" prompt
# - status ERROR but full response (agy's sticky error after an internal retry) => success + warning
# - sums usage across attempts (from step usage when an attempt has no result event) -> <out>/<tag>.usage.json
# Usage: agy-run -t TAG -p PROMPT_FILE [-m MODEL] [-C WORKDIR] [-o OUTDIR] [-T PRINT_TIMEOUT_S] [-r MAX_RESUMES]
#                [-e EFFORT] [-n] [-b BOT] [-j JOB] [-u NOTIFY_URL]
#   -n  do NOT pass --dangerously-skip-permissions
#   -u  (or AGY_NOTIFY_URL) POST {bot,job,model,status,tokens,cost_usd,commit,log_path} when done (3 tries).
#       Secret header: value from AGY_NOTIFY_SECRET or file AGY_NOTIFY_SECRET_FILE, header name AGY_NOTIFY_HEADER
#       (default X-Webhook-Secret). The secret is never printed or logged. Unset URL => no POST.
# Default OUT is $HOME/agy-runs. Writes <out>/<tag>.usage.json and <out>/<tag>.done (marker) when finished.
# Last lines printed: "RUNSUMMARY {json}" and "EXIT <0|1>". Run it in the foreground of a background Shell.
set -uo pipefail
TAG=; MODEL=gemini-3.8-flash-medium; PROMPT=; WD=$PWD; OUT=; TMO=3600; MAXR=3; EFFORT=; SKIP=1
BOT=${AGY_BOT:-${USER:-unknown}}; JOB=; NOTIFY=${AGY_NOTIFY_URL:-}
while getopts t:m:p:C:o:T:r:e:b:j:u:nh o; do case $o in
  b) BOT=$OPTARG;; j) JOB=$OPTARG;; u) NOTIFY=$OPTARG;;
  t) TAG=$OPTARG;; m) MODEL=$OPTARG;; p) PROMPT=$OPTARG;; C) WD=$OPTARG;; o) OUT=$OPTARG;;
  T) TMO=$OPTARG;; r) MAXR=$OPTARG;; e) EFFORT=$OPTARG;; n) SKIP=0;;
  h|*) sed -n '2,18p' "$0"; exit 2;; esac; done
[ -n "$TAG" ] && [ -f "$PROMPT" ] || { echo "agy-run: need -t TAG and -p PROMPT_FILE (see -h)"; exit 2; }
command -v agy >/dev/null || { echo "agy-run: agy not on PATH"; exit 2; }
WD=$(cd "$WD" && pwd) || exit 2
JOB=${JOB:-$TAG}
HEAD0=$(git -C "$WD" rev-parse HEAD 2>/dev/null || true)
OUT=${OUT:-$HOME/agy-runs}; mkdir -p "$OUT"; rm -f "$OUT/$TAG.done" 2>/dev/null; OUT=$(cd "$OUT" && pwd)
# a reused tag: move the previous run's files aside so usage is not mixed
if ls "$OUT/$TAG".a*.jsonl >/dev/null 2>&1; then prev="$OUT/$TAG.prev-$(date +%Y%m%d-%H%M%S)"; mkdir -p "$prev"; mv "$OUT/$TAG".a*.* "$OUT/$TAG".usage.json "$prev"/ 2>/dev/null; echo "agy-run: previous $TAG files moved to $prev"; fi
export NODE_OPTIONS=${NODE_OPTIONS:---max-old-space-size=3072}
if [ "$TMO" != 0 ] && [ "$TMO" -lt 3600 ]; then echo "agy-run: warning: print-timeout ${TMO}s < 3600s"; fi
CONT_PROMPT='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.'
# test hook only: AGY_RUN_SIMULATE_DROP_AFTER=N kills attempt 1 after N s and treats it as a network drop
SIM=${AGY_RUN_SIMULATE_DROP_AFTER:-}

classify() { python3 - "$1" "$2" <<'PY'
import json,sys,re
f,sim=sys.argv[1],sys.argv[2]; txt=open(f,errors='replace').read(); res=None; cid=''
for l in txt.splitlines():
    if l.startswith('{"event":"init"'):
        try: cid=json.loads(l).get('conversation_id','')
        except Exception: pass
    if l.startswith('{"event":"result"'):
        try: res=json.loads(l)['result']; cid=res.get('conversation_id') or cid
        except Exception: pass
e=((res or {}).get('error') or '')+' '+' '.join(re.findall(r'^(?:AGY_ERROR|error:).*$',txt,re.M)); el=e.lower()
resp=(res or {}).get('response') or ''; fr=(res or {}).get('finished_reason') or ''
if sim=='1': c='NETWORK'
elif res and res.get('status')=='SUCCESS': c='OK'
elif res and resp.strip() and fr=='error' and 'summarization' not in el: c='OK_STICKY'
elif fr=='print_timeout' or 'print timeout' in el: c='PRINT_TIMEOUT'
elif 'resource_exhausted' in el or 'code 429' in el or ' 429' in el: c='QUOTA'
elif any(k in el for k in ('summarization','connection timed out','network issue','stream was interrupted','connection reset',' eof','i/o timeout','unavailable')): c='NETWORK'
elif 'not logged' in el or 'unauthenticated' in el or 'permission_denied' in el: c='AUTH'
elif 'interrupted' in el or not res: c='KILLED'
else: c='OTHER'
print(c, cid or '-')
PY
}

conv=; attempt=0; resumes=0; quota=0; ptresumed=0; final=UNKNOWN; warn=
START=$(date '+%F %T %Z')
while :; do
  attempt=$((attempt+1)); log="$OUT/$TAG.a$attempt.jsonl"; clog="$OUT/$TAG.a$attempt.cli.log"
  if [ -z "$conv" ]; then msg=$(cat "$PROMPT"); args=(); else msg=$CONT_PROMPT; args=(--conversation "$conv"); fi
  args+=(-p "$msg" --model "$MODEL" --output-format stream-json --print-timeout "${TMO}s" --log-file "$clog")
  [ "$SKIP" = 1 ] && args+=(--dangerously-skip-permissions)
  [ -n "$EFFORT" ] && args+=(--effort "$EFFORT")
  echo "[agy-run] $(date '+%F %T %Z') attempt=$attempt model=$MODEL conv=${conv:-new} log=$log"
  simflag=0
  outer=()   # outer kill = print-timeout + 120 s, if a timeout binary exists (Linux: timeout; macOS: brew install coreutils -> gtimeout)
  if [ "$TMO" != 0 ]; then
    if command -v timeout >/dev/null 2>&1; then outer=(timeout -k 30 $((TMO+120)))
    elif command -v gtimeout >/dev/null 2>&1; then outer=(gtimeout -k 30 $((TMO+120))); fi
  fi
  ( cd "$WD" && exec ${outer[@]+"${outer[@]}"} agy "${args[@]}" ) >"$log" 2>&1 &
  pid=$!
  if [ -n "$SIM" ] && [ $attempt = 1 ]; then
    for _ in $(seq "$SIM"); do sleep 1; kill -0 $pid 2>/dev/null || break; done
    if kill -0 $pid 2>/dev/null; then pkill -TERM -P $pid 2>/dev/null; kill -TERM $pid 2>/dev/null; simflag=1; echo "[agy-run] TEST: simulated drop after ${SIM}s"; fi
  fi
  wait $pid; rc=$?; echo "EXIT $rc" >>"$log"
  read -r cls cid < <(classify "$log" $simflag)
  [ "$cid" != "-" ] && conv=$cid
  echo "[agy-run] $(date '+%F %T %Z') attempt=$attempt rc=$rc class=$cls conv=${conv:-none}"
  case $cls in
    OK) final=OK; break;;
    OK_STICKY) final=OK; warn="agy reported status ERROR after an internal retry but returned a full response"; break;;
    NETWORK)
      if [ -z "$conv" ] || [ $resumes -ge "$MAXR" ]; then final=FAILED_NETWORK; break; fi
      resumes=$((resumes+1)); s=$(( 10 * (2 ** (resumes-1)) + RANDOM % 10 )); echo "[agy-run] network drop; resume $resumes/$MAXR in ${s}s"; sleep $s;;
    QUOTA)
      if [ -z "$conv" ] || [ $quota -ge 4 ]; then final=FAILED_QUOTA; break; fi
      s=$(( 60 * (2 ** quota) + RANDOM % 15 )); quota=$((quota+1)); echo "[agy-run] 429; backoff ${s}s then resume"; sleep $s;;
    PRINT_TIMEOUT)
      if [ -z "$conv" ] || [ $ptresumed -ge 1 ]; then final=FAILED_PRINT_TIMEOUT; break; fi
      ptresumed=1; echo "[agy-run] print timeout; resuming once"; sleep 5;;
    *) final="FAILED_$cls"; break;;
  esac
done
END=$(date '+%F %T %Z')
HEAD1=$(git -C "$WD" rev-parse HEAD 2>/dev/null || true)
AGY_RUN_WD="$WD" AGY_RUN_NOTIFY_URL="$NOTIFY" python3 - "$OUT" "$TAG" "$MODEL" "$final" "$attempt" "$conv" "$START" "$END" "$warn" "$BOT" "$JOB" "$HEAD0" "$HEAD1" <<'PY'
import json,sys,glob,re,os,time,datetime,urllib.request
out,tag,model,final,att,conv,start,end,warn,bot,job,head0,head1=sys.argv[1:]
# USD per 1M, GCP Standard global list price (as of Nov 16 2026); output includes thinking; scheduled changes by run date
today=datetime.date.today()
def price(m):
    if 'flash-lite' in m: return (0.30,0.03,2.50)
    if 'flash' in m: return (1.50,0.15,7.50) if today>=datetime.date(2027,1,1) else (0.75,0.075,3.75)
    if 'hydrogen' in m: return (1.50,0.075,7.50)
    if 'carbon' in m or 'argon' in m: return (4.0,0.20,20.0) if today>=datetime.date(2026,12,1) else (2.0,0.10,10.0)
    return (0.75,0.075,3.75)
pi,pc,po=price(model)
K=('input','cached','output','thinking')
def ru(x): return dict(input=x.get('input_tokens',0),cached=x.get('cache_read_tokens',0),output=x.get('output_tokens',0),thinking=x.get('thinking_tokens',0))
# agy result usage is CUMULATIVE for the conversation (a resumed attempt's result includes earlier attempts, even the
# in-flight request of a killed attempt). Step usage is per attempt but misses an in-flight request. So:
# attempt usage = result - running total if it has a result, else its step sums.
tot=dict.fromkeys(K,0); atts=[]; resp=''
for f in sorted(glob.glob(f'{out}/{tag}.a*.jsonl'), key=lambda x:int(re.search(r'\.a(\d+)\.jsonl$',x).group(1))):
    step=dict.fromkeys(K,0); res=None
    for l in open(f,errors='replace'):
        if l.startswith('{"event":"step_update"'):
            try: u=json.loads(l)['step_update'].get('usage')
            except Exception: u=None
            if u:
                for k,v in ru(u).items(): step[k]+=v
        elif l.startswith('{"event":"result"'):
            try: res=json.loads(l)['result']
            except Exception: pass
    if res and res.get('usage'):
        cum=ru(res['usage']); u={k:max(0,cum[k]-tot[k]) for k in K}
    else: u=step
    if res and res.get('response'): resp=res['response']
    for k in K: tot[k]+=u[k]
    atts.append(dict(log=f,usage=u,status=(res or {}).get('status','NO_RESULT'),error=((res or {}).get('error') or '')[:300]))
usd=(tot['input']*pi+tot['cached']*pc+(tot['output']+tot['thinking'])*po)/1e6
d=dict(tag=tag,model=model,status=final,warning=warn or None,conversation_id=conv or None,start=start,end=end,attempts=atts,
       tokens=tot,usd=round(usd,4),price_per_1m=dict(input=pi,cached=pc,output_thinking=po),note='GCP global list price; non-global endpoints +10%',
       response_tail=resp[-600:])
# commit: last 40-hex SHA in the final response, else new HEAD if it moved during the run
import subprocess
commit=None
kw=[m.group(1) for m in re.finditer(r'(?i)(?:sha|commit)[^0-9a-f\n]{0,40}\b([0-9a-f]{7,40})\b',resp)]
anyh=re.findall(r'\b[0-9a-f]{7,40}\b',resp)
for c in list(reversed(kw))+anyh:   # prefer the last 'SHA/commit: <hex>', else the first hex (git log is newest-first)
    if len(c)==40 and not os.environ.get('AGY_RUN_WD'): commit=c; break
    try:
        full=subprocess.run(['git','-C',os.environ.get('AGY_RUN_WD','.'),'rev-parse','--verify','-q',c+'^{commit}'],capture_output=True,text=True,timeout=10).stdout.strip()
        if full: commit=full; break
    except Exception: pass
if not commit and head1 and head1!=head0: commit=head1
d.update(bot=bot,job=job,commit=commit)
json.dump(d,open(f'{out}/{tag}.usage.json','w'),indent=1)
lastlog=atts[-1]['log'] if atts else None
print('RUNSUMMARY '+json.dumps({k:d[k] for k in ('bot','job','tag','model','status','warning','conversation_id','start','end','tokens','usd','commit')})+f' usage_json={out}/{tag}.usage.json')
url=os.environ.get('AGY_RUN_NOTIFY_URL','').strip(); notified=None
if url:
    body=json.dumps(dict(bot=bot,job=job,model=model,status=final,tokens=tot,cost_usd=d['usd'],commit=commit,log_path=lastlog,
                         usage_json=f'{out}/{tag}.usage.json',warning=warn or None)).encode()
    secret=os.environ.get('AGY_NOTIFY_SECRET','')
    sf=os.environ.get('AGY_NOTIFY_SECRET_FILE','')
    if not secret and sf:
        try: secret=open(sf).read().strip()
        except Exception as e: print(f'[agy-run] notify: cannot read secret file ({type(e).__name__})')
    hdr=os.environ.get('AGY_NOTIFY_HEADER','X-Webhook-Secret')
    for i in range(3):
        try:
            req=urllib.request.Request(url,data=body,method='POST',headers={'Content-Type':'application/json'})
            if secret: req.add_header(hdr,secret)
            with urllib.request.urlopen(req,timeout=20) as r: code=r.status
            if 200<=code<300: notified=f'ok {code}'; break
            notified=f'http {code}'
        except Exception as e:
            notified=f'error {type(e).__name__}'   # never include headers/secret
        time.sleep(5*(3**i))
    host=re.sub(r'^(https?://[^/]+).*$',r'\1',url)
    print(f'[agy-run] notify {host}/... -> {notified}')
with open(f'{out}/{tag}.done','w') as fh:
    fh.write(json.dumps(dict(status=final,finished=datetime.datetime.now().astimezone().isoformat(timespec='seconds'),usage_json=f'{out}/{tag}.usage.json',notified=notified))+'\n')
PY
case $final in OK) echo "EXIT 0";; *) echo "EXIT 1";; esac
