Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,31 @@ DISCORD_FREE_RESPONSE_CHANNELS=
DISCORD_REQUIRE_MENTION=true
DISCORD_HOME_CHANNEL=

# Backend: openai (Phase 1 runnable) | grok-bot (stub — North Star)
# Backend: openai (Phase 1 default) | grok-bot (unofficial computer-gateway + bridge callback)
AGENT_BACKEND=openai

# OpenAI-compatible provider until GrokBotBackend is available (xAI / OpenAI / OpenRouter / etc.)
# OpenAI-compatible provider (required when AGENT_BACKEND=openai)
API_BASE_URL=https://api.x.ai/v1
API_KEY=
MODEL=grok-2-latest

# Grok Bot computer gateway (required when AGENT_BACKEND=grok-bot).
# Private LAN / Tailscale / SSH tunnel only — never expose :1340 to the internet.
# GROK_BOT_TOKEN is the bearer from that computer's gateway.json (treat like a password).
# GROK_BOT_GATEWAY_URL=http://grok-bot-host:1340
# GROK_BOT_TOKEN=
# GROK_BOT_AGENT_ID=
# GROK_BOT_TIMEOUT_MS=120000

# Bridge callback the Grok Bot agent POSTs to (required when AGENT_BACKEND=grok-bot).
# BRIDGE_PUBLIC_URL must be reachable from the Grok Bot computer (not localhost on that machine).
# BRIDGE_REPLY_TOKEN is a shared secret you create — treat like a password; do not log it.
# BRIDGE_HTTP_HOST=0.0.0.0
# Compose publishes host:container as ${BRIDGE_HTTP_PORT:-8788}:${BRIDGE_HTTP_PORT:-8788}
# BRIDGE_HTTP_PORT=8788
# BRIDGE_PUBLIC_URL=http://bridge-host:8788
# BRIDGE_REPLY_TOKEN=

# Neutral default; see examples/team-assistant and examples/gaming-helper
SYSTEM_PROMPT_FILE=SOUL.md
TEMPERATURE=0.7
Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ RUN npm test && npm run build
FROM node:20-bookworm-slim AS runtime
WORKDIR /app
ENV NODE_ENV=production
EXPOSE 8788
COPY package.json package-lock.json* ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
Expand Down
44 changes: 37 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ flowchart LR
A --> R[Rate limit]
R --> M[AgentBackend]
M --> O[OpenAICompatibleBackend]
M --> G[GrokBotBackend stub]
M --> G[GrokBotBackend]
O --> T[Optional web search]
O --> Mem[Per-channel memory]
G --> GW[Grok Bot computer gateway]
G --> CB[POST /internal/reply]
M --> B
B --> D
```
Expand All @@ -22,14 +24,15 @@ flowchart LR

| | |
|--|--|
| **North Star** | Real `GrokBotBackend` once Grok Bot exposes a Discord/Channels-style inbound API — this repo is the community connector for that. |
| **Phase 1 (today)** | Runnable `OpenAICompatibleBackend` (xAI / OpenAI / OpenRouter) + team-friendly access control + `GrokBotBackend` stub. No invented Grok Bot API, no multi-tenant SaaS, no Azure Functions hosting. |
| **North Star** | Official Grok Bot Discord/Channels inbound API — this repo stays the community connector for that. |
| **Phase 1 (today)** | `OpenAICompatibleBackend` is the default production path (xAI / OpenAI / OpenRouter). |
| **Interim grok-bot** | `GrokBotBackend` can wake a Grok Bot agent via that computer's private HTTP gateway (`POST /api/sendPrompt`) and receive the answer on an authenticated `POST /internal/reply`. Unofficial; may break. |

## Requirements

- Node.js **20+**
- A Discord bot with **Message Content Intent** enabled
- An OpenAI-compatible API key for Phase 1 (xAI, OpenAI, OpenRouter, etc.)
- An OpenAI-compatible API key for the default backend (xAI, OpenAI, OpenRouter, etc.), **or** Grok Bot computer-gateway settings when `AGENT_BACKEND=grok-bot`

## Discord Developer Portal setup

Expand Down Expand Up @@ -79,10 +82,18 @@ docker compose up --build
| `DISCORD_FREE_RESPONSE_CHANNELS` | no | Channel IDs where @mention is not required |
| `DISCORD_REQUIRE_MENTION` | no | Default `true` outside free-response channels (DMs never require mention) |
| `DISCORD_HOME_CHANNEL` | no | Optional home channel (logged at startup) |
| `AGENT_BACKEND` | no | `openai` (Phase 1 default) or `grok-bot` (stub / North Star) |
| `AGENT_BACKEND` | no | `openai` (default) or `grok-bot` |
| `API_BASE_URL` | if openai | e.g. `https://api.x.ai/v1` or `https://api.openai.com/v1` |
| `API_KEY` | if openai | Provider API key |
| `MODEL` | if openai | Model id |
| `GROK_BOT_GATEWAY_URL` | if grok-bot | Private computer gateway base, e.g. `http://host:1340` |
| `GROK_BOT_TOKEN` | if grok-bot | Bearer token from that computer's `gateway.json` (password) |
| `GROK_BOT_AGENT_ID` | if grok-bot | Target agent id (from env, not hardcoded) |
| `GROK_BOT_TIMEOUT_MS` | no | Default `120000` — how long `generate()` waits for `/internal/reply` |
| `BRIDGE_HTTP_HOST` | no | Default `0.0.0.0` — listen address for the callback server |
| `BRIDGE_HTTP_PORT` | no | Default `8788`. Compose maps host and container to this port (`${BRIDGE_HTTP_PORT:-8788}:${BRIDGE_HTTP_PORT:-8788}`) |
| `BRIDGE_PUBLIC_URL` | if grok-bot | URL the **Grok Bot computer** uses to reach this bridge (not `localhost` on that machine) |
| `BRIDGE_REPLY_TOKEN` | if grok-bot | Shared secret for `Authorization: Bearer` on `POST /internal/reply` (password) |
| `SYSTEM_PROMPT_FILE` | no | Default `SOUL.md` (neutral); swap for your agent persona |
| `TEMPERATURE` | no | Default `0.7` |
| `MAX_TOKENS` | no | Default `1024` |
Expand All @@ -94,8 +105,25 @@ docker compose up --build

Access control fails closed: if `DISCORD_ALLOW_ALL_USERS` is false and both user/role allowlists are empty, nobody is served.

`AGENT_BACKEND=grok-bot` also fails closed if any of `GROK_BOT_GATEWAY_URL`, `GROK_BOT_TOKEN`, `GROK_BOT_AGENT_ID`, `BRIDGE_PUBLIC_URL`, or `BRIDGE_REPLY_TOKEN` is missing.

Web search tools are registered **only** when at least one of `BRAVE_API_KEY` / `TAVILY_API_KEY` is set (Phase 1 OpenAI-compatible path).

### Grok Bot callback (interim)

There is no official Discord plugin. The working community path is:

1. Bridge `POST`s `{ agentId, prompt }` to `GROK_BOT_GATEWAY_URL/api/sendPrompt` (wakes the agent; does **not** return the reply).
2. The prompt includes a machine-readable block: `correlationId`, `replyUrl` (`BRIDGE_PUBLIC_URL/internal/reply`), and how to send `Authorization: Bearer <BRIDGE_REPLY_TOKEN>`.
3. The Grok Bot agent `POST`s `{ correlationId, text }` back to the bridge.
4. The bridge posts `text` to the matching Discord channel/thread (same ~1900 split as the OpenAI path).

`BRIDGE_PUBLIC_URL` must be reachable **from the Grok Bot computer**. The bridge often runs in Docker on a different machine than the Grok Bot computer, so `localhost` on the Grok Bot side is not the bridge. Use Tailscale, an SSH tunnel, or another private path.

**Do not** expose the Grok Bot gateway port (`:1340`) to the internet. **Do not** put `DISCORD_BOT_TOKEN` on the Grok Bot side. Treat `GROK_BOT_TOKEN` and `BRIDGE_REPLY_TOKEN` like passwords; never commit or log them.

This callback is unofficial and may break. See [docs/PHASE2-GROK-BOT-BACKEND.md](docs/PHASE2-GROK-BOT-BACKEND.md).

## Scripts

| Script | Action |
Expand All @@ -108,6 +136,8 @@ Web search tools are registered **only** when at least one of `BRAVE_API_KEY` /
## Security

- **Never commit** `.env`, tokens, or API keys. `.gitignore` excludes `.env`.
- Treat `GROK_BOT_TOKEN` and `BRIDGE_REPLY_TOKEN` like passwords. Do not log them.
- `POST /internal/reply` is authenticated and fail-closed (missing/wrong token → 401). It is not a public webhook.
- Keep the Discord application **private** until you trust your allowlists.
- Prefer a private server (or DM-only personal use) for the first run.
- The bot ignores other bots and itself; replies are split near 1900 characters.
Expand All @@ -116,10 +146,10 @@ Web search tools are registered **only** when at least one of `BRAVE_API_KEY` /

1. Map allowlists → `DISCORD_ALLOWED_USERS` / `DISCORD_ALLOWED_ROLES` / `DISCORD_ALLOWED_GUILDS` / `DISCORD_FREE_RESPONSE_CHANNELS`.
2. Point `SYSTEM_PROMPT_FILE` at your soul/instructions (or copy into `SOUL.md`). Keep proprietary host code out of this repo.
3. Use `AGENT_BACKEND=openai` with your OpenAI-compatible provider until the real Grok Bot inbound API lands.
3. Use `AGENT_BACKEND=openai` (default) or `AGENT_BACKEND=grok-bot` with the private computer gateway + callback (see above).
4. Run as an always-on process (`npm start` or Docker); smoke-test in `DISCORD_HOME_CHANNEL` or a DM.

See [docs/PLAN.md](docs/PLAN.md) for the living Phase 1 plan and Phase 2 notes (`GrokBotBackend`).
See [docs/PLAN.md](docs/PLAN.md) and [docs/PHASE2-GROK-BOT-BACKEND.md](docs/PHASE2-GROK-BOT-BACKEND.md).

## License

Expand Down
5 changes: 5 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ services:
restart: unless-stopped
env_file:
- .env
ports:
# Authenticated Grok Bot callback (POST /internal/reply). Not the Grok Bot gateway.
# Host and container ports both follow BRIDGE_HTTP_PORT (Compose interpolates from .env).
- "${BRIDGE_HTTP_PORT:-8788}:${BRIDGE_HTTP_PORT:-8788}"
volumes:
# Optional: override the default soul without rebuilding
- ./SOUL.md:/app/SOUL.md:ro
- ./examples:/app/examples:ro
167 changes: 87 additions & 80 deletions docs/PHASE2-GROK-BOT-BACKEND.md
Original file line number Diff line number Diff line change
@@ -1,111 +1,118 @@
# Phase 2 spike — real `GrokBotBackend` cutover
# Phase 2 — `GrokBotBackend` (interim computer-gateway callback)

Date: 2026-08-12
Status: **blocked on product** — no first-party Discord / Channels inbound API yet
Date: 2026-08-14
Status: **interim, unofficial** — no first-party Discord / Channels inbound API
Repo role: keep Discord UX + access control; persona/tools live in a Grok Bot agent

## What we have today (Phase 1)
## What we have today

| Piece | State |
|-------|--------|
| Discord gateway (`discord.js`) | Live as HermesHelper |
| `OpenAICompatibleBackend` | Production path (OpenRouter `x-ai/grok-4.6`) |
| `GrokBotBackend` | Stub that throws (intentional) |
| Discord gateway (`discord.js`) | Production |
| `OpenAICompatibleBackend` | **Default production path** (`AGENT_BACKEND=openai`) |
| `GrokBotBackend` | Implemented against the **undocumented-but-real** Grok Bot computer HTTP gateway + a bridge callback |
| Access / rate limit / split / thread memory / channel context | Done |
| Grok Bot agent `Discord Gaming Helper` | Exists with full gaming persona — **not wired to Discord** |
| Grok Bot Channels UI | Per-agent pane supports Channels (e.g. GitHub on CoS); **no Discord connector in marketplace** |
| `POST /internal/reply` | Authenticated in-process HTTP server on the bridge |

## Finding (2026-08-12)
Grok Bot has **no official Discord plugin**. The working community path is a private HTTP gateway on each Grok Bot computer (typically port **1340**, bearer token in that computer's `gateway.json`).

1. Cursor / Grok Bot plugin catalog has **Slack** and other connectors; **no Discord** plugin/connector.
2. Grok Bot launch materials describe bots, computers, Slack/Teams-style team chat — not a documented public HTTP “inbound message” API for Discord.
3. Inventing a private API against the app would violate this repo’s Phase 1 rule (“do not invent the Grok Bot API”).
4. Therefore **North Star cutover is not implementable yet**. Phase 1 OpenAI-compatible remains the correct production backend.
Verified gateway methods (do not invent others):

## Target architecture (when Channels Discord or inbound API lands)
- `POST /api/listAgents`
- `POST /api/sendPrompt` `{ agentId, prompt }`
- `GET /health`

`sendPrompt` **wakes the agent asynchronously**. It does **not** return the agent's reply. Replies normally go to Grok Bot chat via the agent's `SendMessage`. Discord only receives text the agent `POST`s back to this bridge.

This design is **unofficial and may break** if the computer gateway changes.

## Interim architecture

```mermaid
flowchart LR
D[Discord Gateway] --> B[discord-agent-bridge]
B --> A[Access + rate limit]
A --> G[GrokBotBackend]
G --> API[Grok Bot inbound / Channels]
API --> Agent[Discord Gaming Helper agent]
Agent --> API
API --> G
G --> B
G --> GW[POST /api/sendPrompt]
GW --> Agent[Grok Bot agent]
Agent --> CB[POST /internal/reply]
CB --> B
B --> D
```

Bridge keeps: Discord auth, allowlists, free-response, typing, split replies, conversation keys.
Agent owns: soul, tools, memory beyond ephemeral bridge buffer, routines.

## Proposed `GrokBotBackend` contract (freeze this; implement when API exists)

Env (sketch):

| Variable | Purpose |
|----------|---------|
| `AGENT_BACKEND=grok-bot` | Select this backend |
| `GROK_BOT_INBOUND_URL` | Documented HTTPS endpoint |
| `GROK_BOT_API_KEY` / token | Auth for inbound |
| `GROK_BOT_AGENT_ID` | Target agent (e.g. Discord Gaming Helper) |
| `GROK_BOT_TIMEOUT_MS` | Request timeout |

Request body (map from `AgentRequest`):

```json
{
"agentId": "...",
"conversationKey": "thread:… or channel:…",
"authorDisplayName": "…",
"content": "…",
"channelName": "7dtd",
"threadName": "optional",
"channelTopic": "optional",
"guildName": "optional",
"metadata": { "platform": "discord", "source": "discord-agent-bridge" }
}
```
1. Discord message passes access control.
2. `GrokBotBackend.generate()` creates a `correlationId`, registers a pending waiter, and `POST`s `sendPrompt` to `GROK_BOT_GATEWAY_URL`.
3. The prompt includes a machine-readable `DISCORD_BRIDGE_REPLY` block plus the human Discord message and `AgentRequest` context.
4. The Grok Bot agent `POST`s `{ correlationId, text }` to `BRIDGE_PUBLIC_URL/internal/reply` with `Authorization: Bearer <BRIDGE_REPLY_TOKEN>`.
5. The bridge looks up the pending request, posts `text` to the matching Discord channel/thread (same ~1900 split as existing replies), then resolves `generate()`.
6. If nothing arrives within `GROK_BOT_TIMEOUT_MS` (default 120s), `generate()` fails so Discord is not stuck typing.

Response:
## Callback contract

```json
{ "text": "…" }
```
`POST /internal/reply`

Errors: map HTTP/timeouts to Discord’s existing “Sorry — I hit an error…” path.
Do **not** put Discord bot token into Grok Bot; bot token stays on the bridge host.
| Rule | Behavior |
|------|----------|
| Listen | `BRIDGE_HTTP_HOST` / `BRIDGE_HTTP_PORT` (defaults `0.0.0.0` / `8788`) |
| Auth | `Authorization: Bearer <BRIDGE_REPLY_TOKEN>` — **fail closed** if unset or wrong → 401 |
| Body | `{ "correlationId": string, "text": string }` (`error` optional) |
| Unknown / expired id | 404 |
| Missing fields | 400 |
| Discord delivery failure | 503 `{ "error": "delivery_failed" }` — pending entry kept for retry |
| Success | 200 `{ "ok": true }` |

## Cutover checklist (execute only after API is real)
This is **not** an unauthenticated public webhook. Do not log `BRIDGE_REPLY_TOKEN` or `GROK_BOT_TOKEN`.

1. Confirm official docs + auth model (OAuth vs API key vs channel connect card).
2. Implement `src/agent/grokBot.ts` against the documented schema; add vitest with mocked fetch.
3. Wire config validation for grok-bot env vars in `config.ts`.
4. Smoke-test: `#ask-hermes` + `#7dtd` mention → reply from **Discord Gaming Helper** persona/tools (not local SOUL.md).
5. Flip `.env` `AGENT_BACKEND=grok-bot`; keep OpenAI path as fallback.
6. Optionally shrink or remove local `SYSTEM_PROMPT_FILE` dependency for that mode.
7. Update README / PLAN Phase 2 from “stub” to “supported”.
`replyUrl` given to the agent is `BRIDGE_PUBLIC_URL + /internal/reply`. The Grok Bot computer is a **different machine** than the Docker host running the bridge, so `localhost` on the Grok Bot computer is not the bridge. Reachability options: Tailscale, SSH tunnel, or another private path.

## Interim options (optional; not North Star)
**Never** expose the Grok Bot gateway port (`:1340`) to the internet. **Never** put `DISCORD_BOT_TOKEN` on the Grok Bot side.

| Option | Pros | Cons |
|--------|------|------|
| **A. Stay on Phase 1** (recommended default) | Already works; low risk | Persona/tools not the full Grok Bot agent |
| **B. Persona sync** — periodically copy Discord Gaming Helper instructions into `SYSTEM_PROMPT_FILE` | Closer voice; still OpenRouter | No agent tools/routines/memory; drift risk |
| **C. Wait for official Discord Channel** — connect in agent info pane when it appears | True North Star; least invention | Unknown ETA |
| **D. Local Cursor-CLI Discord bridges** (e.g. community Cursor↔Discord projects) | Different stack | Not Grok Bot; splits identity |
## Env (grok-bot mode)

Recommendation: **A + C**. Keep HermesHelper on OpenRouter. Treat Discord Gaming Helper as the future target agent. Revisit when a Discord Channel connector or inbound API ships.
| Variable | Required | Purpose |
|----------|----------|---------|
| `AGENT_BACKEND=grok-bot` | yes (to select) | Select this backend |
| `GROK_BOT_GATEWAY_URL` | yes | e.g. `http://host:1340` |
| `GROK_BOT_TOKEN` | yes | Bearer from `gateway.json` |
| `GROK_BOT_AGENT_ID` | yes | Target agent id (from env; do not hardcode a single id) |
| `GROK_BOT_TIMEOUT_MS` | no | Default `120000` |
| `BRIDGE_HTTP_HOST` | no | Default `0.0.0.0` |
| `BRIDGE_HTTP_PORT` | no | Default `8788` (Compose maps `${BRIDGE_HTTP_PORT:-8788}:${BRIDGE_HTTP_PORT:-8788}`) |
| `BRIDGE_PUBLIC_URL` | yes | URL the Grok Bot computer uses to reach the bridge |
| `BRIDGE_REPLY_TOKEN` | yes | Shared secret for the callback |

## Watch list
OpenAI-compatible remains the default. grok-bot fails closed if required vars are missing.

- Grok Bot / Cursor Plugins marketplace: Discord
- Per-agent Channels UI: Discord connect card
- Forum / docs: “Channels”, “inbound”, “messaging”
- Any official webhook/HTTP agent invoke API
## Prompt block (what the agent must parse)

The bridge embeds a JSON block between `---BEGIN DISCORD_BRIDGE_REPLY---` / `---END DISCORD_BRIDGE_REPLY---` containing:

- `correlationId`
- `replyUrl`
- `authorization` (`Bearer <BRIDGE_REPLY_TOKEN>`)
- `httpMethod` / `contentType` / example `body`

Plus Discord context already on `AgentRequest`: `conversationKey`, `channelName`, `threadName`, `channelTopic`, `guildName`, `authorDisplayName`, `content`.

## Decision needed from Nathan
Persona stays in the Grok Bot agent / `SYSTEM_PROMPT_FILE`. This repo is plumbing.

1. Park backend implementation until Discord Channels exists? (**default yes**)
2. Want interim **persona sync** (Option B) so Discord voice matches Discord Gaming Helper sooner?
## Errors

Gateway HTTP failures and callback timeouts throw a short Discord-friendly error. The Discord message handler still uses the existing “Sorry — I hit an error generating a reply…” UX and logs the detail (without tokens).

## Official North Star (still blocked)

A documented Discord/Channels inbound API would replace this callback. Until then, do **not** invent a different official API — only `/api/sendPrompt` + this bridge callback.

## Cutover / smoke

1. Set grok-bot env vars; keep `AGENT_BACKEND=openai` as fallback.
2. Confirm `BRIDGE_PUBLIC_URL` is reachable from the Grok Bot computer (`POST /internal/reply` with a wrong token should 401; do not test with real tokens in logs).
3. Mention the bot in Discord → gateway `sendPrompt` → agent callback → Discord reply.
4. If the unofficial gateway changes, park grok-bot mode and stay on OpenAI.

## Watch list

- Official Discord Channel connector / inbound API
- Computer gateway path or auth changes
- Forum / docs: “Channels”, “inbound”, “messaging”
Loading
Loading