# yaml-language-server: $schema=https://schema.zeabur.app/template.json
apiVersion: zeabur.com/v1
kind: Template
metadata:
    name: OpenAB Grok
spec:
    description: |
        Open Agent Broker — a lightweight Rust harness that bridges Discord and Slack to any ACP-compatible coding CLI over stdio JSON-RPC. This template uses Grok Build (xAI's official coding agent CLI) as the backend via `grok agent stdio`.
        Source: https://github.com/openabdev/openab
    coverImage: https://cdn-console.zeabur.com/f/Xp0H6/openab-cover.webp
    icon: https://cdn-console.zeabur.com/f/0Ewi6/openab-icon.webp
    variables:
        - key: DISCORD_BOT_TOKEN
          type: STRING
          name: Discord Bot Token
          description: Token from https://discord.com/developers/applications
        - key: OPENAB_ALLOWED_CHANNELS
          type: STRING
          name: Discord Channel IDs (optional)
          description: 'Optional. Comma-separated Discord channel IDs where the bot listens. Leave empty to allow all channels. Example: 123456789012345678,234567890123456789'
        - key: OPENAB_ALLOWED_USERS
          type: STRING
          name: Discord User IDs (optional)
          description: Optional. Comma-separated Discord user IDs allowed to interact with the bot. Leave empty to allow everyone in the allowed channels.
        - key: OPENAB_TRUSTED_BOT_IDS
          type: STRING
          name: Trusted Bot IDs (optional)
          description: Optional. Comma-separated Discord bot IDs trusted to send messages to this bot. Leave empty to trust all bots (default). Only applies when Allow Bot Messages is set.
        - key: OPENAB_ALLOW_BOT_MESSAGES
          type: STRING
          name: Allow Bot Messages (optional)
          description: Optional. Set to 'on' to allow messages from bots/webhooks to trigger the agent. Leave empty to disable (default).
        - key: GROK_CODE_XAI_API_KEY
          type: STRING
          name: Grok / xAI API Key (optional)
          description: Optional. xAI API key (xai-...) from https://console.x.ai/. Leave empty to authenticate via device flow after deployment (SuperGrok subscription) or to use a deployment key set later in the Dashboard.
        - key: SLACK_BOT_TOKEN
          type: STRING
          name: Slack Bot Token (optional)
          description: Optional. Bot User OAuth Token (xoxb-...) from Slack App settings. Leave empty to disable Slack adapter.
        - key: SLACK_APP_TOKEN
          type: STRING
          name: Slack App Token (optional)
          description: Optional. App-Level Token (xapp-...) for Socket Mode. Required when Slack Bot Token is set.
        - key: OPENAB_MAX_SESSIONS
          type: STRING
          name: Max Concurrent Sessions (optional)
          description: 'Optional. Maximum number of concurrent agent sessions (default: 10). Oldest idle session is evicted when the limit is reached.'
    tags:
        - AI
        - Developer Tools
        - Discord
        - Slack
    readme: "# OpenAB Grok\n\n[OpenAB](https://github.com/openabdev/openab) is a lightweight, open-source Rust harness that bridges Discord and Slack to any [Agent Client Protocol](https://github.com/anthropics/agent-protocol)-compatible coding CLI over stdio JSON-RPC.\n\nThis template runs the Grok variant — it uses [Grok Build](https://x.ai/news/grok-build-cli), xAI's official coding agent CLI, as the backend via `grok agent stdio`.\n\n## Important Notes\n\n- **Image tag:** This template uses a pinned version (`0.8.3-beta.11`). To upgrade, change the image tag in Zeabur Dashboard → Service → Settings. Available tags: [GitHub Packages](https://github.com/openabdev/openab/pkgs/container/openab-grok).\n- **Persistent storage:** `/home/agent` is mounted as a persistent volume. Grok credentials (`~/.grok/auth.json`), settings, and config survive restarts.\n\n## Setup\n\n### 1. Get a Discord Bot Token\n\n1. Go to https://discord.com/developers/applications and click **New Application**\n2. Navigate to **Bot** tab → click **Reset Token** → copy the token\n3. On the same page, scroll down and enable **Message Content Intent** under Privileged Gateway Intents\n4. Go to **OAuth2 → URL Generator** → check scope `bot` → check permissions: Send Messages, Send Messages in Threads, Create Public Threads, Read Message History, Add Reactions, Manage Messages\n5. Copy the generated URL and open it in your browser to invite the bot to your server\n\n### 2. Get Discord Channel IDs\n\n1. Open Discord → go to **User Settings** (gear icon) → **Advanced** → enable **Developer Mode**\n2. Right-click the channel where you want the bot to respond → **Copy Channel ID**\n3. For multiple channels, separate IDs with commas: `123456789012345678,234567890123456789`\n\n### 3. Choose an Auth Method\n\nGrok Build supports three credential sources. Pick whichever fits your use case.\n\n| Method | When to use | How |\n|--------|-------------|-----|\n| **API Key** | Pay-per-token API billing, CI / bot deployments | Get a key from [console.x.ai](https://console.x.ai/) → paste into `GROK_CODE_XAI_API_KEY` variable |\n| **Device-Auth** | SuperGrok paid subscription | Leave `GROK_CODE_XAI_API_KEY` empty. After deploy, run `runuser -u agent -- grok login --device-auth` in the service Exec terminal. The CLI prints a short code + URL — open the URL on any device, enter the code, approve. Token stored at `/home/agent/.grok/auth.json` (persists across restarts). |\n| **Deployment Key** | xAI enterprise customers | Add `GROK_DEPLOYMENT_KEY` as a custom variable in Zeabur Dashboard → Service → Variables after deploy. Takes precedence over `auth.json`. |\n\n> \U0001F4A1 Unlike OAuth flows that bind to a loopback port, Grok's device-auth works in any headless environment (no port-forward, no curl-the-callback trick).\n\n### 4. Deploy\n\nFill in the variables and click deploy. The service connects to Discord automatically. If you used **Device-Auth**, run the login command in step 3 after the service is running.\n\n## Slack Setup (Optional)\n\nOpenAB supports Slack via Socket Mode — no public URL needed.\n\n1. Go to https://api.slack.com/apps → **Create New App** → **From scratch**\n2. **Socket Mode** → Enable → generate an App-Level Token with scope `connections:write` → copy the `xapp-...` token (`SLACK_APP_TOKEN`)\n3. **Event Subscriptions** → Enable Events → add bot events: `app_mention`, `message.channels`, `message.groups`\n4. **OAuth & Permissions** → Bot Token Scopes → add: `app_mentions:read`, `chat:write`, `channels:history`, `groups:history`, `channels:read`, `groups:read`, `reactions:write`, `files:read`, `users:read`\n5. **Install App** → Install to Workspace → copy the `xoxb-...` token (`SLACK_BOT_TOKEN`)\n6. In each Slack channel you want the bot in, run `/invite @YourAppName`\n\nSet `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` in the template variables before deploying. Both Discord and Slack can run simultaneously.\n\n## Add Messaging Platforms (Telegram / LINE / Feishu / Google Chat / MS Teams / WeCom)\n\nTo bridge Telegram, LINE, Feishu/Lark, Google Chat, MS Teams, or WeCom, deploy the [OpenAB Gateway template](https://zeabur.com/templates/IMRONB) into the same Zeabur project. Then add these environment variables to this service:\n\n- `GATEWAY_URL` = `ws://openab-gateway:8080/ws`\n- `GATEWAY_PLATFORM` = one of `telegram`, `line`, `feishu`, `googlechat`, `teams`, `wecom`\n\nRestart the service. The startup script auto-injects the `[gateway]` block into `config.toml`.\n\n## Usage\n\n- **@mention the bot** in an allowed Discord channel or Slack channel to start a conversation\n- OpenAB creates a **thread** for multi-turn conversations — no @mention needed for follow-ups\n- Each thread maps to a persistent Grok session (24h TTL)\n\n## Customization\n\n| File | Description |\n|------|-------------|\n| `/home/agent/.config/openab/config.toml` | OpenAB config (sessions, reactions, STT, etc.) |\n| `/home/agent/.grok/auth.json` | Grok OAuth credentials (managed by `grok login`) |\n| `/home/agent/.grok/config.toml` | Grok runtime config |\n\n`config.toml` is created from a built-in template on first boot. After that, edit the file directly — environment variables are only used for initial setup. To reset to defaults, delete the file and restart: `rm /home/agent/.config/openab/config.toml`\n\nFor OpenAB config options, see the [OpenAB documentation](https://github.com/openabdev/openab). For Grok config options, see the [Grok Build docs](https://x.ai/news/grok-build-cli).\n\n## Disabling\n\nLeave `Discord Bot Token` empty (and `SLACK_BOT_TOKEN` empty). The service sleeps instead of crashing.\n\n## Links\n\n- [OpenAB GitHub](https://github.com/openabdev/openab)\n- [Grok Build (xAI)](https://x.ai/news/grok-build-cli)\n- [Agent Client Protocol](https://github.com/anthropics/agent-protocol)\n"
    resourceRequirement:
        minConfig:
            cpu: 2
            ram: 4
        recommendedConfig:
            cpu: 4
            ram: 8
    services:
        - name: openab
          icon: https://cdn-console.zeabur.com/f/0Ewi6/openab-icon.webp
          template: PREBUILT_V2
          spec:
            id: openab
            source:
                image: ghcr.io/openabdev/openab-grok:0.8.3-beta.11
                command:
                    - /bin/sh
                    - -c
                    - /opt/start-openab.sh
            volumes:
                - id: agent-home
                  dir: /home/agent
            env:
                DISCORD_BOT_TOKEN:
                    default: ${DISCORD_BOT_TOKEN}
                GROK_CODE_XAI_API_KEY:
                    default: ""
                OPENAB_ALLOW_BOT_MESSAGES:
                    default: ""
                OPENAB_ALLOWED_CHANNELS:
                    default: ""
                OPENAB_ALLOWED_USERS:
                    default: ""
                OPENAB_MAX_SESSIONS:
                    default: ""
                OPENAB_TRUSTED_BOT_IDS:
                    default: ""
                SLACK_APP_TOKEN:
                    default: ""
                SLACK_BOT_TOKEN:
                    default: ""
            configs:
                - path: /opt/start-openab.sh
                  template: |
                    #!/bin/sh
                    set -e

                    # Initialize shell dotfiles and fix ownership for persistent volume
                    if [ ! -f /home/agent/.bashrc ]; then
                      cp /etc/skel/.bashrc /home/agent/.bashrc 2>/dev/null || true
                      cp /etc/skel/.profile /home/agent/.profile 2>/dev/null || true
                      cp /etc/skel/.bash_logout /home/agent/.bash_logout 2>/dev/null || true
                    fi

                    # Fix ownership for persistent volume when startup runs as root
                    if [ "$(id -u)" = "0" ]; then
                      chown -R agent:agent /home/agent
                      chmod 755 /home/agent/.config 2>/dev/null || true
                    fi

                    if [ -z "$DISCORD_BOT_TOKEN" ] && [ -z "$SLACK_BOT_TOKEN" ]; then
                      echo "openab: neither DISCORD_BOT_TOKEN nor SLACK_BOT_TOKEN set — sleeping"
                      exec sleep infinity
                    fi

                    CONFIG_DIR=/home/agent/.config/openab
                    CONFIG_FILE=$CONFIG_DIR/config.toml
                    mkdir -p "$CONFIG_DIR"

                    # Generate config.toml on first boot only
                    # To regenerate, delete the file and restart
                    if [ ! -f "$CONFIG_FILE" ]; then
                      cp /opt/config.toml.template "$CONFIG_FILE"

                      # Add [discord] section if token provided
                      if [ -n "$DISCORD_BOT_TOKEN" ]; then
                        printf '\n[discord]\nbot_token = "${DISCORD_BOT_TOKEN}"\n' >> "$CONFIG_FILE"
                        if [ -n "$OPENAB_ALLOW_BOT_MESSAGES" ]; then
                          printf 'allow_bot_messages = "%s"\n' "$OPENAB_ALLOW_BOT_MESSAGES" >> "$CONFIG_FILE"
                        fi
                        if [ -n "$OPENAB_ALLOWED_CHANNELS" ]; then
                          IFS=','; channels=""; for id in $OPENAB_ALLOWED_CHANNELS; do
                            id=$(echo "$id" | tr -d ' '); [ -n "$id" ] && channels="${channels}\"${id}\","; done; unset IFS
                          printf 'allowed_channels = [%s]\n' "$(echo "$channels" | sed 's/,$//')" >> "$CONFIG_FILE"
                        fi
                        if [ -n "$OPENAB_ALLOWED_USERS" ]; then
                          IFS=','; users=""; for id in $OPENAB_ALLOWED_USERS; do
                            id=$(echo "$id" | tr -d ' '); [ -n "$id" ] && users="${users}\"${id}\","; done; unset IFS
                          printf 'allowed_users = [%s]\n' "$(echo "$users" | sed 's/,$//')" >> "$CONFIG_FILE"
                        fi
                        if [ -n "$OPENAB_TRUSTED_BOT_IDS" ]; then
                          IFS=','; bots=""; for id in $OPENAB_TRUSTED_BOT_IDS; do
                            id=$(echo "$id" | tr -d ' '); [ -n "$id" ] && bots="${bots}\"${id}\","; done; unset IFS
                          printf 'trusted_bot_ids = [%s]\n' "$(echo "$bots" | sed 's/,$//')" >> "$CONFIG_FILE"
                        fi
                      fi

                      # Add [slack] section if tokens provided
                      if [ -n "$SLACK_BOT_TOKEN" ] && [ -n "$SLACK_APP_TOKEN" ]; then
                        printf '\n[slack]\nbot_token = "${SLACK_BOT_TOKEN}"\napp_token = "${SLACK_APP_TOKEN}"\n' >> "$CONFIG_FILE"
                      fi

                      # Add [pool] section if max_sessions provided
                      if [ -n "$OPENAB_MAX_SESSIONS" ]; then
                        printf '\n[pool]\nmax_sessions = %s\n' "$OPENAB_MAX_SESSIONS" >> "$CONFIG_FILE"
                      fi

                      echo "openab: config.toml generated"
                    else
                      echo "openab: using existing config.toml (delete to regenerate)"
                    fi

                    if [ "$(id -u)" = "0" ]; then
                      chown -R agent:agent "$CONFIG_DIR"
                      exec runuser -u agent --preserve-environment -- openab run --config "$CONFIG_FILE"
                    fi

                    exec openab run --config "$CONFIG_FILE"
                  permission: 493
                  envsubst: null
                - path: /opt/config.toml.template
                  template: |
                    [agent]
                    command = "grok"
                    args = ["agent", "stdio"]
                    working_dir = "/home/agent"
                  permission: null
                  envsubst: null
localization:
    es-ES:
        description: |
            Open Agent Broker — un arnés ligero en Rust que conecta Discord y Slack con cualquier CLI de coding compatible con ACP a través de stdio JSON-RPC. Esta plantilla usa Grok Build (el CLI oficial de coding agent de xAI) como backend mediante `grok agent stdio`.
            Fuente: https://github.com/openabdev/openab
        variables:
            - key: DISCORD_BOT_TOKEN
              type: STRING
              name: Token del Bot de Discord
              description: Token obtenido de https://discord.com/developers/applications
            - key: GROK_CODE_XAI_API_KEY
              type: STRING
              name: Grok / xAI API Key (opcional)
              description: Opcional. xAI API key (xai-...) obtenida de [console.x.ai](https://console.x.ai/). Dejar vacío para autenticar mediante device flow tras el despliegue (suscripción SuperGrok), o añadir un deployment key más tarde en el Dashboard.
            - key: OPENAB_ALLOWED_CHANNELS
              type: STRING
              name: IDs de Canales de Discord (opcional)
              description: 'Opcional. IDs de canales de Discord donde el bot escucha, separados por comas. Dejar vacío para permitir todos los canales. Ejemplo: 123456789012345678,234567890123456789'
            - key: OPENAB_ALLOWED_USERS
              type: STRING
              name: IDs de Usuarios de Discord (opcional)
              description: Opcional. IDs de usuarios de Discord permitidos para interactuar con el bot, separados por comas. Dejar vacío para permitir a todos en los canales permitidos.
        readme: "# OpenAB Grok\n\n[OpenAB](https://github.com/openabdev/openab) es un arnés ligero de código abierto en Rust que conecta Discord y Slack con cualquier CLI de coding compatible con [Agent Client Protocol](https://github.com/anthropics/agent-protocol) a través de stdio JSON-RPC.\n\nEsta plantilla ejecuta la variante Grok — usa [Grok Build](https://x.ai/news/grok-build-cli), el CLI oficial de coding agent de xAI, como backend mediante `grok agent stdio`.\n\n## Notas Importantes\n\n- **Etiqueta de imagen:** Esta plantilla usa una versión fijada (`0.8.3-beta.11`). Para actualizar, cambie la etiqueta de imagen en Zeabur Dashboard → Servicio → Configuración. Etiquetas disponibles: [GitHub Packages](https://github.com/openabdev/openab/pkgs/container/openab-grok).\n- **Almacenamiento persistente:** `/home/agent` está montado como volumen persistente. Las credenciales de Grok (`~/.grok/auth.json`), settings y config se conservan entre reinicios.\n\n## Configuración\n\n### 1. Obtener el Discord Bot Token\n\n1. Ir a https://discord.com/developers/applications y hacer clic en **New Application**\n2. Ir a la pestaña **Bot** → clic en **Reset Token** → copiar el token\n3. En la misma página, bajar y habilitar **Message Content Intent** en Privileged Gateway Intents\n4. Ir a **OAuth2 → URL Generator** → marcar scope `bot` → marcar permisos: Send Messages, Send Messages in Threads, Create Public Threads, Read Message History, Add Reactions, Manage Messages\n5. Copiar la URL generada y abrirla en el navegador para invitar al Bot al servidor\n\n### 2. Obtener IDs de canales de Discord\n\n1. Abrir Discord → **Ajustes de usuario** (icono de engranaje) → **Avanzado** → activar **Modo desarrollador**\n2. Clic derecho en el canal donde quieres que el Bot responda → **Copiar ID del canal**\n3. Para múltiples canales, separar con comas: `123456789012345678,234567890123456789`\n\n### 3. Elegir un método de autenticación\n\nGrok Build soporta tres fuentes de credenciales. Elige la que se adapte a tu caso de uso.\n\n| Método | Cuándo usar | Cómo |\n|--------|-------------|------|\n| **API Key** | Facturación pay-per-token, despliegues CI / bot | Obtén una clave en [console.x.ai](https://console.x.ai/) → pégala en la variable `GROK_CODE_XAI_API_KEY` |\n| **Device-Auth** | Suscripción de pago SuperGrok | Deja `GROK_CODE_XAI_API_KEY` vacío. Tras el despliegue, ejecuta `runuser -u agent -- grok login --device-auth` en la terminal Exec del servicio. El CLI imprime un código corto + URL — abre la URL en cualquier dispositivo, introduce el código y aprueba. El token se guarda en `/home/agent/.grok/auth.json` (persiste entre reinicios). |\n| **Deployment Key** | Clientes empresariales de xAI | Añade `GROK_DEPLOYMENT_KEY` como variable personalizada en Zeabur Dashboard → Servicio → Variables tras desplegar. Tiene prioridad sobre `auth.json`. |\n\n> \U0001F4A1 A diferencia de los flujos OAuth que se vinculan a un puerto loopback, el device-auth de Grok funciona en cualquier entorno headless (sin port-forward, sin truco curl-the-callback).\n\n### 4. Desplegar\n\nCompleta las variables y haz clic en desplegar. El servicio se conecta a Discord automáticamente. Si usaste **Device-Auth**, ejecuta el comando de login del paso 3 después de que el servicio esté en ejecución.\n\n## Configuración de Slack (Opcional)\n\nOpenAB soporta Slack mediante Socket Mode — no se necesita URL pública.\n\n1. Ir a https://api.slack.com/apps → **Create New App** → **From scratch**\n2. **Socket Mode** → Habilitar → generar App-Level Token con scope `connections:write` → copiar el token `xapp-...` (`SLACK_APP_TOKEN`)\n3. **Event Subscriptions** → Habilitar → añadir bot events: `app_mention`, `message.channels`, `message.groups`\n4. **OAuth & Permissions** → Bot Token Scopes → añadir: `app_mentions:read`, `chat:write`, `channels:history`, `groups:history`, `channels:read`, `groups:read`, `reactions:write`, `files:read`, `users:read`\n5. **Install App** → Instalar en el workspace → copiar el token `xoxb-...` (`SLACK_BOT_TOKEN`)\n6. En cada canal de Slack donde quieras usar el bot, ejecuta `/invite @YourAppName`\n\nRellena `SLACK_BOT_TOKEN` y `SLACK_APP_TOKEN` antes de desplegar. Discord y Slack pueden funcionar simultáneamente.\n\n## Añadir plataformas de mensajería (Telegram / LINE / Feishu / Google Chat / MS Teams / WeCom)\n\nPara conectar Telegram, LINE, Feishu/Lark, Google Chat, MS Teams o WeCom, despliega la [plantilla OpenAB Gateway](https://zeabur.com/templates/IMRONB) en el mismo proyecto Zeabur. Luego añade estas variables de entorno a este servicio:\n\n- `GATEWAY_URL` = `ws://openab-gateway:8080/ws`\n- `GATEWAY_PLATFORM` = uno de `telegram`, `line`, `feishu`, `googlechat`, `teams`, `wecom`\n\nReinicia el servicio. El script de arranque inyecta automáticamente el bloque `[gateway]` en `config.toml`.\n\n## Uso\n\n- **@mencionar al bot** en un canal de Discord o Slack permitido para iniciar una conversación\n- OpenAB crea un **thread** para conversaciones de múltiples turnos — no se necesita @mención en los mensajes siguientes\n- Cada thread corresponde a una sesión persistente de Grok (TTL de 24h por defecto)\n\n## Personalización\n\n| Archivo | Descripción |\n|---------|-------------|\n| `/home/agent/.config/openab/config.toml` | Configuración de OpenAB (sessions, reactions, STT, etc.) |\n| `/home/agent/.grok/auth.json` | Credenciales OAuth de Grok (gestionadas por `grok login`) |\n| `/home/agent/.grok/config.toml` | Configuración runtime de Grok |\n\n`config.toml` se crea a partir de una plantilla integrada en el primer arranque. Después, edite el archivo directamente — las variables de entorno solo se usan para la configuración inicial. Para restablecer los valores predeterminados, elimine el archivo y reinicie: `rm /home/agent/.config/openab/config.toml`\n\nPara las opciones de configuración de OpenAB, consulte la [documentación de OpenAB](https://github.com/openabdev/openab). Para las opciones de configuración de Grok, consulte la [documentación de Grok Build](https://x.ai/news/grok-build-cli).\n\n## Desactivar\n\nDejar `Discord Bot Token` y `SLACK_BOT_TOKEN` vacíos al desplegar. El servicio entrará en modo sleep sin fallar.\n\n## Enlaces\n\n- [OpenAB GitHub](https://github.com/openabdev/openab)\n- [Grok Build (xAI)](https://x.ai/news/grok-build-cli)\n- [Agent Client Protocol](https://github.com/anthropics/agent-protocol)\n"
    id-ID:
        description: |
            Open Agent Broker — harness Rust yang ringan untuk menjembatani Discord dan Slack ke CLI coding yang kompatibel dengan ACP melalui stdio JSON-RPC. Template ini menggunakan Grok Build (CLI coding agent resmi xAI) sebagai backend melalui `grok agent stdio`.
            Sumber: https://github.com/openabdev/openab
        variables:
            - key: DISCORD_BOT_TOKEN
              type: STRING
              name: Token Bot Discord
              description: Token dari https://discord.com/developers/applications
            - key: GROK_CODE_XAI_API_KEY
              type: STRING
              name: Grok / xAI API Key (opsional)
              description: Opsional. xAI API key (xai-...) dari [console.x.ai](https://console.x.ai/). Kosongkan untuk autentikasi melalui device flow setelah deploy (langganan SuperGrok), atau tambahkan deployment key nanti di Dashboard.
            - key: OPENAB_ALLOWED_CHANNELS
              type: STRING
              name: ID Channel Discord (opsional)
              description: 'Opsional. ID channel Discord tempat bot mendengarkan, dipisahkan koma. Kosongkan untuk mengizinkan semua channel. Contoh: 123456789012345678,234567890123456789'
            - key: OPENAB_ALLOWED_USERS
              type: STRING
              name: ID Pengguna Discord (opsional)
              description: Opsional. ID pengguna Discord yang diizinkan berinteraksi dengan bot, dipisahkan koma. Kosongkan untuk mengizinkan semua orang di channel yang diizinkan.
        readme: "# OpenAB Grok\n\n[OpenAB](https://github.com/openabdev/openab) adalah harness Rust yang ringan dan open-source yang menjembatani Discord dan Slack ke CLI coding yang kompatibel dengan [Agent Client Protocol](https://github.com/anthropics/agent-protocol) melalui stdio JSON-RPC.\n\nTemplate ini menjalankan varian Grok — menggunakan [Grok Build](https://x.ai/news/grok-build-cli), CLI coding agent resmi dari xAI, sebagai backend melalui `grok agent stdio`.\n\n## Catatan Penting\n\n- **Tag image:** Template ini menggunakan versi yang dipin (`0.8.3-beta.11`). Untuk upgrade, ubah tag image di Zeabur Dashboard → Layanan → Pengaturan. Tag yang tersedia: [GitHub Packages](https://github.com/openabdev/openab/pkgs/container/openab-grok).\n- **Penyimpanan persisten:** `/home/agent` di-mount sebagai volume persisten. Kredensial Grok (`~/.grok/auth.json`), settings, dan config dipertahankan antar restart.\n\n## Pengaturan\n\n### 1. Dapatkan Discord Bot Token\n\n1. Buka https://discord.com/developers/applications dan klik **New Application**\n2. Buka tab **Bot** → klik **Reset Token** → salin token\n3. Di halaman yang sama, scroll ke bawah dan aktifkan **Message Content Intent** di Privileged Gateway Intents\n4. Buka **OAuth2 → URL Generator** → centang scope `bot` → centang izin: Send Messages, Send Messages in Threads, Create Public Threads, Read Message History, Add Reactions, Manage Messages\n5. Salin URL yang dihasilkan dan buka di browser untuk mengundang Bot ke server Anda\n\n### 2. Dapatkan ID Channel Discord\n\n1. Buka Discord → **Pengaturan Pengguna** (ikon roda gigi) → **Lanjutan** → aktifkan **Mode Pengembang**\n2. Klik kanan channel tempat Anda ingin Bot merespons → **Salin ID Channel**\n3. Untuk beberapa channel, pisahkan dengan koma: `123456789012345678,234567890123456789`\n\n### 3. Pilih Metode Autentikasi\n\nGrok Build mendukung tiga sumber kredensial. Pilih yang sesuai dengan kasus penggunaan Anda.\n\n| Metode | Kapan digunakan | Cara |\n|--------|-----------------|------|\n| **API Key** | Penagihan API pay-per-token, deployment CI / bot | Dapatkan key di [console.x.ai](https://console.x.ai/) → tempelkan ke variabel `GROK_CODE_XAI_API_KEY` |\n| **Device-Auth** | Langganan berbayar SuperGrok | Biarkan `GROK_CODE_XAI_API_KEY` kosong. Setelah deploy, jalankan `runuser -u agent -- grok login --device-auth` di terminal Exec layanan. CLI mencetak kode pendek + URL — buka URL di perangkat mana pun, masukkan kode, lalu setujui. Token disimpan di `/home/agent/.grok/auth.json` (bertahan setelah restart). |\n| **Deployment Key** | Pelanggan enterprise xAI | Tambahkan `GROK_DEPLOYMENT_KEY` sebagai variabel kustom di Zeabur Dashboard → Layanan → Variables setelah deploy. Lebih diutamakan daripada `auth.json`. |\n\n> \U0001F4A1 Tidak seperti alur OAuth yang terikat pada port loopback, device-auth Grok berfungsi di lingkungan headless mana pun (tanpa port-forward, tanpa trik curl-the-callback).\n\n### 4. Deploy\n\nIsi variabel dan klik deploy. Layanan akan otomatis terhubung ke Discord. Jika menggunakan **Device-Auth**, jalankan perintah login di langkah 3 setelah layanan berjalan.\n\n## Pengaturan Slack (Opsional)\n\nOpenAB mendukung Slack melalui Socket Mode — tidak perlu URL publik.\n\n1. Buka https://api.slack.com/apps → **Create New App** → **From scratch**\n2. **Socket Mode** → Aktifkan → buat App-Level Token dengan scope `connections:write` → salin token `xapp-...` (`SLACK_APP_TOKEN`)\n3. **Event Subscriptions** → Aktifkan → tambahkan bot events: `app_mention`, `message.channels`, `message.groups`\n4. **OAuth & Permissions** → Bot Token Scopes → tambahkan: `app_mentions:read`, `chat:write`, `channels:history`, `groups:history`, `channels:read`, `groups:read`, `reactions:write`, `files:read`, `users:read`\n5. **Install App** → Install ke workspace → salin token `xoxb-...` (`SLACK_BOT_TOKEN`)\n6. Di setiap channel Slack yang ingin menggunakan bot, jalankan `/invite @YourAppName`\n\nIsi `SLACK_BOT_TOKEN` dan `SLACK_APP_TOKEN` sebelum deploy. Discord dan Slack dapat berjalan bersamaan.\n\n## Tambahkan Platform Pesan (Telegram / LINE / Feishu / Google Chat / MS Teams / WeCom)\n\nUntuk menjembatani Telegram, LINE, Feishu/Lark, Google Chat, MS Teams, atau WeCom, deploy [template OpenAB Gateway](https://zeabur.com/templates/IMRONB) di proyek Zeabur yang sama. Kemudian tambahkan variabel lingkungan berikut ke layanan ini:\n\n- `GATEWAY_URL` = `ws://openab-gateway:8080/ws`\n- `GATEWAY_PLATFORM` = salah satu dari `telegram`, `line`, `feishu`, `googlechat`, `teams`, `wecom`\n\nRestart layanan. Skrip startup otomatis menyuntikkan blok `[gateway]` ke `config.toml`.\n\n## Penggunaan\n\n- **@mention bot** di channel Discord atau Slack yang diizinkan untuk memulai percakapan\n- OpenAB membuat **thread** untuk percakapan multi-giliran — tidak perlu @mention untuk pesan selanjutnya\n- Setiap thread dipetakan ke sesi Grok yang persisten (TTL 24 jam secara default)\n\n## Kustomisasi\n\n| File | Deskripsi |\n|------|-----------|\n| `/home/agent/.config/openab/config.toml` | Konfigurasi OpenAB (sessions, reactions, STT, dll.) |\n| `/home/agent/.grok/auth.json` | Kredensial OAuth Grok (dikelola oleh `grok login`) |\n| `/home/agent/.grok/config.toml` | Konfigurasi runtime Grok |\n\n`config.toml` dibuat dari template bawaan saat boot pertama. Setelah itu, edit file secara langsung — variabel lingkungan hanya digunakan untuk pengaturan awal. Untuk mengembalikan ke default, hapus dan restart: `rm /home/agent/.config/openab/config.toml`\n\nUntuk opsi konfigurasi OpenAB, lihat [dokumentasi OpenAB](https://github.com/openabdev/openab). Untuk opsi konfigurasi Grok, lihat [dokumentasi Grok Build](https://x.ai/news/grok-build-cli).\n\n## Menonaktifkan\n\nKosongkan `Discord Bot Token` dan `SLACK_BOT_TOKEN` saat deploy. Layanan akan tidur tanpa crash.\n\n## Tautan\n\n- [OpenAB GitHub](https://github.com/openabdev/openab)\n- [Grok Build (xAI)](https://x.ai/news/grok-build-cli)\n- [Agent Client Protocol](https://github.com/anthropics/agent-protocol)\n"
    ja-JP:
        description: |
            Open Agent Broker — stdio JSON-RPC を通じて Discord と Slack を ACP 対応の coding CLI にブリッジする軽量な Rust ハーネス。このテンプレートは Grok Build（xAI 公式の coding agent CLI）をバックエンドとして使用し、`grok agent stdio` で起動します。
            ソース：https://github.com/openabdev/openab
        variables:
            - key: DISCORD_BOT_TOKEN
              type: STRING
              name: Discord Bot トークン
              description: https://discord.com/developers/applications から取得したトークン
            - key: GROK_CODE_XAI_API_KEY
              type: STRING
              name: Grok / xAI API Key（オプション）
              description: オプション。xAI API key（xai-...）。[console.x.ai](https://console.x.ai/) から取得。空のままにするとデプロイ後の device flow 認証（SuperGrok サブスクリプション）、または後で Dashboard で deployment key を追加できます。
            - key: OPENAB_ALLOWED_CHANNELS
              type: STRING
              name: Discord チャンネル ID（オプション）
              description: オプション。Bot が監視する Discord チャンネル ID（カンマ区切り）。空の場合、全チャンネルで応答。例：123456789012345678,234567890123456789
            - key: OPENAB_ALLOWED_USERS
              type: STRING
              name: Discord ユーザー ID（オプション）
              description: オプション。Bot と対話できるユーザーの Discord ユーザー ID（カンマ区切り）。空の場合、許可チャンネルの全員が利用可能。
        readme: "# OpenAB Grok\n\n[OpenAB](https://github.com/openabdev/openab) は、stdio JSON-RPC を通じて Discord と Slack を [Agent Client Protocol](https://github.com/anthropics/agent-protocol) 対応の coding CLI にブリッジする軽量なオープンソース Rust ハーネスです。\n\nこのテンプレートは Grok バリアントを実行します — xAI 公式の coding agent CLI である [Grok Build](https://x.ai/news/grok-build-cli) をバックエンドとして使用し、`grok agent stdio` で起動します。\n\n## 注意事項\n\n- **イメージタグ：** このテンプレートは固定バージョン（`0.8.3-beta.11`）を使用しています。アップグレードするには、Zeabur Dashboard → サービス → 設定でイメージタグを変更してください。利用可能なタグ：[GitHub Packages](https://github.com/openabdev/openab/pkgs/container/openab-grok)。\n- **永続ストレージ：** `/home/agent` が永続ボリュームとしてマウントされます。Grok の認証情報（`~/.grok/auth.json`）、設定、config は再起動後も保持されます。\n\n## セットアップ\n\n### 1. Discord Bot Token の取得\n\n1. https://discord.com/developers/applications にアクセスし、**New Application** をクリック\n2. **Bot** タブ → **Reset Token** をクリック → token をコピー\n3. 同じページを下にスクロールし、Privileged Gateway Intents の **Message Content Intent** を有効化\n4. **OAuth2 → URL Generator** → scope `bot` にチェック → 権限にチェック：Send Messages、Send Messages in Threads、Create Public Threads、Read Message History、Add Reactions、Manage Messages\n5. 生成された URL をコピーし、ブラウザで開いて Bot をサーバーに招待\n\n### 2. Discord チャンネル ID の取得\n\n1. Discord を開く → **ユーザー設定**（歯車アイコン）→ **詳細設定** → **開発者モード** を有効化\n2. Bot に応答させたいチャンネルを右クリック → **チャンネル ID をコピー**\n3. 複数チャンネルはカンマで区切る：`123456789012345678,234567890123456789`\n\n### 3. 認証方法の選択\n\nGrok Build は 3 種類の認証ソースをサポートします。ユースケースに合うものを選んでください。\n\n| 方法 | 利用シーン | 手順 |\n|------|-----------|------|\n| **API Key** | トークン課金の API 利用、CI / bot デプロイ | [console.x.ai](https://console.x.ai/) でキーを取得 → `GROK_CODE_XAI_API_KEY` 変数に貼り付け |\n| **Device-Auth** | SuperGrok 有料サブスクリプション | `GROK_CODE_XAI_API_KEY` は空のまま。デプロイ後、サービスの Exec ターミナルで `runuser -u agent -- grok login --device-auth` を実行。CLI が短いコードと URL を表示するので、任意のデバイスで URL を開き、コードを入力して承認。Token は `/home/agent/.grok/auth.json` に保存され、再起動後も保持されます。 |\n| **Deployment Key** | xAI エンタープライズ顧客 | デプロイ後、Zeabur Dashboard → サービス → Variables で `GROK_DEPLOYMENT_KEY` をカスタム変数として追加。`auth.json` より優先されます。 |\n\n> \U0001F4A1 loopback ポートにバインドする OAuth フローとは異なり、Grok の device-auth は任意のヘッドレス環境で動作します（port-forward 不要、curl-the-callback トリック不要）。\n\n### 4. デプロイ\n\n変数を入力してデプロイをクリック。サービスは自動的に Discord に接続します。**Device-Auth** を使用する場合は、サービス起動後にステップ 3 の login コマンドを実行してください。\n\n## Slack セットアップ（オプション）\n\nOpenAB は Socket Mode 経由で Slack をサポートします — 公開 URL は不要です。\n\n1. https://api.slack.com/apps → **Create New App** → **From scratch**\n2. **Socket Mode** → 有効化 → scope `connections:write` で App-Level Token を生成 → `xapp-...` token をコピー（`SLACK_APP_TOKEN`）\n3. **Event Subscriptions** → 有効化 → bot events を追加：`app_mention`、`message.channels`、`message.groups`\n4. **OAuth & Permissions** → Bot Token Scopes → 追加：`app_mentions:read`、`chat:write`、`channels:history`、`groups:history`、`channels:read`、`groups:read`、`reactions:write`、`files:read`、`users:read`\n5. **Install App** → ワークスペースにインストール → `xoxb-...` token をコピー（`SLACK_BOT_TOKEN`）\n6. Bot を使用したい各 Slack チャンネルで `/invite @YourAppName` を実行\n\nデプロイ前に `SLACK_BOT_TOKEN` と `SLACK_APP_TOKEN` 変数を入力してください。Discord と Slack は同時に使用できます。\n\n## メッセージプラットフォームを追加（Telegram / LINE / Feishu / Google Chat / MS Teams / WeCom）\n\nTelegram、LINE、Feishu/Lark、Google Chat、MS Teams、WeCom を接続するには、同じ Zeabur プロジェクトに [OpenAB Gateway テンプレート](https://zeabur.com/templates/IMRONB) をデプロイしてから、このサービスに次の環境変数を設定してください：\n\n- `GATEWAY_URL` = `ws://openab-gateway:8080/ws`\n- `GATEWAY_PLATFORM` = `telegram`、`line`、`feishu`、`googlechat`、`teams`、`wecom` のいずれか\n\nサービスを再起動すると、起動スクリプトが `config.toml` に `[gateway]` セクションを自動追加します。\n\n## 使い方\n\n- 許可された Discord または Slack チャンネルで **Bot を @mention** して会話を開始\n- OpenAB は自動的に **thread** を作成してマルチターン会話を行います — 以降のメッセージでは @mention 不要\n- 各 thread は永続的な Grok session に対応（デフォルト 24 時間 TTL）\n\n## カスタマイズ\n\n| ファイル | 説明 |\n|---------|------|\n| `/home/agent/.config/openab/config.toml` | OpenAB 設定（sessions、reactions、STT など） |\n| `/home/agent/.grok/auth.json` | Grok OAuth 認証情報（`grok login` で管理） |\n| `/home/agent/.grok/config.toml` | Grok ランタイム設定 |\n\n`config.toml` は初回起動時に内蔵テンプレートから作成されます。以降の変更はファイルを直接編集してください。環境変数は初期設定時のみ使用されます。デフォルトに戻すにはファイルを削除して再起動：`rm /home/agent/.config/openab/config.toml`\n\nOpenAB の設定オプションは [OpenAB ドキュメント](https://github.com/openabdev/openab) を、Grok の設定オプションは [Grok Build ドキュメント](https://x.ai/news/grok-build-cli) を参照してください。\n\n## 無効化\n\nデプロイ時に `Discord Bot Token` と `SLACK_BOT_TOKEN` の両方を空にしてください。サービスはクラッシュせずスリープ状態になります。\n\n## リンク\n\n- [OpenAB GitHub](https://github.com/openabdev/openab)\n- [Grok Build（xAI）](https://x.ai/news/grok-build-cli)\n- [Agent Client Protocol](https://github.com/anthropics/agent-protocol)\n"
    zh-CN:
        description: |
            Open Agent Broker — 轻量的 Rust 程序，通过 stdio JSON-RPC 将 Discord 和 Slack 桥接到任何 ACP 兼容的 coding CLI。此模板使用 Grok Build（xAI 官方 coding agent CLI）作为后端，通过 `grok agent stdio` 启动。
            来源：https://github.com/openabdev/openab
        variables:
            - key: DISCORD_BOT_TOKEN
              type: STRING
              name: Discord Bot Token
              description: 从 https://discord.com/developers/applications 获取的 Token
            - key: GROK_CODE_XAI_API_KEY
              type: STRING
              name: Grok / xAI API Key（选填）
              description: 选填。xAI API key（xai-...），从 https://console.x.ai/ 获取。留空则部署后使用 device flow 认证（SuperGrok 订阅），或之后在 Dashboard 新增 deployment key。
            - key: OPENAB_ALLOWED_CHANNELS
              type: STRING
              name: Discord 频道 ID（选填）
              description: 选填。Bot 监听的 Discord 频道 ID，以逗号分隔。留空则允许所有频道。示例：123456789012345678,234567890123456789
            - key: OPENAB_ALLOWED_USERS
              type: STRING
              name: Discord 用户 ID（选填）
              description: 选填。以逗号分隔的 Discord 用户 ID，限制可与 Bot 互动的用户。留空则允许频道中所有人。
        readme: "# OpenAB Grok\n\n[OpenAB](https://github.com/openabdev/openab) 是一个轻量的开源 Rust 程序，通过 stdio JSON-RPC 将 Discord 和 Slack 桥接到任何支持 [Agent Client Protocol](https://github.com/anthropics/agent-protocol) 的 coding CLI。\n\n此模板部署 Grok 变体 — 使用 xAI 官方 coding agent CLI [Grok Build](https://x.ai/news/grok-build-cli) 作为后端，通过 `grok agent stdio` 启动。\n\n## 注意事项\n\n- **镜像标签：** 此模板使用固定版本（`0.8.3-beta.11`）。如需升级，请在 Zeabur Dashboard → 服务 → 设置中更改镜像标签。可用标签：[GitHub Packages](https://github.com/openabdev/openab/pkgs/container/openab-grok)。\n- **持久化存储：** `/home/agent` 挂载为持久化磁盘。Grok 认证数据（`~/.grok/auth.json`）、设置、config 会在重启后保留。\n\n## 设置步骤\n\n### 1. 获取 Discord Bot Token\n\n1. 前往 https://discord.com/developers/applications，点击 **New Application**\n2. 进入 **Bot** 页签 → 点击 **Reset Token** → 复制 token\n3. 同一页面往下滑，在 Privileged Gateway Intents 下启用 **Message Content Intent**\n4. 前往 **OAuth2 → URL Generator** → 勾选 scope `bot` → 勾选权限：Send Messages、Send Messages in Threads、Create Public Threads、Read Message History、Add Reactions、Manage Messages\n5. 复制生成的 URL，在浏览器中打开以邀请 Bot 到你的服务器\n\n### 2. 获取 Discord 频道 ID\n\n1. 打开 Discord → 前往 **用户设置**（齿轮图标）→ **高级** → 启用 **开发者模式**\n2. 右键点击你要 Bot 回应的频道 → **复制频道 ID**\n3. 多个频道用逗号分隔：`123456789012345678,234567890123456789`\n\n### 3. 选择认证方式\n\nGrok Build 支持三种认证来源，选一个适合你的场景：\n\n| 方法 | 适用场景 | 操作 |\n|------|----------|------|\n| **API Key** | 按使用量付费 API、CI / bot 部署 | 至 [console.x.ai](https://console.x.ai/) 获取 key，填入 `GROK_CODE_XAI_API_KEY` 变量 |\n| **Device-Auth** | SuperGrok 订阅 | `GROK_CODE_XAI_API_KEY` 留空。部署后到服务 Exec 终端执行 `runuser -u agent -- grok login --device-auth`。CLI 会打印短代码 + URL — 在任何设备打开 URL、输入代码、同意授权。Token 写入 `/home/agent/.grok/auth.json`（重启后保留）。 |\n| **Deployment Key** | xAI 企业客户 | 部署后在 Zeabur Dashboard → 服务 → Variables 新增自定义变量 `GROK_DEPLOYMENT_KEY`。优先级高于 `auth.json`。 |\n\n> \U0001F4A1 跟 loopback OAuth 不同，Grok 的 device-auth 在任何 headless 环境都能用（不需 port-forward、不需 curl callback）。\n\n### 4. 部署\n\n填入变量后点击部署。服务会自动连接到 Discord。如果选择 **Device-Auth**，部署后再执行步骤 3 中的 login 指令。\n\n## Slack 设置（可选）\n\nOpenAB 支持通过 Socket Mode 连接 Slack，无需公开 URL。\n\n1. 前往 https://api.slack.com/apps → **Create New App** → **From scratch**\n2. **Socket Mode** → 启用 → 生成 App-Level Token，scope 选 `connections:write` → 复制 `xapp-...` token（`SLACK_APP_TOKEN`）\n3. **Event Subscriptions** → 启用 → 添加 bot events：`app_mention`、`message.channels`、`message.groups`\n4. **OAuth & Permissions** → Bot Token Scopes → 添加：`app_mentions:read`、`chat:write`、`channels:history`、`groups:history`、`channels:read`、`groups:read`、`reactions:write`、`files:read`、`users:read`\n5. **Install App** → 安装到工作区 → 复制 `xoxb-...` token（`SLACK_BOT_TOKEN`）\n6. 在每个要使用 Bot 的 Slack 频道执行 `/invite @YourAppName`\n\n部署前填入 `SLACK_BOT_TOKEN` 和 `SLACK_APP_TOKEN` 变量。Discord 和 Slack 可同时运行。\n\n## 添加通讯平台（Telegram / LINE / 飞书 / Google Chat / MS Teams / 企业微信）\n\n若要桥接 Telegram、LINE、飞书/Lark、Google Chat、MS Teams 或企业微信（WeCom），请在同一个 Zeabur 项目中部署 [OpenAB Gateway 模板](https://zeabur.com/templates/IMRONB)，然后在此服务上设置以下环境变量：\n\n- `GATEWAY_URL` = `ws://openab-gateway:8080/ws`\n- `GATEWAY_PLATFORM` = `telegram`、`line`、`feishu`、`googlechat`、`teams` 或 `wecom` 之一\n\n重启服务。启动脚本会自动将 `[gateway]` 块注入 `config.toml`。\n\n## 使用方式\n\n- 在允许的 Discord 或 Slack 频道中 **@mention Bot** 即可开始对话\n- OpenAB 会自动创建 **thread** 进行多轮对话 — 后续消息不需要再 @mention\n- 每个 thread 对应一个持久的 Grok session（默认 24 小时 TTL）\n\n## 自定义设置\n\n| 文件 | 说明 |\n|------|------|\n| `/home/agent/.config/openab/config.toml` | OpenAB 设置（sessions、reactions、STT 等） |\n| `/home/agent/.grok/auth.json` | Grok OAuth 认证（由 `grok login` 管理） |\n| `/home/agent/.grok/config.toml` | Grok runtime 设置 |\n\n`config.toml` 在首次启动时从内建模板创建。之后请直接编辑文件，环境变量仅用于初始设置。要恢复默认值请删除后重启：`rm /home/agent/.config/openab/config.toml`\n\nOpenAB 设置选项请参阅 [OpenAB 文档](https://github.com/openabdev/openab)。Grok 设置选项请参阅 [Grok Build 文档](https://x.ai/news/grok-build-cli)。\n\n## 停用\n\n部署时将 `Discord Bot Token` 和 `SLACK_BOT_TOKEN` 都留空即可。服务会进入 sleep 状态，不会崩溃。\n\n## 链接\n\n- [OpenAB GitHub](https://github.com/openabdev/openab)\n- [Grok Build（xAI）](https://x.ai/news/grok-build-cli)\n- [Agent Client Protocol](https://github.com/anthropics/agent-protocol)\n"
    zh-TW:
        description: |
            Open Agent Broker — 輕量的 Rust 程式，透過 stdio JSON-RPC 將 Discord 和 Slack 橋接到任何 ACP 相容的 coding CLI。此模板使用 Grok Build（xAI 官方 coding agent CLI）作為後端，透過 `grok agent stdio` 啟動。
            來源：https://github.com/openabdev/openab
        variables:
            - key: DISCORD_BOT_TOKEN
              type: STRING
              name: Discord Bot Token
              description: 從 https://discord.com/developers/applications 取得的 Token
            - key: GROK_CODE_XAI_API_KEY
              type: STRING
              name: Grok / xAI API Key（選填）
              description: 選填。xAI API key（xai-...），從 https://console.x.ai/ 取得。留空則部署後使用 device flow 認證（SuperGrok 訂閱），或之後在 Dashboard 新增 deployment key。
            - key: OPENAB_ALLOWED_CHANNELS
              type: STRING
              name: Discord 頻道 ID（選填）
              description: 選填。Bot 監聽的 Discord 頻道 ID，以逗號分隔。留空則允許所有頻道。範例：123456789012345678,234567890123456789
            - key: OPENAB_ALLOWED_USERS
              type: STRING
              name: Discord 用戶 ID（選填）
              description: 選填。以逗號分隔的 Discord 用戶 ID，限制可與 Bot 互動的用戶。留空則允許頻道中所有人。
        readme: "# OpenAB Grok\n\n[OpenAB](https://github.com/openabdev/openab) 是一個輕量的開源 Rust 程式，透過 stdio JSON-RPC 將 Discord 和 Slack 橋接到任何支援 [Agent Client Protocol](https://github.com/anthropics/agent-protocol) 的 coding CLI。\n\n此模板部署 Grok 變體 — 使用 xAI 官方 coding agent CLI [Grok Build](https://x.ai/news/grok-build-cli) 作為後端，透過 `grok agent stdio` 啟動。\n\n## 注意事項\n\n- **映像標籤：** 此模板使用固定版本（`0.8.3-beta.11`）。如需升級，請在 Zeabur Dashboard → 服務 → 設定中更改映像標籤。可用標籤：[GitHub Packages](https://github.com/openabdev/openab/pkgs/container/openab-grok)。\n- **持久化儲存：** `/home/agent` 掛載為持久化磁碟。Grok 認證資料（`~/.grok/auth.json`）、設定、config 會在重啟後保留。\n\n## 設定步驟\n\n### 1. 取得 Discord Bot Token\n\n1. 前往 https://discord.com/developers/applications，點擊 **New Application**\n2. 進入 **Bot** 頁籤 → 點擊 **Reset Token** → 複製 token\n3. 同一頁面往下滑，在 Privileged Gateway Intents 下啟用 **Message Content Intent**\n4. 前往 **OAuth2 → URL Generator** → 勾選 scope `bot` → 勾選權限：Send Messages、Send Messages in Threads、Create Public Threads、Read Message History、Add Reactions、Manage Messages\n5. 複製產生的 URL，在瀏覽器中開啟以邀請 Bot 到你的伺服器\n\n### 2. 取得 Discord 頻道 ID\n\n1. 開啟 Discord → 前往 **使用者設定**（齒輪圖示）→ **進階** → 啟用 **開發者模式**\n2. 對你要 Bot 回應的頻道按右鍵 → **複製頻道 ID**\n3. 多個頻道用逗號分隔：`123456789012345678,234567890123456789`\n\n### 3. 選擇認證方式\n\nGrok Build 支援三種認證來源，選一個適合你的場景：\n\n| 方法 | 適用場景 | 操作 |\n|------|----------|------|\n| **API Key** | 依使用量付費 API、CI / bot 部署 | 至 [console.x.ai](https://console.x.ai/) 取得 key，填入 `GROK_CODE_XAI_API_KEY` 變數 |\n| **Device-Auth** | SuperGrok 訂閱 | `GROK_CODE_XAI_API_KEY` 留空。部署後到服務 Exec 終端執行 `runuser -u agent -- grok login --device-auth`。CLI 會印出短代碼 + URL — 在任何裝置開啟 URL、輸入代碼、同意授權。Token 寫入 `/home/agent/.grok/auth.json`（重啟後保留）。 |\n| **Deployment Key** | xAI 企業客戶 | 部署後在 Zeabur Dashboard → 服務 → Variables 新增自訂變數 `GROK_DEPLOYMENT_KEY`。優先權高於 `auth.json`。 |\n\n> \U0001F4A1 跟 loopback OAuth 不同，Grok 的 device-auth 在任何 headless 環境都能用（不需 port-forward、不需 curl callback）。\n\n### 4. 部署\n\n填入變數後點擊部署。服務會自動連線到 Discord。如果選擇 **Device-Auth**，部署後再執行步驟 3 中的 login 指令。\n\n## Slack 設定（選用）\n\nOpenAB 支援透過 Socket Mode 連接 Slack，不需要公開 URL。\n\n1. 前往 https://api.slack.com/apps → **Create New App** → **From scratch**\n2. **Socket Mode** → 啟用 → 產生 App-Level Token，scope 選 `connections:write` → 複製 `xapp-...` token（`SLACK_APP_TOKEN`）\n3. **Event Subscriptions** → 啟用 → 新增 bot events：`app_mention`、`message.channels`、`message.groups`\n4. **OAuth & Permissions** → Bot Token Scopes → 新增：`app_mentions:read`、`chat:write`、`channels:history`、`groups:history`、`channels:read`、`groups:read`、`reactions:write`、`files:read`、`users:read`\n5. **Install App** → 安裝到工作區 → 複製 `xoxb-...` token（`SLACK_BOT_TOKEN`）\n6. 在每個要使用 Bot 的 Slack 頻道執行 `/invite @YourAppName`\n\n部署前填入 `SLACK_BOT_TOKEN` 和 `SLACK_APP_TOKEN` 變數。Discord 和 Slack 可同時運作。\n\n## 新增通訊平台（Telegram / LINE / Feishu / Google Chat / MS Teams / WeCom）\n\n若要橋接 Telegram、LINE、Feishu/Lark、Google Chat、MS Teams 或 WeCom（企業微信），請在同一個 Zeabur 專案中部署 [OpenAB Gateway 模板](https://zeabur.com/templates/IMRONB)，然後在此服務新增以下環境變數：\n\n- `GATEWAY_URL` = `ws://openab-gateway:8080/ws`\n- `GATEWAY_PLATFORM` = `telegram`、`line`、`feishu`、`googlechat`、`teams` 或 `wecom` 其中之一\n\n重新啟動服務後，啟動腳本會自動在 `config.toml` 中加入 `[gateway]` 區塊。\n\n## 使用方式\n\n- 在允許的 Discord 或 Slack 頻道中 **@mention Bot** 即可開始對話\n- OpenAB 會自動建立 **thread** 進行多輪對話 — 後續訊息不需要再 @mention\n- 每個 thread 對應一個持久的 Grok session（預設 24 小時 TTL）\n\n## 自訂設定\n\n| 檔案 | 說明 |\n|------|------|\n| `/home/agent/.config/openab/config.toml` | OpenAB 設定（sessions、reactions、STT 等） |\n| `/home/agent/.grok/auth.json` | Grok OAuth 認證（由 `grok login` 管理） |\n| `/home/agent/.grok/config.toml` | Grok runtime 設定 |\n\n`config.toml` 在首次啟動時從內建範本建立。之後請直接編輯檔案，環境變數僅用於初始設定。要恢復預設值請刪除後重啟：`rm /home/agent/.config/openab/config.toml`\n\nOpenAB 設定選項請參閱 [OpenAB 文件](https://github.com/openabdev/openab)。Grok 設定選項請參閱 [Grok Build 文件](https://x.ai/news/grok-build-cli)。\n\n## 停用\n\n部署時將 `Discord Bot Token` 和 `SLACK_BOT_TOKEN` 都留空即可。服務會進入 sleep 狀態，不會崩潰。\n\n## 連結\n\n- [OpenAB GitHub](https://github.com/openabdev/openab)\n- [Grok Build（xAI）](https://x.ai/news/grok-build-cli)\n- [Agent Client Protocol](https://github.com/anthropics/agent-protocol)\n"
