FROM node:20-slim

# Install system dependencies
# chromium is the browser engine driven by agent-browser (apt pulls its headless libs).
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ffmpeg \
    ca-certificates \
    git \
    jq \
    python3 \
    python3-pip \
    build-essential \
    sudo \
    openssh-client \
    rsync \
    chromium \
    && rm -rf /var/lib/apt/lists/*

# Install Claude Code CLI
RUN curl -fsSL https://claude.ai/install.sh | sh || \
    npm install -g @anthropic-ai/claude-code

# Install OpenAI Codex CLI for the /codex backend
RUN npm install -g @openai/codex

# Browser automation for the agent: vercel-labs agent-browser (Rust CLI, token-efficient,
# replaces Playwright MCP). Installed at build time as root so the non-root runtime user
# doesn't hit EACCES on `npm install -g`. Chrome is pinned to the apt chromium binary so it
# lives outside the /data VOLUME (build-time writes to /data are discarded at runtime).
RUN npm install -g agent-browser
ENV AGENT_BROWSER_EXECUTABLE_PATH=/usr/bin/chromium

# Create non-root user (Claude Code refuses --dangerously-skip-permissions as root)
# node:20-slim already has uid/gid 1000 (node user). Create claudia with different IDs.
RUN groupadd -g 1001 claudia && useradd -u 1001 -g 1001 -m -d /data claudia

# Allow claudia to install packages at runtime without a password
RUN echo "claudia ALL=(ALL) NOPASSWD: /usr/bin/apt-get, /usr/bin/apt" > /etc/sudoers.d/claudia-apt && \
    chmod 0440 /etc/sudoers.d/claudia-apt

# Create app directory
WORKDIR /app

# Copy package files and install
COPY package*.json ./
RUN npm ci --production

# Copy app source
COPY . .

# Ensure app files are readable regardless of host file perms
RUN chmod -R a+rX /app

# Expose the open-claudia CLI on PATH so spawned agents can send files, manage tasks, etc.
RUN chmod +x /app/bin/cli.js && ln -s /app/bin/cli.js /usr/local/bin/open-claudia

# Let the runtime user overlay new source into /app for in-place /upgrade.
RUN chown -R claudia:claudia /app

# Entrypoint auto-configures from env vars on first run
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Set up data directory ownership
RUN mkdir -p /data/Workspace /data/.open-claudia /data/.claude && \
    chown -R claudia:claudia /data

# Config and data volume
ENV HOME=/data
ENV WEB_UI=true
ENV WEB_PORT=8080
VOLUME /data

EXPOSE 8080

# Switch to non-root user
USER 1001

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["node", "bin/cli.js", "web"]
