# Build stage
# Digest-pinned: integration_docker builds on the shared ECS pool, whose
# docker daemon image store persists across jobs — a co-resident job can
# retag a mutable base tag with a poisoned image, but a digest cannot be
# moved by `docker tag`. Bump the digest together with the tag.
# ratchet:docker.io/library/node:22-slim
FROM docker.io/library/node:22-slim@sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5 AS builder

# Optional apt mirror for the layer below. Empty keeps deb.debian.org, which is
# what release builds and local sandbox builds use; the E2E leg passes a
# regional mirror only on hosts where its probe found the default CDN path to be
# far slower (#16214).
ARG APT_MIRROR=

# Install build dependencies on the direct path graded by apt-mirror-probe.sh
# (clearing build-time proxy vars so apt never detours through an egress proxy).
RUN set -e; \
  unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY; \
  if [ -n "${APT_MIRROR}" ]; then \
    for sources in /etc/apt/sources.list /etc/apt/sources.list.d/debian.sources; do \
      if [ -f "${sources}" ]; then sed -i "s|deb.debian.org|${APT_MIRROR}|g" "${sources}"; fi; \
    done; \
  fi; \
  apt-get update && apt-get install -y --no-install-recommends \
  python3 \
  make \
  g++ \
  git \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*

# Set up npm global package folder
RUN mkdir -p /usr/local/share/npm-global
ENV NPM_CONFIG_PREFIX=/usr/local/share/npm-global
ENV PATH=$PATH:/usr/local/share/npm-global/bin

# Copy source code
COPY . /home/node/app
WORKDIR /home/node/app

# Optional build-time npm/corepack registry mirrors. Empty keeps the repo .npmrc
# default (https://registry.npmjs.org); declared as ARG (never ENV) so mirrors
# cannot leak into the published runtime image.
ARG NPM_CONFIG_REGISTRY=
ARG COREPACK_NPM_REGISTRY=

# Install dependencies, build workspaces, bundle into a single distributable, and pack.
# QWEN_SKIP_PREPARE=1 stops the install's prepare script from building and bundling —
# the explicit build and bundle steps below already do that.
# Corepack and pnpm mirrors are handled independently:
# - COREPACK_NPM_REGISTRY only governs corepack's download of pnpm itself; warming
#   `corepack pnpm --version` falls back without duplicating the package install.
# - pnpm 11 gives project .npmrc precedence over NPM_CONFIG_REGISTRY, so a mirror
#   override must be passed via --config.registry. Fall back to the default registry
#   (inheriting any build-time HTTP(S)_PROXY) only on registry/network fetch errors,
#   never on postinstall/lifecycle or lockfile failures.
RUN set -e; \
  if [ -n "${COREPACK_NPM_REGISTRY}" ]; then \
    if ! corepack pnpm --version >/dev/null 2>&1; then \
      echo "Warning: corepack via configured mirror failed; falling back to default registry" >&2; \
      unset COREPACK_NPM_REGISTRY; \
      corepack pnpm --version >/dev/null; \
    fi; \
  fi; \
  if [ -n "${NPM_CONFIG_REGISTRY}" ]; then \
    install_log="$(mktemp)"; \
    install_rc=0; \
    QWEN_SKIP_PREPARE=1 corepack pnpm --config.registry="${NPM_CONFIG_REGISTRY}" install --frozen-lockfile --reporter=append-only >"${install_log}" 2>&1 || install_rc=$?; \
    if [ "${install_rc}" -ne 0 ]; then \
      cat "${install_log}" >&2; \
      if ! grep -Eq 'ELIFECYCLE|ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL|ERR_PNPM_OUTDATED_LOCKFILE' "${install_log}" && \
         grep -Eq 'ERR_PNPM_(META_FETCH_FAIL|FETCH_[0-9]+|TARBALL_INTEGRITY|NO_MATCHING_VERSION)|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|EPIPE|EPROTO|socket hang up|FetchError|error \(23\)|HTTP status 5[0-9]{2}' "${install_log}"; then \
        rm -f "${install_log}"; \
        echo "Warning: pnpm install via configured registry mirror failed; falling back to default registry" >&2; \
        env -u NPM_CONFIG_REGISTRY -u npm_config_registry -u COREPACK_NPM_REGISTRY \
          QWEN_SKIP_PREPARE=1 corepack pnpm install --frozen-lockfile --reporter=append-only; \
      else \
        rm -f "${install_log}"; \
        exit "${install_rc}"; \
      fi; \
    else \
      cat "${install_log}"; \
      rm -f "${install_log}"; \
    fi; \
  else \
    QWEN_SKIP_PREPARE=1 corepack pnpm install --frozen-lockfile --reporter=append-only; \
  fi; \
  unset NPM_CONFIG_REGISTRY npm_config_registry COREPACK_NPM_REGISTRY; \
  npm run build; \
  npm run bundle; \
  npm run prepare:package; \
  cd dist; \
  npm pack

# Runtime stage
# Digest-pinned for the same reason as the builder stage above.
# ratchet:docker.io/library/node:22-slim
FROM docker.io/library/node:22-slim@sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5

ARG SANDBOX_NAME="qwen-code-sandbox"
ARG CLI_VERSION_ARG
# Same optional override as the builder stage: a stage cannot inherit an ARG
# declared before its own FROM.
ARG APT_MIRROR=
ENV SANDBOX="$SANDBOX_NAME"
ENV CLI_VERSION=$CLI_VERSION_ARG

# Install runtime dependencies on the direct path graded by apt-mirror-probe.sh.
RUN set -e; \
  unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY; \
  if [ -n "${APT_MIRROR}" ]; then \
    for sources in /etc/apt/sources.list /etc/apt/sources.list.d/debian.sources; do \
      if [ -f "${sources}" ]; then sed -i "s|deb.debian.org|${APT_MIRROR}|g" "${sources}"; fi; \
    done; \
  fi; \
  apt-get update && apt-get install -y --no-install-recommends \
  python3 \
  man-db \
  curl \
  dnsutils \
  less \
  jq \
  bc \
  gh \
  git \
  unzip \
  rsync \
  ripgrep \
  procps \
  psmisc \
  lsof \
  socat \
  ca-certificates \
  fonts-dejavu-core \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/*

# Set up npm global package folder
RUN mkdir -p /usr/local/share/npm-global
ENV NPM_CONFIG_PREFIX=/usr/local/share/npm-global
ENV PATH=$PATH:/usr/local/share/npm-global/bin

# Copy bundled package from builder stage
COPY --from=builder /home/node/app/dist/*.tgz /tmp/

# Same build-time-only registry override as the builder stage: a stage cannot
# inherit an ARG declared before its own FROM.
ARG NPM_CONFIG_REGISTRY=

# Install built packages globally
RUN set -e; \
  if [ -n "${NPM_CONFIG_REGISTRY}" ]; then \
    install_log="$(mktemp)"; \
    install_rc=0; \
    npm install -g --registry="${NPM_CONFIG_REGISTRY}" /tmp/*.tgz >"${install_log}" 2>&1 || install_rc=$?; \
    if [ "${install_rc}" -ne 0 ]; then \
      cat "${install_log}" >&2; \
      if ! grep -Eq 'npm (error|ERR!) code (ELIFECYCLE|EACCES|EPERM|ENOSPC)' "${install_log}" && \
         grep -Eq 'npm (error|ERR!) code (E4[0-9]{2}|E5[0-9]{2}|ETARGET|EINTEGRITY|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENOTFOUND|EPIPE|EPROTO|FETCH_ERROR)|HTTP 5[0-9]{2}|socket hang up|FetchError' "${install_log}"; then \
        rm -f "${install_log}"; \
        echo "Warning: npm install -g via configured registry mirror failed; falling back to default registry" >&2; \
        env -u NPM_CONFIG_REGISTRY -u npm_config_registry \
          npm install -g --registry=https://registry.npmjs.org /tmp/*.tgz; \
      else \
        rm -f "${install_log}"; \
        exit "${install_rc}"; \
      fi; \
    else \
      cat "${install_log}"; \
      rm -f "${install_log}"; \
    fi; \
  else \
    npm install -g /tmp/*.tgz; \
  fi; \
  unset NPM_CONFIG_REGISTRY npm_config_registry; \
  npm cache clean --force; \
  rm -rf /tmp/*.tgz

# Default entrypoint when none specified
CMD ["qwen"]
