FROM node:22-bookworm-slim AS frontend
RUN corepack enable && corepack prepare pnpm@latest --activate
WORKDIR /build

# Copy workspace root config
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./

# Copy packages needed for the inspector build chain:
#   inspector -> sandbox-agent SDK -> acp-http-client, cli-shared, persist-indexeddb
COPY sdks/typescript/ sdks/typescript/
COPY sdks/acp-http-client/ sdks/acp-http-client/
COPY sdks/cli-shared/ sdks/cli-shared/
COPY sdks/persist-indexeddb/ sdks/persist-indexeddb/
COPY sdks/react/ sdks/react/
COPY frontend/packages/inspector/ frontend/packages/inspector/
COPY docs/openapi.json docs/

# Create stub package.json for workspace packages referenced in pnpm-workspace.yaml
# but not needed for the inspector build (avoids install errors).
RUN set -e; for dir in \
      sdks/cli sdks/gigacode \
      sdks/persist-postgres sdks/persist-sqlite sdks/persist-rivet \
      resources/agent-schemas resources/vercel-ai-sdk-schemas \
      scripts/release scripts/sandbox-testing \
      examples/shared examples/docker examples/e2b examples/vercel \
      examples/daytona examples/cloudflare examples/file-system \
      examples/mcp examples/mcp-custom-tool \
      examples/skills examples/skills-custom-tool \
      frontend/packages/website; do \
      mkdir -p "$dir"; \
      printf '{"name":"@stub/%s","private":true,"version":"0.0.0"}\n' "$(basename "$dir")" > "$dir/package.json"; \
    done; \
    for parent in sdks/cli/platforms sdks/gigacode/platforms; do \
      for plat in darwin-arm64 darwin-x64 linux-arm64 linux-x64 win32-x64; do \
        mkdir -p "$parent/$plat"; \
        printf '{"name":"@stub/%s-%s","private":true,"version":"0.0.0"}\n' "$(basename "$parent")" "$plat" > "$parent/$plat/package.json"; \
      done; \
    done

RUN pnpm install --no-frozen-lockfile
ENV SKIP_OPENAPI_GEN=1
RUN pnpm --filter sandbox-agent build && \
    pnpm --filter @sandbox-agent/inspector build

FROM rust:1.88.0-bookworm AS builder
WORKDIR /build
COPY Cargo.toml Cargo.lock ./
COPY server/ ./server/
COPY gigacode/ ./gigacode/
COPY resources/agent-schemas/artifacts/ ./resources/agent-schemas/artifacts/
COPY scripts/agent-configs/ ./scripts/agent-configs/
COPY --from=frontend /build/frontend/packages/inspector/dist/ ./frontend/packages/inspector/dist/
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/usr/local/cargo/git \
    --mount=type=cache,target=/build/target \
    cargo build -p sandbox-agent --release && \
    cp target/release/sandbox-agent /sandbox-agent

FROM node:22-bookworm-slim
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends ca-certificates > /dev/null 2>&1 && \
    rm -rf /var/lib/apt/lists/*
COPY --from=builder /sandbox-agent /usr/local/bin/sandbox-agent
RUN sandbox-agent install-agent claude
