#!/bin/sh
# shellcheck disable=SC2250
set -u

# Resolve the real location of this script, following symlinks using only
# portable POSIX constructs (readlink without -f, case-based join). This works
# on stock macOS BSD and Linux without GNU coreutils.
#
# A bounded iteration count guards against pathological symlink cycles. In
# practice npm .bin links are single-hop, but a crafted or corrupt chain is
# rejected after MAX_SYMLINK_HOPS rather than looping indefinitely.
_llxprt_self=$0
_llxprt_hops=0
MAX_SYMLINK_HOPS=40
while [ -L "$_llxprt_self" ]; do
  _llxprt_hops=$((_llxprt_hops + 1))
  if [ "$_llxprt_hops" -gt "$MAX_SYMLINK_HOPS" ]; then
    printf '%s\n' 'LLxprt Code: symlink resolution exceeded maximum hops (possible cycle).' >&2
    printf '%s\n' "The symlink chain at $_llxprt_self may be cyclic or corrupt." >&2
    printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
    exit 43
  fi
  _llxprt_dir=$(dirname -- "$_llxprt_self")
  # On readlink failure (permission denied, dangling link, I/O error), emit an
  # actionable error and exit 43 immediately rather than preserving the same
  # symlink (which would spin MAX_SYMLINK_HOPS iterations). The hop bound
  # above still guards against cycles where readlink succeeds.
  if ! _llxprt_target=$(readlink -- "$_llxprt_self" 2>/dev/null); then
    printf '%s\n' 'LLxprt Code: could not resolve symlink (readlink failed).' >&2
    printf '%s\n' "The symlink at $_llxprt_self is broken, cyclic, or unreadable." >&2
    printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
    exit 43
  fi
  case "$_llxprt_target" in
    /*) _llxprt_self=$_llxprt_target ;;
    *)  _llxprt_self=$_llxprt_dir/$_llxprt_target ;;
  esac
done
_llxprt_script_dir=$(cd -- "$(dirname -- "$_llxprt_self")" 2>/dev/null && pwd) || \
  _llxprt_script_dir=$(dirname -- "$_llxprt_self")

# Read the pinned Bun dependency version and package name from this package's
# own package.json. When an exact pin is present, discovered Bun candidates are
# validated against this pin so an unrelated Bun (a different version) is
# rejected even if it lives inside an allowed boundary. A missing or unreadable
# candidate package.json/version is also rejected when a pin exists, so a
# partial install cannot silently fall through to an unrelated Bun.
_llxprt_pkg_json=$_llxprt_script_dir/../package.json
_llxprt_bun_pin=""
if [ -f "$_llxprt_pkg_json" ]; then
  _llxprt_bun_pin=$(sed -n 's/^[[:space:]]*"bun"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' -- "$_llxprt_pkg_json" 2>/dev/null | head -n1)
fi

# Derive the candidate bun package.json path from a bun binary path. The binary
# lives at .../bun/bin/bun.exe and its package.json is two dirs up
# (.../bun/package.json). Sets _llxprt_bun_pkg to the derived path and returns
# 0; returns 1 for layouts where the package.json cannot be derived.
_llxprt_derive_bun_pkg() {
  _llxprt_candidate=$1
  case "$_llxprt_candidate" in
    */bin/bun|*/bin/bun.exe)
      # .../bun/bin/bun.exe -> .../bun/package.json (two dirs up from binary)
      _llxprt_bun_pkg=$(dirname -- "$(dirname -- "$_llxprt_candidate")")/package.json
      return 0
      ;;
    *)
      # Unknown layout: cannot derive package.json.
      return 1
      ;;
  esac
}

# Check whether $_llxprt_bun_pin is an exact X.Y.Z version (with optional
# prerelease suffix). Returns 0 for an exact pin, 1 for a range/non-exact spec.
# This is stricter than a bare digit-leading glob: "1.x" and "1.3.14 - 2.0.0"
# start with a digit but are NOT exact versions and must not be treated as pins.
# A prerelease pin like "1.3.14-beta.1" IS an exact version and must be
# accepted so the strict version equality check is applied during Bun beta/rc
# testing cycles. The prerelease suffix (dash followed by dot-separated
# alphanumeric identifiers) is validated so ranges like "1.3.14-" or
# "1.3.14-alpha.." are still rejected.
_llxprt_is_exact_pin() {
  _llxprt_pin=$1
  _llxprt_prerelease=""
  _llxprt_has_prerelease=0
  # Split on the first dash to separate the core version from any prerelease
  # suffix (e.g. "1.3.14-beta.1" -> core="1.3.14", prerelease="beta.1").
  # A range like "1.x" or "^1.3.14" contains no dash and is handled below by
  # the core-only numeric check.
  case "$_llxprt_pin" in
    *-*)
      _llxprt_core=${_llxprt_pin%%-*}
      _llxprt_prerelease=${_llxprt_pin#*-}
      _llxprt_has_prerelease=1
      ;;
    *)
      _llxprt_core=$_llxprt_pin
      ;;
  esac
  # The core (before any dash) must be purely numeric with dots.
  case "$_llxprt_core" in
    *[!0-9.]*) return 1 ;;
    *) ;;
  esac
  # Must have exactly two dots (three numeric groups) in the core.
  _llxprt_rest=$_llxprt_core
  _llxprt_group=0
  while [ -n "$_llxprt_rest" ]; do
    _llxprt_part=${_llxprt_rest%%.*}
    case "$_llxprt_part" in
      ''|*[!0-9]*) return 1 ;;
      *) ;;
    esac
    _llxprt_group=$((_llxprt_group + 1))
    case "$_llxprt_rest" in
      *.*) _llxprt_rest=${_llxprt_rest#*.} ;;
      *) break ;;
    esac
  done
  [ "$_llxprt_group" -eq 3 ] || return 1
  # If a prerelease separator is present, validate its non-empty,
  # dot-separated identifiers (which may contain hyphens per semver).
  if [ "$_llxprt_has_prerelease" -eq 1 ]; then
    [ -n "$_llxprt_prerelease" ] || return 1
    case "$_llxprt_prerelease" in
      .*|*.|*..*) return 1 ;;
      *) ;;
    esac
    _llxprt_pre_rest=$_llxprt_prerelease
    while [ -n "$_llxprt_pre_rest" ]; do
      _llxprt_pre_part=${_llxprt_pre_rest%%.*}
      case "$_llxprt_pre_part" in
        ''|*[!A-Za-z0-9-]*) return 1 ;;
        *) ;;
      esac
      case "$_llxprt_pre_rest" in
        *.*) _llxprt_pre_rest=${_llxprt_pre_rest#*.} ;;
        *) break ;;
      esac
    done
  fi
  return 0
}

# Check whether a discovered Bun binary's version matches the dependency pin.
#
# When no exact pin is known (empty _llxprt_bun_pin or a range like "^1.3.14"),
# the boundary check is the primary defense and the candidate is accepted
# (return 0).
#
# When an exact pin IS known, the candidate's package.json version MUST be
# present and MUST match. A missing/unreadable package.json or missing version
# field is rejected (return 1) rather than accepted, so a partial or tampered
# install cannot bypass the pin. This is stricter than a mere advisory check.
_llxprt_bun_validates() {
  _llxprt_candidate=$1
  # No exact pin: accept (boundary check is the primary defense). A range
  # pin (e.g. "^1.3.14" or "1.x") is not exact, so we cannot compare equality.
  if [ -z "$_llxprt_bun_pin" ] || ! _llxprt_is_exact_pin "$_llxprt_bun_pin"; then
    return 0
  fi
  if ! _llxprt_derive_bun_pkg "$_llxprt_candidate"; then
    # Cannot derive package.json for this layout; reject under an exact pin.
    return 1
  fi
  if [ ! -f "$_llxprt_bun_pkg" ]; then
    # Candidate package.json missing: reject under an exact pin rather than
    # accept, so a partial install cannot bypass version verification.
    return 1
  fi
  _llxprt_found_ver=$(sed -n 's/^[[:space:]]*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' -- "$_llxprt_bun_pkg" 2>/dev/null | head -n1)
  # sed may succeed with exit 0 but print nothing (malformed JSON, binary
  # garbage, or a non-version manifest). Treat an empty extraction as a
  # rejection under exact-pin semantics — do NOT accept.
  if [ -z "$_llxprt_found_ver" ]; then
    # Version field missing/unreadable: reject under an exact pin.
    return 1
  fi
  [ "$_llxprt_found_ver" = "$_llxprt_bun_pin" ]
}

# Determine the package root (parent of the bin/ directory) and whether the
# package is installed under an enclosing node_modules directory. When installed
# (e.g. consumer/node_modules/@vybestack/llxprt-code/bin/llxprt), the enclosing
# node_modules boundary is honored and consumer ancestors are never climbed.
# When NOT under a node_modules (source workspace: packages/cli/bin/llxprt), a
# verified workspace-root fallback is used instead.
_llxprt_pkg_root=$(cd -- "$_llxprt_script_dir/.." 2>/dev/null && pwd) || \
  _llxprt_pkg_root=$_llxprt_script_dir/..

# Returns 0 if $_llxprt_pkg_root is nested under a directory literally named
# "node_modules" (an installed package), 1 otherwise. Sets
# _llxprt_enclosing_nm to the nearest enclosing node_modules path when found.
_llxprt_find_enclosing_nm() {
  _llxprt_search=$_llxprt_pkg_root
  _llxprt_enclosing_nm=""
  while [ "$_llxprt_search" != "/" ] && [ -n "$_llxprt_search" ]; do
    _llxprt_parent=$(dirname -- "$_llxprt_search")
    if [ "$(basename -- "$_llxprt_parent")" = "node_modules" ]; then
      _llxprt_enclosing_nm=$_llxprt_parent
      return 0
    fi
    _llxprt_search=$_llxprt_parent
  done
  return 1
}

# Verify a candidate repository root is the genuine llxprt-code workspace root
# for this package using canonical filesystem structure validation — NOT regex
# or grep scanning of arbitrary root JSON. Since the candidate root is derived
# deterministically as exactly three directories above this launcher
# (packages/<pkg>/bin/llxprt → packages/<pkg>/bin → packages/<pkg> → root), the
# canonical layout is verified structurally:
#   1. The candidate's package.json exists.
#   2. The canonical package path <candidate>/packages/<pkg> equals our pkg_root,
#      where <pkg> is derived from the launcher's own resolved location.
# No JSON content scanning is performed, so a crafted manifest cannot produce a
# false positive and no unescaped variable regex is needed. Sets
# _llxprt_ws_root on success.
_llxprt_verify_workspace_root() {
  _llxprt_candidate_root=$1
  _llxprt_root_manifest=$_llxprt_candidate_root/package.json
  if [ ! -f "$_llxprt_root_manifest" ]; then
    return 1
  fi
  # Canonical structural check: the candidate workspace root must contain this
  # launcher's package at packages/<name>, where <name> is derived from the
  # launcher's own resolved location (basename of the package dir one level
  # above this script's bin/ dir) instead of hardcoded. This lets the same
  # launcher run from packages/cli (the dev bin target) and from an installed
  # copy under node_modules. Both sides of the
  # comparison are canonicalized via cd && pwd so symlinked components,
  # redundant separators, or ./.. segments cannot cause a false mismatch.
  _llxprt_pkg_subdir=$(basename -- "$_llxprt_pkg_root")
  _llxprt_canonical_pkg=$(cd -- "$_llxprt_candidate_root/packages/$_llxprt_pkg_subdir" 2>/dev/null && pwd) || \
    _llxprt_canonical_pkg="$_llxprt_candidate_root/packages/$_llxprt_pkg_subdir"
  _llxprt_pkg_root_abs=$(cd -- "$_llxprt_pkg_root" 2>/dev/null && pwd) || \
    _llxprt_pkg_root_abs="$_llxprt_pkg_root"
  if [ "$_llxprt_pkg_root_abs" != "$_llxprt_canonical_pkg" ]; then
    return 1
  fi
  _llxprt_ws_root=$_llxprt_candidate_root
  return 0
}

_llxprt_kernel=$(uname -s 2>/dev/null || printf '%s' '')

# Entry precedence (issue #2999):
#   1. LLXPRT_FORCE_SOURCE_ENTRY=1 -> source index.ts (debug escape hatch)
#   2. prebuilt bundle (<pkg>/bundle/llxprt.js) if present
#   3. source index.ts
# Fallback to source is mandatory: dev checkouts and source runs have no bundle.
_llxprt_entry=""
if [ "${LLXPRT_FORCE_SOURCE_ENTRY:-0}" != "1" ] && \
   [ -f "$_llxprt_pkg_root/bundle/llxprt.js" ]; then
  _llxprt_entry="$_llxprt_pkg_root/bundle/llxprt.js"
fi
if [ -z "$_llxprt_entry" ]; then
  _llxprt_entry="$_llxprt_pkg_root/index.ts"
fi

# Fallback for layouts where the launcher does not sit inside the package that
# owns the entry point (for example a bin linked out of a nested node_modules
# tree). Walk up looking for @vybestack/llxprt-code, mirroring the win32
# launcher :find_main loop. _llxprt_pkg_root is left untouched; Bun resolution
# still keys off the launcher package root.
if [ ! -f "$_llxprt_entry" ]; then
  _llxprt_walk=$(cd -- "$_llxprt_pkg_root" 2>/dev/null && pwd) || _llxprt_walk=""
  # The walk MUST be bounded. POSIX permits pwd to report a leading "//" as a
  # distinct pathname, so `cd ..` from the root can alternate "/" -> "//" -> "/"
  # forever; comparing the parent against the current directory alone does not
  # terminate. Normalise a leading "//", stop explicitly at the root, and cap
  # the depth so a pathological filesystem can never hang the launcher.
  _llxprt_depth=0
  while [ -n "$_llxprt_walk" ] && [ "$_llxprt_depth" -lt 64 ]; do
    _llxprt_depth=$((_llxprt_depth + 1))
    _llxprt_main="$_llxprt_walk/node_modules/@vybestack/llxprt-code"
    # Honour the same entry precedence as above: a published install ships BOTH
    # bundle/llxprt.js and index.ts, so probing index.ts first would silently
    # run from source and bypass the prebuilt bundle.
    if [ "${LLXPRT_FORCE_SOURCE_ENTRY:-0}" != "1" ] && \
       [ -f "$_llxprt_main/bundle/llxprt.js" ]; then
      _llxprt_entry="$_llxprt_main/bundle/llxprt.js"
      break
    fi
    if [ -f "$_llxprt_main/index.ts" ]; then
      _llxprt_entry="$_llxprt_main/index.ts"
      break
    fi
    if [ "$_llxprt_walk" = "/" ]; then
      break
    fi
    _llxprt_parent=$(cd -- "$_llxprt_walk/.." 2>/dev/null && pwd) || _llxprt_parent=""
    while :; do
      case "$_llxprt_parent" in
        //*) _llxprt_parent="/${_llxprt_parent#//}" ;;
        *) break ;;
      esac
    done
    if [ -z "$_llxprt_parent" ] || [ "$_llxprt_parent" = "$_llxprt_walk" ]; then
      break
    fi
    _llxprt_walk="$_llxprt_parent"
  done
fi

# Issue #2978: the os-gated launcher package's own package.json carries no
# "bun" pin, so _llxprt_bun_pin above comes back empty and _llxprt_bun_validates
# would accept ANY executable @oven candidate without a version check. Recover
# the pin from the main package that actually declares it.
if [ -z "$_llxprt_bun_pin" ] && [ -n "$_llxprt_entry" ]; then
  _llxprt_main_pkg_json=$(dirname -- "$_llxprt_entry")/package.json
  if [ ! -f "$_llxprt_main_pkg_json" ]; then
    _llxprt_main_pkg_json=$(dirname -- "$(dirname -- "$_llxprt_entry")")/package.json
  fi
  if [ -f "$_llxprt_main_pkg_json" ]; then
    _llxprt_bun_pin=$(sed -n 's/^[[:space:]]*"bun"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' -- "$_llxprt_main_pkg_json" 2>/dev/null | head -n1)
  fi
fi

if [ ! -f "$_llxprt_entry" ]; then
  printf '%s
' 'LLxprt Code: entry point was not found.' >&2
  printf '%s
' "Expected: $_llxprt_entry" >&2
  printf '%s
' 'Your installation may be corrupt; reinstall @vybestack/llxprt-code.' >&2
  exit 43
fi

# Compares two dotted versions. Returns 0 when $1 >= $2, comparing only the
# numeric major.minor.patch core. A prerelease suffix is stripped rather than
# ordered (so "1.3.15-canary" counts as 1.3.15). That is deliberately generous:
# the floor exists to keep an ancient Bun out, not to enforce exact identity.
# A non-numeric component (e.g. a range pin such as "^1.3.14") returns 1, so an
# unparseable pin falls back to the bundled runtime rather than guessing.
_llxprt_version_ge() {
  _llxprt_v_have=${1%%-*}
  _llxprt_v_want=${2%%-*}
  _llxprt_v_field=0
  while [ "$_llxprt_v_field" -lt 3 ]; do
    _llxprt_v_h=${_llxprt_v_have%%.*}
    _llxprt_v_w=${_llxprt_v_want%%.*}
    case $_llxprt_v_h in
      ''|*[!0-9]*) return 1 ;;
      *) ;;
    esac
    case $_llxprt_v_w in
      ''|*[!0-9]*) return 1 ;;
      *) ;;
    esac
    if [ "$_llxprt_v_h" -gt "$_llxprt_v_w" ]; then
      return 0
    fi
    if [ "$_llxprt_v_h" -lt "$_llxprt_v_w" ]; then
      return 1
    fi
    case $_llxprt_v_have in
      *.*) _llxprt_v_have=${_llxprt_v_have#*.} ;;
      *) _llxprt_v_have=0 ;;
    esac
    case $_llxprt_v_want in
      *.*) _llxprt_v_want=${_llxprt_v_want#*.} ;;
      *) _llxprt_v_want=0 ;;
    esac
    _llxprt_v_field=$((_llxprt_v_field + 1))
  done
  return 0
}

# macOS only: prefer a Bun already on PATH when it meets the pinned version
# floor (issue #2962).
#
# Why: npm removes and re-extracts the whole package tree on every install,
# including the nested bun dependency, even when that dependency did not change.
# That unlinks the executable of every RUNNING session. On macOS an unlinked
# executable cannot be identified by securityd, which then cannot evaluate any
# Keychain item's ACL and falls back to a login-password prompt on every
# credential operation. Exec'ing a Bun that npm does not own removes the trigger.
#
# This knowingly relaxes the "never look at PATH" rule that governs the bundled
# resolution below. The trade is accepted: anyone who can write your PATH can
# already run code as you, and a successful `bun --version` proves the candidate
# is an executable, working Bun — a stronger check than the magic-byte
# inspection applied to the bundled binary. Linux and Windows are untouched;
# neither keys credential access on code identity, so neither has anything to
# gain here.
if [ "$_llxprt_kernel" = "Darwin" ] && [ -n "$_llxprt_bun_pin" ]; then
  if _llxprt_path_bun_version=$(bun --version 2>/dev/null) && \
     [ -n "$_llxprt_path_bun_version" ] && \
     _llxprt_version_ge "$_llxprt_path_bun_version" "$_llxprt_bun_pin"; then
    # Issue #3021: an ad-hoc or cdhash-only signed PATH Bun cannot satisfy the
    # identity-based macOS Keychain ACL, so every credential read degrades to a
    # login-password prompt that "Always Allow" cannot persist (#3020 sealed
    # change_acl with an empty application list). Inspect the designated
    # requirement of the exact binary selected and warn once per launch (not
    # once per credential read, which is the failure mode being described)
    # unless it carries
    # Oven's exact team-identity clause (certificate leaf[subject.OU] =
    # "7FRXF46ZSN"), which is the OU stored in the existing Keychain ACL. The
    # warning is advisory: a Bun that is ad-hoc signed or has no team identity
    # runs llxprt correctly except for Keychain access, and skipping it would
    # silently restore the npm-unlink failure mode #2962 exists to prevent.
    if _llxprt_path_bun_exe=$(command -v bun 2>/dev/null) && \
       [ -n "$_llxprt_path_bun_exe" ]; then
      # Suppress the warning only when codesign succeeds AND its output carries
      # Oven's exact team-identity clause. A failing codesign (unsigned binary,
      # or an error whose diagnostic merely echoes the clause), or a successful
      # inspection signed by any other team, must still warn — the Keychain ACL
      # stores Oven's OU (7FRXF46ZSN) and only a binary signed by that exact
      # team can satisfy it.
      _llxprt_has_team_id=0
      if _llxprt_dr=$(codesign -d --requirements - "$_llxprt_path_bun_exe" 2>&1); then
        case "$_llxprt_dr" in
          *certificate\ leaf\[subject.OU]\ =\ \"7FRXF46ZSN\"*) _llxprt_has_team_id=1 ;;
          *) ;;
        esac
      fi
      if [ "$_llxprt_has_team_id" -eq 0 ]; then
        printf '%s\n' 'LLxprt Code: the Bun on your PATH is ad-hoc signed or otherwise' >&2
        printf '%s\n' 'lacks a stable team identity, so it cannot hold a persistent macOS' >&2
        printf '%s\n' 'Keychain grant. You will be prompted for your login password on every' >&2
        printf '%s\n' 'credential read, and "Always Allow" will not persist (#3020).' >&2
        printf '%s\n' 'Install the official Bun release signed by Oven:' >&2
        printf '%s\n' '    brew uninstall bun && brew install oven-sh/bun/bun' >&2
        printf '%s\n' '    curl -fsSL https://bun.com/install | bash' >&2
      fi
    fi
    exec bun "$_llxprt_entry" "$@"
  fi
fi

# Resolve the bundled Bun runtime. Resolution is strictly bounded so an
# unrelated consumer Bun can never be accepted:
#
#   1. Package-local: <pkg>/node_modules/bun/bin/bun.exe
#   2. Hoisted (installed only): <enclosing-node_modules>/bun/bin/bun.exe
#   3. Workspace root (source workspace only): if the package is NOT under a
#      node_modules and the repository root two levels up is a verified
#      llxprt-code workspace (its manifest references this package), permit
#      only that verified root's node_modules/bun/bin/bun.exe.
#
# We deliberately do NOT scan .bin symlinks: resolving them portably without
# GNU readlink -f is unreliable, and the direct bun/bin/bun.exe paths are
# authoritative under both npm and Bun installers. We never generic-climb
# arbitrary ancestors.
_llxprt_bun=""

# Probe @oven/bun-<platform> variant binaries under the given node_modules
# directory. Sets _llxprt_bun to the first valid candidate found (and returns
# 0), or leaves it unchanged (and returns 1).
#
# IMPORTANT (issue #2978): This function performs host detection (uname,
# sysctl, grep /proc/cpuinfo, PowerShell on win32) and is called ONLY on the
# @oven fallback path — never when bun/bin/bun.exe was found — so a normal
# install does not fork detection subprocesses. The @oven tarballs contain
# only bin/bun[.exe] and NO scripts, so they materialize under npm v12's
# default-deny of install scripts.
#
# Variant ordering applies the deliberate musl-first deviation: on a musl host,
# musl variants are tried before glibc. Non-avx2 hosts never receive an avx2
# package (it crashes with SIGILL).
_llxprt_probe_oven() {
  _llxprt_po_nm=$1

  # Reuse the already-computed $_llxprt_kernel instead of forking uname -s a
  # second time. The glob labels below use a trailing star and a reordered
  # Windows alternative so they are textually distinct from the plain labels
  # in the magic-byte block further down, keeping source-structure tests that
  # locate that block by raw text working correctly.
  _llxprt_po_os=""
  case "$_llxprt_kernel" in
    Darwin*)  _llxprt_po_os=darwin ;;
    Linux*)   _llxprt_po_os=linux ;;
    FreeBSD*) _llxprt_po_os=freebsd ;;
    CYGWIN*|MINGW*|MSYS*) _llxprt_po_os=win32 ;;
    *) return 1 ;;
  esac

  _llxprt_po_arch=""
  case "$(uname -m 2>/dev/null || printf '%s' '')" in
    x86_64|amd64) _llxprt_po_arch=x64 ;;
    arm64|aarch64) _llxprt_po_arch=arm64 ;;
    *) return 1 ;;
  esac

  # Rosetta 2: darwin x64 under translation is treated as arm64.
  if [ "$_llxprt_po_os" = darwin ] && [ "$_llxprt_po_arch" = x64 ]; then
    if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || printf '%s' '')" = 1 ]; then
      _llxprt_po_arch=arm64
    fi
  fi

  # AVX2 detection (x64 only). Best-effort: on detection failure, assume
  # baseline (safe — a non-avx2 host must NEVER receive an avx2 package).
  _llxprt_po_avx2=0
  if [ "$_llxprt_po_arch" = x64 ]; then
    case "$_llxprt_po_os" in
      linux)
        if grep -q avx2 /proc/cpuinfo 2>/dev/null; then
          _llxprt_po_avx2=1
        fi
        ;;
      darwin)
        # machdep.cpu alone is the CPU *brand string* ("Intel(R) Core(TM)
        # i7-5557U CPU @ 3.10GHz"), which never contains feature names. The
        # flags live in machdep.cpu.features and machdep.cpu.leaf7_features
        # (AVX2 is a leaf7 feature).
        if sysctl -n machdep.cpu.features machdep.cpu.leaf7_features 2>/dev/null |
          grep -qi avx2; then
          _llxprt_po_avx2=1
        fi
        ;;
      win32)
        if powershell -NoProfile -Command "(Add-Type -MemberDefinition '[DllImport(\"kernel32.dll\")] public static extern bool IsProcessorFeaturePresent(int f);' -Name K -Namespace W -PassThru)::IsProcessorFeaturePresent(40)" 2>/dev/null | grep -qi 'True'; then
          _llxprt_po_avx2=1
        fi
        ;;
      # No probe for other kernels: leave avx2=0 so the baseline build is
      # chosen. An unknown OS is rejected by the candidate case below anyway.
      *) ;;
    esac
  fi

  # Ask the loader itself rather than probing for a distro marker file: musl is
  # used well beyond Alpine (Void musl, Gentoo musl profile, OpenWrt), and
  # mis-detecting it makes us order the glibc-linked @oven/bun-linux-* variants
  # first, which cannot load at all on a musl system. On musl, `ldd --version`
  # prints its usage banner (containing "musl") to stderr and exits non-zero,
  # so stderr is folded in and the pipeline's status comes from grep.
  _llxprt_po_musl=0
  if [ "$_llxprt_po_os" = linux ]; then
    if ldd --version 2>&1 | grep -qi musl; then
      _llxprt_po_musl=1
    elif [ -f /etc/alpine-release ]; then
      # Fallback for images with no ldd on PATH (busybox-only rootfs).
      _llxprt_po_musl=1
    fi
  fi

  # Build the ordered candidate list via positional parameters (set --).
  # This avoids word-splitting on unquoted variables (SC2086-safe).
  case "$_llxprt_po_os" in
    darwin)
      case "$_llxprt_po_arch" in
        arm64) set -- '@oven/bun-darwin-aarch64' ;;
        x64)
          if [ "$_llxprt_po_avx2" = 1 ]; then
            set -- '@oven/bun-darwin-x64' '@oven/bun-darwin-x64-baseline'
          else
            set -- '@oven/bun-darwin-x64-baseline'
          fi
          ;;
        *) return 1 ;;
      esac
      ;;
    linux)
      case "$_llxprt_po_arch" in
        arm64)
          if [ "$_llxprt_po_musl" = 1 ]; then
            set -- '@oven/bun-linux-aarch64-musl' '@oven/bun-linux-aarch64'
          else
            set -- '@oven/bun-linux-aarch64'
          fi
          ;;
        x64)
          if [ "$_llxprt_po_musl" = 1 ]; then
            if [ "$_llxprt_po_avx2" = 1 ]; then
              set -- '@oven/bun-linux-x64-musl' '@oven/bun-linux-x64-musl-baseline' '@oven/bun-linux-x64' '@oven/bun-linux-x64-baseline'
            else
              set -- '@oven/bun-linux-x64-musl-baseline' '@oven/bun-linux-x64-baseline'
            fi
          else
            if [ "$_llxprt_po_avx2" = 1 ]; then
              set -- '@oven/bun-linux-x64' '@oven/bun-linux-x64-baseline'
            else
              set -- '@oven/bun-linux-x64-baseline'
            fi
          fi
          ;;
        *) return 1 ;;
      esac
      ;;
    freebsd)
      case "$_llxprt_po_arch" in
        arm64) set -- '@oven/bun-freebsd-aarch64' ;;
        x64)   set -- '@oven/bun-freebsd-x64' ;;
        *) return 1 ;;
      esac
      ;;
    win32)
      case "$_llxprt_po_arch" in
        arm64) set -- '@oven/bun-windows-aarch64' ;;
        x64)
          if [ "$_llxprt_po_avx2" = 1 ]; then
            set -- '@oven/bun-windows-x64' '@oven/bun-windows-x64-baseline'
          else
            set -- '@oven/bun-windows-x64-baseline'
          fi
          ;;
        *) return 1 ;;
      esac
      ;;
    *) return 1 ;;
  esac

  # Determine exe name preference (platform-native first).
  if [ "$_llxprt_po_os" = win32 ]; then
    _llxprt_po_e1=bun.exe
    _llxprt_po_e2=bun
  else
    _llxprt_po_e1=bun
    _llxprt_po_e2=bun.exe
  fi

  # Probe each candidate variant in order, trying both exe names.
  for _llxprt_po_pkg do
    _llxprt_po_path="${_llxprt_po_nm}/${_llxprt_po_pkg}/bin/${_llxprt_po_e1}"
    if [ -x "$_llxprt_po_path" ] && _llxprt_bun_validates "$_llxprt_po_path"; then
      _llxprt_bun=$_llxprt_po_path
      return 0
    fi
    _llxprt_po_path="${_llxprt_po_nm}/${_llxprt_po_pkg}/bin/${_llxprt_po_e2}"
    if [ -x "$_llxprt_po_path" ] && _llxprt_bun_validates "$_llxprt_po_path"; then
      _llxprt_bun=$_llxprt_po_path
      return 0
    fi
  done
  return 1
}
# 1. Package-local Bun.
if [ -x "$_llxprt_pkg_root/node_modules/bun/bin/bun.exe" ] && \
   _llxprt_bun_validates "$_llxprt_pkg_root/node_modules/bun/bin/bun.exe"; then
  _llxprt_bun=$_llxprt_pkg_root/node_modules/bun/bin/bun.exe
fi

# 1b. @oven fallback (issue #2978): package-local @oven/bun-<platform> variant.
# Probed only when bun/bin/bun.exe was absent (npm v12 default-deny blocked
# bun's postinstall). Detection (uname, sysctl, /proc/cpuinfo) runs lazily
# inside _llxprt_probe_oven, never on a normal install.
if [ -z "$_llxprt_bun" ]; then
  _llxprt_probe_oven "$_llxprt_pkg_root/node_modules"
fi

# 2. Hoisted Bun within the enclosing node_modules (installed packages only).
if [ -z "$_llxprt_bun" ] && _llxprt_find_enclosing_nm; then
  if [ -x "$_llxprt_enclosing_nm/bun/bin/bun.exe" ] && \
     _llxprt_bun_validates "$_llxprt_enclosing_nm/bun/bin/bun.exe"; then
    _llxprt_bun=$_llxprt_enclosing_nm/bun/bin/bun.exe
  fi
  # 2b. @oven fallback: hoisted @oven variant within enclosing node_modules.
  if [ -z "$_llxprt_bun" ]; then
    _llxprt_probe_oven "$_llxprt_enclosing_nm"
  fi
fi

# 3. Workspace-root Bun (source workspace only). The package is NOT under a
#    node_modules; verify the repository root two levels up
#    (packages/cli -> packages -> repo-root) is a genuine workspace whose
#    manifest references this package, then accept only its node_modules/bun.
if [ -z "$_llxprt_bun" ] && ! _llxprt_find_enclosing_nm; then
  _llxprt_ws_candidate=$(cd -- "$_llxprt_pkg_root/../.." 2>/dev/null && pwd) || \
    _llxprt_ws_candidate=""
  if [ -n "$_llxprt_ws_candidate" ] && \
     _llxprt_verify_workspace_root "$_llxprt_ws_candidate" && \
     [ -x "$_llxprt_ws_root/node_modules/bun/bin/bun.exe" ] && \
     _llxprt_bun_validates "$_llxprt_ws_root/node_modules/bun/bin/bun.exe"; then
    _llxprt_bun=$_llxprt_ws_root/node_modules/bun/bin/bun.exe
  fi
  # 3b. @oven fallback: workspace-root @oven variant.
  if [ -z "$_llxprt_bun" ] && [ -n "${_llxprt_ws_root:-}" ]; then
    _llxprt_probe_oven "$_llxprt_ws_root/node_modules"
  fi
fi

if [ -z "$_llxprt_bun" ]; then
  printf '%s\n' 'LLxprt Code: bundled Bun runtime was not found.' >&2
  printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
  printf '%s\n' 'to restore the bundled Bun dependency, or visit https://bun.sh' >&2
  exit 43
fi

# Validate the Bun executable's native binary magic before exec. A bare exec
# on a corrupt/text file triggers the shell's ENOEXEC fallback, which silently
# interprets the file as a shell script — masking the corruption. Reading the
# first 4 bytes via `od` (portable -An -tx1 -N4 form) lets us reject non-native
# binaries with an actionable exit 43 without spawning Bun.
#
# Platform-gated format acceptance:
#   Darwin:  Mach-O only (feedface/feedfacf/cefaedfe/cffaedfe, fat cafebabe/bebafeca)
#   Linux:   ELF only (7f454c46)
#   MINGW/MSYS/CYGWIN: PE/COFF only (4d5a, "MZ") — Windows runs PE natively.
#
# Note: wrong-architecture vs wrong-format are distinct failure modes. This
# check validates the FORMAT (the OS can parse the container); it does NOT
# validate the architecture (e.g. arm64 vs x86_64). A wrong-architecture binary
# will be exec'd and fail with an OS error, which is a different, less common
# failure than a corrupt/text file. Architecture validation would require
# parsing the binary header (e.g. ELF e_machine or Mach-O cputype) and
# comparing against `uname -m`, which adds significant complexity for marginal
# gain; the format check covers the primary corruption vector.

# `od` is a POSIX-standard utility; verify it is available before relying on
# it. A missing or failing `od` is treated as a launcher runtime failure (exit
# 43) with a clear diagnostic rather than silently skipping the format check.
if ! command -v od >/dev/null 2>&1; then
  printf '%s\n' 'LLxprt Code: required tool "od" was not found on PATH.' >&2
  printf '%s\n' 'The launcher needs od to validate the bundled Bun binary format.' >&2
  printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
  printf '%s\n' 'to restore the bundled Bun dependency, or visit https://bun.sh' >&2
  exit 43
fi

# Capture od's combined stdout+stderr into a single read so we can detect a
# read failure (non-existent/unreadable file) separately from a successful
# read of an unrecognized format.
_llxprt_od_out=$(od -An -tx1 -N4 -- "$_llxprt_bun" 2>&1) || {
  # od itself failed (read error, I/O error). Treat as a launcher runtime
  # failure with a clear diagnostic.
  printf '%s\n' 'LLxprt Code: could not read bundled Bun binary to validate its format.' >&2
  printf '%s\n' "od reported: $_llxprt_od_out" >&2
  printf '%s\n' 'The bundled bun.exe may be corrupt, the wrong platform, or an unrecognized native format.' >&2
  printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
  printf '%s\n' 'to restore the bundled Bun dependency, or visit https://bun.sh' >&2
  exit 43
}
_llxprt_magic=$(printf '%s' "$_llxprt_od_out" | tr -d ' \n')

case "$_llxprt_kernel" in
  MINGW*|MSYS*|CYGWIN*)
    # Windows POSIX layer: only PE/COFF is accepted (the OS runs PE natively;
    # ELF and Mach-O would indicate a corrupt or wrong-platform install).
    case "$_llxprt_magic" in
      4d5a*) ;;
      *)
        printf '%s\n' 'LLxprt Code: bundled Bun runtime is not a usable native binary.' >&2
        printf '%s\n' 'The bundled bun.exe may be corrupt, the wrong platform, or an unrecognized native format.' >&2
        printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
        printf '%s\n' 'to restore the bundled Bun dependency, or visit https://bun.sh' >&2
        exit 43
        ;;
    esac
    ;;
  Darwin)
    # macOS: only Mach-O is accepted.
    case "$_llxprt_magic" in
      feedface|feedfacf|cefaedfe|cffaedfe|cafebabe|bebafeca) ;;
      *)
        printf '%s\n' 'LLxprt Code: bundled Bun runtime is not a usable native binary.' >&2
        printf '%s\n' 'The bundled bun.exe may be corrupt, the wrong platform, or an unrecognized native format.' >&2
        printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
        printf '%s\n' 'to restore the bundled Bun dependency, or visit https://bun.sh' >&2
        exit 43
        ;;
    esac
    ;;
  *)
    # Linux and other ELF systems: only ELF is accepted.
    case "$_llxprt_magic" in
      7f454c46) ;;
      *)
        printf '%s\n' 'LLxprt Code: bundled Bun runtime is not a usable native binary.' >&2
        printf '%s\n' 'The bundled bun.exe may be corrupt, the wrong platform, or an unrecognized native format.' >&2
        printf '%s\n' 'Reinstall the package with "npm install @vybestack/llxprt-code"' >&2
        printf '%s\n' 'to restore the bundled Bun dependency, or visit https://bun.sh' >&2
        exit 43
        ;;
    esac
    ;;
esac

exec "$_llxprt_bun" "$_llxprt_entry" "$@"
