#!/usr/bin/env bash
# check-agent-framework.sh: offline, read-only checker for the malicious agent-framework 1.26.1 and 1.26.2 releases
# on PyPI (17 Nov 2026; no CVE). Pack 1.0.0 (18 Nov 2026). It opens no sockets, writes no files, never imports or runs
# Python and runs no program except find, tr, head, wc, awk and sort. It prints paths, line numbers and version
# numbers only; it never prints file content, so tokens in lockfiles, .pth files or listings are never shown.
#
# Usage: check-agent-framework.sh [--path DIR]... [--file FILE]... [--max-depth N]
#   --path DIR       a directory to walk (site-packages, a venv, a pipx, conda or uv tree, a project, a home folder or
#                    a mounted container image). Symlinked directories are not followed; .git folders are skipped.
#   --file FILE      one saved file to scan line by line: a lockfile, a requirements file, or a saved listing such as
#                    "pip freeze", "pip list", "conda list" or a file search. A *.pth file is checked for payload imports.
#   --max-depth N    how deep to walk under each --path (1 to 64, default 16)
#   At least one --path or --file is needed; each may be given up to 32 times.
#
# What it looks for (sources in README.md):
#   dist-info folders and wheel files for agent-framework 1.26.1 or 1.26.2; the payload files agent_framework_meta.pth,
#   agent_framework_meta/_telemetry.py (1.26.1), af_runtime_diag.pth and af_runtime_diag.py (1.26.2) and their compiled
#   copies; any .pth file that imports agent_framework_meta or af_runtime_diag; and, in requirements*.txt, *.in,
#   constraints*.txt, poetry.lock, uv.lock, Pipfile, Pipfile.lock, pdm.lock, pyproject.toml, pylock*.toml and
#   environment.yml files, pins, lock entries, listings and the sha256 of either malicious wheel.
#
# Exit codes:
#   0 NOT FOUND     nothing malicious found, and every agent-framework reference has an exact clean version
#   1               not used (reserved for unexpected runtime errors)
#   2 COMPROMISED   a malicious version, payload file, payload import or malicious wheel hash was found
#   3 REVIEW        an unpinned reference, a file too large or with lines too long to scan, or an unreadable folder
#                   or file, and nothing malicious found
#   5 USAGE OR READ ERROR
set -u
export LC_ALL=C

BAD_VERSIONS="1.26.1 1.26.2"
SAFE_VERSION="1.26.0"
WHEEL_SHA_1261="d27fa34414e6201d5e03e559ef634f020057554d7b3f4898dd5d7cd3e989e110"
WHEEL_SHA_1262="3d20a8bc91351a9a16b6db243b848ceca0206b7a8623b02d2af553a9c9f7e0a9"
WINDOW="17 Nov 2026, 20:35 to 21:17 GMT"
SRC="https://pypi.org/project/agent-framework/"
MAX_SMALL=8388608
MAX_LINE=8192
MAX_ARGS=32
MAX_SHOW=200

usage() {
  echo 'Usage: check-agent-framework.sh [--path DIR]... [--file FILE]... [--max-depth N]'
  echo 'Offline and read-only. Exit codes: 0 NOT FOUND, 2 COMPROMISED, 3 REVIEW, 5 USAGE OR READ ERROR (1 is not used).'
}
die() { echo "ERROR: $*"; exit 5; }
# shown PATH: printable ASCII only (each other byte becomes ?), at most 300 characters.
shown() { local s=${1//[^[:print:]]/?}; if [ "${#s}" -gt 300 ]; then s="${s:0:297}..."; fi; printf '%s' "$s"; }
lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }

PATHS=(); FILES=(); DEPTH=16
while [ $# -gt 0 ]; do
  case $1 in
    --path|-Path) [ $# -ge 2 ] || { usage; die "missing value for $1"; }; PATHS+=("$2"); shift 2 ;;
    --file|-File) [ $# -ge 2 ] || { usage; die "missing value for $1"; }; FILES+=("$2"); shift 2 ;;
    --max-depth|-MaxDepth) [ $# -ge 2 ] || { usage; die "missing value for $1"; }; DEPTH=$2; shift 2 ;;
    -h|--help|-Help) usage; exit 5 ;;
    *) usage; die "unknown option: $(shown "$1")" ;;
  esac
done
[ "${#PATHS[@]}" -gt 0 ] || [ "${#FILES[@]}" -gt 0 ] || { usage; die "give at least one --path or --file"; }
{ [ "${#PATHS[@]}" -le "$MAX_ARGS" ] && [ "${#FILES[@]}" -le "$MAX_ARGS" ]; } || die "at most $MAX_ARGS --path and $MAX_ARGS --file values"
{ [[ "$DEPTH" =~ ^[0-9]{1,2}$ ]] && [ "$((10#$DEPTH))" -ge 1 ] && [ "$((10#$DEPTH))" -le 64 ]; } || die "--max-depth must be 1 to 64"
DEPTH=$((10#$DEPTH))
for p in "${PATHS[@]+"${PATHS[@]}"}"; do { [ -d "$p" ] && [ -r "$p" ] && [ -x "$p" ]; } || die "not a readable directory: $(shown "$p")"; done
for f in "${FILES[@]+"${FILES[@]}"}"; do { [ -f "$f" ] && [ -r "$f" ]; } || die "file not found or unreadable: $(shown "$f")"; done

# The line scanner. Input: file text (NUL already turned into a line break). Output records: KIND<TAB>LINE<TAB>DETAIL.
# It uses no system(), no getline and no output redirection.
# shellcheck disable=SC2016  # awk program, intentionally literal
AWK_SCAN='
function norm(v) { sub(/^v/, "", v); sub(/\+.*$/, "", v); while (v ~ /\.0$/ && dots(v) > 2) v = substr(v, 1, length(v) - 2); return v }
function dots(v,   n, i) { n = 0; for (i = 1; i <= length(v); i++) if (substr(v, i, 1) == ".") n++; return n }
function isbad(v) { v = norm(v); return (v == "1.26.1" || v == "1.26.2") }
function vtok(s) { if (match(s, /^[0-9][0-9a-z.!+*]*/)) return substr(s, 1, RLENGTH); return "" }
function verdict(kind, v) {
  if (v == "" || index(v, "*") > 0) { if (!ref) ref = NR; return }
  if (isbad(v)) { print "FOUND\t" NR "\t" kind "\t" norm(v); found++ } else if (!clean) { clean = NR; cleanv = v; cleank = kind }
}
# nameat(s): position just after the first agent-framework name with clean edges in s, or 0.
function nameat(s,   off, t, b, a) {
  off = 0; t = s
  while (match(t, /agent[-_.]framework/)) {
    b = (off + RSTART == 1) ? "" : substr(s, off + RSTART - 1, 1)
    a = substr(s, off + RSTART + RLENGTH, 1)
    if (b !~ /[a-z0-9_.-]/ && a !~ /[a-z0-9_.-]/) return off + RSTART + RLENGTH
    off = off + RSTART; t = substr(s, off + 1)
  }
  return 0
}
BEGIN { found = 0; clean = 0; ref = 0; long = 0; pend = 0 }
{
  sub(/\r$/, "")
  if (length($0) > maxline) { long++; next }
  l = tolower($0)
  if (mode == "pth") {
    if (l ~ /^[ \t]*import[ \t]/) {
      if (index(l, "agent_framework_meta")) { print "FOUND\t" NR "\tpthimport\tagent_framework_meta"; found++ }
      else if (index(l, "af_runtime_diag")) { print "FOUND\t" NR "\tpthimport\taf_runtime_diag"; found++ }
    }
    next
  }
  if (l ~ /^[ \t]*#/) next
  if (index(l, h1)) { print "FOUND\t" NR "\thash\t1.26.1"; found++; next }
  if (index(l, h2)) { print "FOUND\t" NR "\thash\t1.26.2"; found++; next }
  if (index(l, "agent_framework_meta.pth")) { print "FOUND\t" NR "\tiocname\tagent_framework_meta.pth"; found++; next }
  if (index(l, "af_runtime_diag.pth")) { print "FOUND\t" NR "\tiocname\taf_runtime_diag.pth"; found++; next }
  if (index(l, "af_runtime_diag.py")) { print "FOUND\t" NR "\tiocname\taf_runtime_diag.py"; found++; next }
  if (index(l, "agent_framework_meta/_telemetry.py") || index(l, "agent_framework_meta\\_telemetry.py")) { print "FOUND\t" NR "\tiocname\tagent_framework_meta/_telemetry.py"; found++; next }
  if (match(l, /agent[-_.]framework-1\.26\.[12](\.0)*(\.dist-info|-py|\.tar\.gz)/)) {
    b = (RSTART == 1) ? "" : substr(l, RSTART - 1, 1)
    if (b !~ /[a-z0-9_.-]/) { print "FOUND\t" NR "\tdistname\t1.26." substr(l, RSTART + 21, 1); found++; next }
  }
  if (l ~ /^[ \t]*name[ \t]*=[ \t]*"agent[-_.]framework"[ \t]*$/ || l ~ /^[ \t]*"agent[-_.]framework"[ \t]*:[ \t]*\{/ || l ~ /^name:[ \t]*agent[-_.]framework[ \t]*$/) { pend = 1; next }
  if (pend) {
    if (match(l, /^[ \t]*"?version"?[ \t]*[=:][ \t]*"?(==)?/)) { pend = 0; verdict("lock entry", vtok(substr(l, RSTART + RLENGTH))); next }
    if (l ~ /^[ \t]*[[}]/) { pend = 0; next }
  }
  p = nameat(l)
  if (!p) next
  r = substr(l, p)
  if (match(r, /^\[[^]]*\]/)) r = substr(r, RLENGTH + 1)
  if (match(r, /^[ \t]*===?[ \t]*v?/)) { verdict("pin", vtok(substr(r, RLENGTH + 1))); next }
  if (match(r, /^["\047]?[ \t]*=[ \t]*["\047](===?)?v?/)) { verdict("pin", vtok(substr(r, RLENGTH + 1))); next }
  if (match(r, /^"[ \t]*,[ \t]*specifier[ \t]*=[ \t]*"===?/)) { verdict("pin", vtok(substr(r, RLENGTH + 1))); next }
  if (match(r, /^[ \t]+v?[0-9]/)) { q = RLENGTH; v = vtok(substr(r, q)); a = substr(r, q + length(v), 1); if (a == "" || a == " " || a == "\t") { verdict("listing", v); next } }
  if (!ref) ref = NR
}
END {
  if (!found && clean) print "CLEAN\t" clean "\t" cleank "\t" cleanv
  if (!found && !clean && ref) print "REF\t" ref "\tref\t-"
  if (!found && long) print "LONG\t0\tlong\t" long
}'

REC=()        # each entry: sort key, a tab, then the message
NFOUND=0; NREVIEW=0; NCLEAN=0; NREAD=0; NUNREAD=0; NENTRIES=0; NCAND=0
add() { # level path line message
  local k
  printf -v k '%s\t%08d\t%s %s%s: %s' "$(shown "$2")" "$3" "$1" "$(shown "$2")" "$([ "$3" -gt 0 ] && printf ' line %d' "$3")" "$4"
  REC+=("$k")
  case $1 in FOUND) NFOUND=$((NFOUND + 1)) ;; REVIEW) NREVIEW=$((NREVIEW + 1)) ;; CLEAN) NCLEAN=$((NCLEAN + 1)) ;; esac
}
# scan_file PATH MODE(generic|pth) EXPLICIT(1|0)
scan_file() {
  local f=$1 mode=$2 explicit=$3 sz kind line det val out
  if [ ! -r "$f" ] || ! sz=$(head -c "$((MAX_SMALL + 1))" < "$f" 2>/dev/null | wc -c); then
    if [ "$explicit" = 1 ]; then die "file unreadable: $(shown "$f")"; fi
    NUNREAD=$((NUNREAD + 1)); add REVIEW "$f" 0 "could not be read"; return
  fi
  if [ "$sz" -gt "$MAX_SMALL" ]; then
    if [ "$explicit" = 1 ]; then die "file too large (over $MAX_SMALL bytes): $(shown "$f")"; fi
    add REVIEW "$f" 0 "too large to scan (over $MAX_SMALL bytes)"; return
  fi
  NREAD=$((NREAD + 1))
  out=$(head -c "$MAX_SMALL" < "$f" | tr '\000' '\n' | awk -v mode="$mode" -v maxline="$MAX_LINE" -v h1="$WHEEL_SHA_1261" -v h2="$WHEEL_SHA_1262" "$AWK_SCAN")
  while IFS=$'\t' read -r kind line det val; do
    [ -n "$kind" ] || continue
    case "$kind:$det" in
      FOUND:hash) add FOUND "$f" "$line" "sha256 of the malicious agent-framework $val wheel" ;;
      FOUND:iocname) add FOUND "$f" "$line" "names the payload file $val" ;;
      FOUND:distname) add FOUND "$f" "$line" "names a malicious agent-framework $val wheel or dist-info" ;;
      FOUND:pthimport) add FOUND "$f" "$line" "startup hook imports the payload module $val" ;;
      FOUND:*) add FOUND "$f" "$line" "$det for malicious agent-framework $val" ;;
      CLEAN:*) add CLEAN "$f" "$line" "agent-framework $val ($det), not a malicious version" ;;
      REF:*) add REVIEW "$f" "$line" "names agent-framework without an exact version; check what it resolved to ($WINDOW)" ;;
      LONG:*) add REVIEW "$f" 0 "$val line(s) over $MAX_LINE bytes were not scanned" ;;
    esac
  done <<< "$out"
}
is_lockname() {
  case $1 in
    requirements*.txt|requirements*.in|constraints*.txt|poetry.lock|uv.lock|pipfile|pipfile.lock|pdm.lock|pyproject.toml|pylock*.toml|environment.yml|environment.yaml) return 0 ;;
  esac
  return 1
}
walk() {
  local root=$1 e b lb parent gparent n ver errs
  n=$(find "$root" -mindepth 1 -maxdepth "$DEPTH" -name .git -prune -o -print0 2>/dev/null | tr -dc '\000' | wc -c)
  NENTRIES=$((NENTRIES + n))
  errs=$(find "$root" -mindepth 1 -maxdepth "$DEPTH" -name .git -prune -o -print0 2>&1 >/dev/null | tr -cd '\n' | wc -c)
  while IFS= read -r -d '' e; do
    NCAND=$((NCAND + 1))
    b=${e##*/}; lb=$(lower "$b"); parent=${e%/*}; parent=$(lower "${parent##*/}"); gparent=${e%/*}; gparent=${gparent%/*}; gparent=$(lower "${gparent##*/}")
    case $lb in
      agent_framework_meta.pth) add FOUND "$e" 0 "1.26.1 payload startup hook (agent_framework_meta.pth)" ;;
      af_runtime_diag.pth) add FOUND "$e" 0 "1.26.2 payload startup hook (af_runtime_diag.pth)" ;;
      af_runtime_diag.py) add FOUND "$e" 0 "1.26.2 payload module (af_runtime_diag.py)" ;;
      af_runtime_diag.*.pyc) add FOUND "$e" 0 "compiled 1.26.2 payload module (Python imported it at least once)" ;;
      _telemetry.py) if [ "$parent" = agent_framework_meta ]; then add FOUND "$e" 0 "1.26.1 payload module (agent_framework_meta/_telemetry.py)"; fi ;;
      _telemetry.*.pyc) if [ "$parent" = __pycache__ ] && [ "$gparent" = agent_framework_meta ]; then add FOUND "$e" 0 "compiled 1.26.1 payload module (Python imported it at least once)"; fi ;;
    esac
    if [[ "$lb" =~ ^agent[-_.]framework-([0-9][0-9a-z.!+]*)\.dist-info$ ]]; then
      ver=${BASH_REMATCH[1]}
      if is_bad "$ver"; then add FOUND "$e" 0 "dist-info for malicious agent-framework $(normv "$ver")"; else add CLEAN "$e" 0 "agent-framework $ver installed (dist-info), not a malicious version"; fi
    elif [[ "$lb" =~ ^agent[-_.]framework-([0-9][0-9a-z.!+]*)-[^-]+-[^-]+-[^-]+\.whl$ ]]; then
      ver=${BASH_REMATCH[1]}
      if is_bad "$ver"; then add FOUND "$e" 0 "wheel file for malicious agent-framework $(normv "$ver")"; fi
    fi
    if [ -f "$e" ] && [ ! -L "$e" ]; then
      if [[ "$lb" == *.pth ]]; then scan_file "$e" pth 0
      elif is_lockname "$lb"; then scan_file "$e" generic 0; fi
    fi
  done < <(find "$root" -mindepth 1 -maxdepth "$DEPTH" -name .git -prune -o \( -iname '*.pth' -o -iname '*.dist-info' -o -iname '*.whl' \
      -o -iname 'af_runtime_diag*' -o -iname '_telemetry*' -o -iname 'requirements*.txt' -o -iname 'requirements*.in' \
      -o -iname 'constraints*.txt' -o -iname poetry.lock -o -iname uv.lock -o -iname Pipfile -o -iname Pipfile.lock \
      -o -iname pdm.lock -o -iname pyproject.toml -o -iname 'pylock*.toml' -o -iname 'environment.y*ml' \) -print0 2>/dev/null)
  if [ "$errs" -gt 0 ]; then NUNREAD=$((NUNREAD + errs)); add REVIEW "$root" 0 "$errs folder(s) under this path could not be read, so the walk is incomplete"; fi
}
normv() { local v=${1#v}; v=${v%%+*}; while [[ "$v" == *.0 ]] && [ "$(printf '%s' "$v" | tr -cd . | wc -c)" -gt 2 ]; do v=${v%.0}; done; printf '%s' "$v"; }
is_bad() { local v; v=$(normv "$1"); [ "$v" = 1.26.1 ] || [ "$v" = 1.26.2 ]; }

echo "agent-framework PyPI compromise check (pack 1.0.0). Malicious: $BAD_VERSIONS. Last clean release: $SAFE_VERSION. Source: $SRC"
for p in "${PATHS[@]+"${PATHS[@]}"}"; do walk "$p"; done
for f in "${FILES[@]+"${FILES[@]}"}"; do
  lb=$(lower "${f##*/}")
  if [[ "$lb" == *.pth ]]; then scan_file "$f" pth 1; else scan_file "$f" generic 1; fi
done
shownum=0
if [ "${#REC[@]}" -gt 0 ]; then
  while IFS= read -r r; do
    shownum=$((shownum + 1)); [ "$shownum" -le "$MAX_SHOW" ] && printf '%s\n' "${r#*$'\t'*$'\t'}"
  done < <(printf '%s\n' "${REC[@]}" | sort)
fi
[ "$shownum" -gt "$MAX_SHOW" ] && echo "NOTE: only the first $MAX_SHOW of $shownum results are shown"
echo "SUMMARY: paths ${#PATHS[@]}, files ${#FILES[@]}, entries walked $NENTRIES, candidates $NCAND, files read $NREAD, unreadable $NUNREAD"
echo "RESULT: found $NFOUND, review $NREVIEW, clean $NCLEAN"
if [ "$NFOUND" -gt 0 ]; then
  echo "NEXT: treat each host, runner or image above as exposed: isolate it, rebuild it from a clean source with agent-framework==$SAFE_VERSION pinned by hash, and rotate every credential it held from a clean system (README, OUR ADVICE)"
  echo "OVERALL: COMPROMISED (exit 2)"; exit 2
elif [ "$NREVIEW" -gt 0 ]; then
  echo "OVERALL: REVIEW (exit 3)"; exit 3
fi
echo "OVERALL: NOT FOUND (exit 0)"; exit 0
