From 0609b7b97ca1e538e7719fcc52ccaeec903f3386 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 14 Aug 2026 17:56:49 +0000 Subject: [PATCH 1/2] Implement GrokBotBackend via computer gateway and authenticated reply callback. Add an in-process POST /internal/reply server so a Grok Bot agent can return text after sendPrompt wakes it asynchronously. grok-bot mode fails closed on missing env; openai remains the default path. Co-authored-by: Fly Over Coder --- .env.example | 20 ++- Dockerfile | 1 + README.md | 44 +++++-- docker-compose.yml | 4 + docs/PHASE2-GROK-BOT-BACKEND.md | 166 +++++++++++++------------ docs/PLAN.md | 26 ++-- src/agent/backend.ts | 7 ++ src/agent/grokBot.test.ts | 187 +++++++++++++++++++++++++++++ src/agent/grokBot.ts | 160 ++++++++++++++++++++++-- src/agent/openaiCompatible.test.ts | 14 --- src/config.test.ts | 68 ++++++++++- src/config.ts | 49 ++++++++ src/discord/bot.ts | 5 +- src/http/pendingReplies.ts | 81 +++++++++++++ src/http/replyServer.test.ts | 144 ++++++++++++++++++++++ src/http/replyServer.ts | 181 ++++++++++++++++++++++++++++ src/index.ts | 45 +++++-- 17 files changed, 1070 insertions(+), 132 deletions(-) create mode 100644 src/agent/grokBot.test.ts create mode 100644 src/http/pendingReplies.ts create mode 100644 src/http/replyServer.test.ts create mode 100644 src/http/replyServer.ts diff --git a/.env.example b/.env.example index d12f5db..7750a47 100644 --- a/.env.example +++ b/.env.example @@ -12,14 +12,30 @@ 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 +# 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 diff --git a/Dockerfile b/Dockerfile index ba5070c..7886482 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/README.md b/README.md index 7ea69fb..0a50dfe 100644 --- a/README.md +++ b/README.md @@ -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 ``` @@ -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 @@ -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` — published by Docker Compose | +| `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` | @@ -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 `. +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 | @@ -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. @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index 4f3ac8a..d911b77 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,6 +4,10 @@ services: restart: unless-stopped env_file: - .env + ports: + # Authenticated Grok Bot callback (POST /internal/reply). Not the Grok Bot gateway. + - "8788:8788" volumes: # Optional: override the default soul without rebuilding - ./SOUL.md:/app/SOUL.md:ro + - ./examples:/app/examples:ro diff --git a/docs/PHASE2-GROK-BOT-BACKEND.md b/docs/PHASE2-GROK-BOT-BACKEND.md index 26795b2..bc42d41 100644 --- a/docs/PHASE2-GROK-BOT-BACKEND.md +++ b/docs/PHASE2-GROK-BOT-BACKEND.md @@ -1,111 +1,117 @@ -# 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 `. +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 ` — **fail closed** if unset or wrong → 401 | +| Body | `{ "correlationId": string, "text": string }` (`error` optional) | +| Unknown / expired id | 404 | +| Missing fields | 400 | +| 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 publishes `8788: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 `) +- `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? \ No newline at end of file +## 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” diff --git a/docs/PLAN.md b/docs/PLAN.md index 33859cd..1ab9f3e 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -12,7 +12,7 @@ Use-case specificity (persona, tools, routines) belongs in the **Grok Bot**, not Ship a real `GrokBotBackend` once Grok Bot exposes a Discord/Channels-style inbound API. This repo is the community connector for that path. -**Phase 1** keeps `OpenAICompatibleBackend` as the runnable stand-in (xAI / OpenAI / OpenRouter chat completions) so individuals and teams can use Discord today. `GrokBotBackend` is an explicit stub until the API exists — we do not invent it. +**Phase 1** keeps `OpenAICompatibleBackend` as the default runnable path (xAI / OpenAI / OpenRouter chat completions). `GrokBotBackend` can optionally wake a Grok Bot agent via that computer's unofficial private HTTP gateway plus an authenticated bridge callback — not an official Discord/Channels API. ## Phase 1 scope @@ -39,9 +39,10 @@ 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] M --> B B --> D ``` @@ -57,7 +58,8 @@ flowchart LR | `src/discord/bot.ts` | Client, messageCreate handler, ignore bots/self | | `src/agent/backend.ts` | `AgentBackend` interface | | `src/agent/openaiCompatible.ts` | Phase 1 runnable: chat completions + memory + optional tools | -| `src/agent/grokBot.ts` | Stub — awaiting Grok Bot Channels-style API | +| `src/agent/grokBot.ts` | Unofficial computer-gateway client (`POST /api/sendPrompt`) + callback wait | +| `src/http/replyServer.ts` | Authenticated `POST /internal/reply` for the Grok Bot agent | | `src/agent/memory.ts` | In-memory per-channel/thread history with length cap | | `src/agent/tools/webSearch.ts` | Brave and/or Tavily if keys present | | `src/index.ts` | Load config, pick backend, start bot | @@ -77,7 +79,15 @@ flowchart LR | `DISCORD_FREE_RESPONSE_CHANNELS` | no | Channel IDs: reply without @mention | | `DISCORD_REQUIRE_MENTION` | no | Default `true` outside free-response channels (DMs never require mention) | | `DISCORD_HOME_CHANNEL` | no | Optional home channel ID (logged / future routing) | -| `AGENT_BACKEND` | no | `openai` (default, Phase 1) \| `grok-bot` (stub → North Star) | +| `AGENT_BACKEND` | no | `openai` (default) \| `grok-bot` (unofficial gateway + callback) | +| `GROK_BOT_GATEWAY_URL` | if grok-bot | Private computer gateway base (do not expose `:1340` publicly) | +| `GROK_BOT_TOKEN` | if grok-bot | Bearer from that computer's `gateway.json` | +| `GROK_BOT_AGENT_ID` | if grok-bot | Target agent id | +| `GROK_BOT_TIMEOUT_MS` | no | Default `120000` | +| `BRIDGE_HTTP_HOST` | no | Default `0.0.0.0` | +| `BRIDGE_HTTP_PORT` | no | Default `8788` | +| `BRIDGE_PUBLIC_URL` | if grok-bot | Reachable from the Grok Bot computer | +| `BRIDGE_REPLY_TOKEN` | if grok-bot | Bearer for `POST /internal/reply` | | `API_BASE_URL` | if openai | e.g. `https://api.x.ai/v1` | | `API_KEY` | if openai | Provider API key | | `MODEL` | if openai | Model id | @@ -128,7 +138,7 @@ Point `SYSTEM_PROMPT_FILE` at an example, or replace with your Grok Bot’s own | Layer | Coverage | |-------|----------| -| Unit | Config parsing; access control matrix (guild/DM/roles); message split; rate limit; memory cap; backend stub error | +| Unit | Config parsing; access control matrix (guild/DM/roles); message split; rate limit; memory cap; reply-endpoint auth; Grok Bot sendPrompt + callback / timeout | | Manual | Invite bot → set allowlists → mention in free vs gated channels / DM → verify OpenAI-compatible reply | | CI | `npm ci` → `npm test` → `npm run build` | @@ -142,15 +152,15 @@ Point `SYSTEM_PROMPT_FILE` at an example, or replace with your Grok Bot’s own ## Phase 1 non-goals - No Azure Functions hosting -- No real Grok Bot Channels API client (stub only — North Star for Phase 2+) +- No invented official Grok Bot Discord/Channels API (interim path is only `/api/sendPrompt` + bridge callback) - No multi-tenant SaaS - No use-case-specific product logic in the bridge (gaming, sales, etc. belong in the agent) ## Phase 2 notes -See [PHASE2-GROK-BOT-BACKEND.md](./PHASE2-GROK-BOT-BACKEND.md) for the 2026-08-12 spike: no Discord Channels / inbound API yet; proposed contract + cutover checklist; stay on OpenAI-compatible until product catches up. +See [PHASE2-GROK-BOT-BACKEND.md](./PHASE2-GROK-BOT-BACKEND.md) for the interim unofficial computer-gateway + `/internal/reply` callback (2026-08-14). Official Discord Channels inbound API is still the North Star and may replace this. -- Implement `GrokBotBackend` only against a **documented** Discord/Channels-style inbound API; keep `AgentBackend` as the seam. +- Keep `AgentBackend` as the seam. Do not expose the Grok Bot gateway port publicly. - Possible later: persistent memory (SQLite/Redis), richer tool registry, slash commands as *supplement* to gateway, observability (structured logs / metrics). ## Implementation order diff --git a/src/agent/backend.ts b/src/agent/backend.ts index 4a1ac8e..36e5d4e 100644 --- a/src/agent/backend.ts +++ b/src/agent/backend.ts @@ -13,10 +13,17 @@ export interface AgentRequest { channelTopic?: string | null; /** Guild name when available. */ guildName?: string; + /** + * Optional delivery hook used by GrokBotBackend so POST /internal/reply + * can send the Discord message (split/~1900) before generate() resolves. + */ + deliverReply?: (text: string) => Promise; } export interface AgentResponse { text: string; + /** True when the backend already posted to Discord (skip a second send). */ + delivered?: boolean; } export interface AgentBackend { diff --git a/src/agent/grokBot.test.ts b/src/agent/grokBot.test.ts new file mode 100644 index 0000000..b9e0c35 --- /dev/null +++ b/src/agent/grokBot.test.ts @@ -0,0 +1,187 @@ +import { describe, expect, it, vi } from "vitest"; +import { PendingReplyStore } from "../http/pendingReplies.js"; +import { startReplyServer } from "../http/replyServer.js"; +import { + buildGrokBotPrompt, + GrokBotBackend, + GrokBotGatewayError, + joinUrl, +} from "./grokBot.js"; + +const request = { + conversationKey: "channel:123", + authorDisplayName: "Nate", + content: "where are cooking pots?", + channelName: "general", + threadName: "loot", + channelTopic: "team chat", + guildName: "Example Guild", +}; + +function backendOpts(overrides: Partial[0]> = {}) { + return { + gatewayUrl: "http://gateway.example:1340", + token: "gateway-token", + agentId: "agent-from-env", + timeoutMs: 5_000, + replyUrl: "http://bridge.example:8788/internal/reply", + replyToken: "reply-token", + pending: new PendingReplyStore(), + ...overrides, + }; +} + +function correlationIdFromPrompt(prompt: string): string { + const match = prompt.match(/"correlationId": "([^"]+)"/); + if (!match?.[1]) throw new Error("prompt missing correlationId"); + return match[1]; +} + +describe("buildGrokBotPrompt", () => { + it("includes correlationId, replyUrl, Discord context, and bearer instructions", () => { + const prompt = buildGrokBotPrompt( + request, + "corr-abc", + "http://bridge.example:8788/internal/reply", + "reply-token", + ); + + expect(prompt).toContain("corr-abc"); + expect(prompt).toContain("http://bridge.example:8788/internal/reply"); + expect(prompt).toContain("Authorization: Bearer"); + expect(prompt).toContain("conversationKey: channel:123"); + expect(prompt).toContain("channelName: general"); + expect(prompt).toContain("threadName: loot"); + expect(prompt).toContain("channelTopic: team chat"); + expect(prompt).toContain("guildName: Example Guild"); + expect(prompt).toContain("authorDisplayName: Nate"); + expect(prompt).toContain("where are cooking pots?"); + expect(prompt).toContain("---BEGIN DISCORD_BRIDGE_REPLY---"); + }); +}); + +describe("GrokBotBackend", () => { + it("POSTs sendPrompt with correlationId and replyUrl, then resolves from the callback", async () => { + const pending = new PendingReplyStore(); + const calls: Array<{ url: string; init: RequestInit }> = []; + + const fetchImpl: typeof fetch = async (url, init) => { + calls.push({ url: String(url), init: init ?? {} }); + return new Response("{}", { status: 200 }); + }; + + const grok = new GrokBotBackend( + backendOpts({ + pending, + fetchImpl, + agentId: "agent-from-env", + }), + ); + + const generatePromise = grok.generate(request); + await vi.waitFor(() => expect(calls).toHaveLength(1)); + + const sent = JSON.parse(String(calls[0]!.init.body)) as { agentId: string; prompt: string }; + expect(calls[0]!.url).toBe("http://gateway.example:1340/api/sendPrompt"); + expect(calls[0]!.init.headers).toMatchObject({ + Authorization: "Bearer gateway-token", + }); + expect(sent.agentId).toBe("agent-from-env"); + expect(sent.prompt).toContain("http://bridge.example:8788/internal/reply"); + expect(sent.prompt).toContain("where are cooking pots?"); + expect(sent.prompt).toContain("conversationKey: channel:123"); + + const correlationId = correlationIdFromPrompt(sent.prompt); + await expect(pending.complete(correlationId, "Check houses near traders.")).resolves.toBe(true); + await expect(generatePromise).resolves.toEqual({ + text: "Check houses near traders.", + delivered: false, + }); + }); + + it("resolves generate() when POST /internal/reply completes the pending request", async () => { + const pending = new PendingReplyStore(); + const server = await startReplyServer({ + host: "127.0.0.1", + port: 0, + replyToken: "reply-token", + pending, + }); + + try { + const calls: string[] = []; + const fetchImpl: typeof fetch = async (_url, init) => { + const body = JSON.parse(String(init?.body)) as { prompt: string }; + calls.push(body.prompt); + return new Response("{}", { status: 200 }); + }; + + const grok = new GrokBotBackend(backendOpts({ pending, fetchImpl })); + const generatePromise = grok.generate(request); + await vi.waitFor(() => expect(calls).toHaveLength(1)); + + const correlationId = correlationIdFromPrompt(calls[0]!); + const res = await fetch(`http://127.0.0.1:${server.port}/internal/reply`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer reply-token", + }, + body: JSON.stringify({ correlationId, text: "Traders sell pots." }), + }); + + expect(res.status).toBe(200); + await expect(generatePromise).resolves.toEqual({ + text: "Traders sell pots.", + delivered: false, + }); + } finally { + await server.close(); + } + }); + + it("delivers to Discord via the pending callback before generate() resolves", async () => { + const pending = new PendingReplyStore(); + const delivered: string[] = []; + const calls: string[] = []; + const fetchImpl: typeof fetch = async (_url, init) => { + calls.push(String(init?.body)); + return new Response("{}", { status: 200 }); + }; + const grok = new GrokBotBackend(backendOpts({ pending, fetchImpl })); + + const generatePromise = grok.generate({ + ...request, + deliverReply: async (text) => { + delivered.push(text); + }, + }); + await vi.waitFor(() => expect(calls).toHaveLength(1)); + const body = JSON.parse(calls[0]!) as { prompt: string }; + await pending.complete(correlationIdFromPrompt(body.prompt), "Posted first."); + await expect(generatePromise).resolves.toEqual({ text: "Posted first.", delivered: true }); + expect(delivered).toEqual(["Posted first."]); + }); + + it("times out when the agent never callbacks", async () => { + const fetchImpl: typeof fetch = async () => new Response("{}", { status: 200 }); + const grok = new GrokBotBackend(backendOpts({ fetchImpl, timeoutMs: 40 })); + + await expect(grok.generate(request)).rejects.toThrow(/timed out waiting for a reply/i); + }); + + it("maps gateway HTTP errors to a short Discord-friendly string", async () => { + const fetchImpl: typeof fetch = async () => new Response("nope", { status: 502 }); + const grok = new GrokBotBackend(backendOpts({ fetchImpl })); + + await expect(grok.generate(request)).rejects.toBeInstanceOf(GrokBotGatewayError); + await expect(grok.generate(request)).rejects.toThrow(/HTTP 502/); + }); +}); + +describe("joinUrl", () => { + it("joins gateway and public URL bases without double slashes", () => { + expect(joinUrl("http://host:1340/", "/api/sendPrompt")).toBe("http://host:1340/api/sendPrompt"); + expect(joinUrl("http://bridge:8788", "internal/reply")).toBe("http://bridge:8788/internal/reply"); + }); +}); diff --git a/src/agent/grokBot.ts b/src/agent/grokBot.ts index 0f9fb8a..927c3ce 100644 --- a/src/agent/grokBot.ts +++ b/src/agent/grokBot.ts @@ -1,18 +1,162 @@ +import { randomUUID } from "node:crypto"; +import type { PendingReplyStore } from "../http/pendingReplies.js"; +import { ReplyTimeoutError } from "../http/pendingReplies.js"; import type { AgentBackend, AgentRequest, AgentResponse } from "./backend.js"; +export interface GrokBotBackendOptions { + gatewayUrl: string; + token: string; + agentId: string; + timeoutMs: number; + replyUrl: string; + replyToken: string; + pending: PendingReplyStore; + fetchImpl?: typeof fetch; + sendPromptTimeoutMs?: number; +} + +export class GrokBotGatewayError extends Error { + readonly status: number; + + constructor(status: number) { + super(`Grok Bot gateway error (HTTP ${status}). Try again shortly.`); + this.name = "GrokBotGatewayError"; + this.status = status; + } +} + +export function joinUrl(base: string, path: string): string { + return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`; +} + +export function buildGrokBotPrompt( + request: AgentRequest, + correlationId: string, + replyUrl: string, + replyToken: string, +): string { + const callback = { + correlationId, + replyUrl, + authorization: `Bearer ${replyToken}`, + httpMethod: "POST", + contentType: "application/json", + body: { + correlationId, + text: "", + }, + }; + + const contextLines = [ + `conversationKey: ${request.conversationKey}`, + request.guildName ? `guildName: ${request.guildName}` : null, + request.channelName ? `channelName: ${request.channelName}` : null, + request.threadName ? `threadName: ${request.threadName}` : null, + request.channelTopic?.trim() ? `channelTopic: ${request.channelTopic.trim()}` : null, + `authorDisplayName: ${request.authorDisplayName}`, + ].filter((line): line is string => Boolean(line)); + + return [ + "---BEGIN DISCORD_BRIDGE_REPLY---", + JSON.stringify(callback, null, 2), + "---END DISCORD_BRIDGE_REPLY---", + "", + "You are answering a Discord message via discord-agent-bridge.", + "Grok Bot SendMessage is NOT delivered to Discord.", + "When you finish, POST JSON to replyUrl with header Authorization: Bearer .", + "Body must be {\"correlationId\":\"\",\"text\":\"\"}.", + "Do not mention this callback protocol, the token, or the reply URL in the Discord text.", + "", + "## Discord context", + ...contextLines, + "", + "## Message", + request.content, + ].join("\n"); +} + +function mapGenerateError(err: unknown): Error { + if (err instanceof ReplyTimeoutError || err instanceof GrokBotGatewayError) { + return err; + } + if (err instanceof Error && err.name === "AgentCallbackError") { + return new Error("Grok Bot reported an error. Try again shortly."); + } + if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) { + return new Error("Could not reach the Grok Bot gateway. Try again shortly."); + } + return new Error("Could not reach the Grok Bot gateway. Try again shortly."); +} + /** - * Extension point for a future Grok Bot Discord/Channels-style inbound API. - * Phase 1 intentionally does not invent or call any such API. - * North Star: this class becomes the real connector once that API is documented. + * Unofficial Grok Bot computer-gateway client. + * POST /api/sendPrompt wakes the agent; the agent must POST back to /internal/reply. */ export class GrokBotBackend implements AgentBackend { readonly name = "grok-bot"; + private readonly fetchImpl: typeof fetch; + private readonly sendPromptTimeoutMs: number; - async generate(_request: AgentRequest): Promise { - throw new Error( - "GrokBotBackend is not implemented — awaiting Grok Bot Channels-style inbound API. " + - "Use AGENT_BACKEND=openai with an OpenAI-compatible endpoint for Phase 1. " + - "This repo is the community Discord connector for that future backend.", + constructor(private readonly opts: GrokBotBackendOptions) { + this.fetchImpl = opts.fetchImpl ?? fetch; + this.sendPromptTimeoutMs = opts.sendPromptTimeoutMs ?? 15_000; + } + + async generate(request: AgentRequest): Promise { + const correlationId = randomUUID(); + const prompt = buildGrokBotPrompt( + request, + correlationId, + this.opts.replyUrl, + this.opts.replyToken, + ); + const replyPromise = this.opts.pending.register( + correlationId, + this.opts.timeoutMs, + request.deliverReply, ); + + try { + await this.sendPrompt(prompt); + } catch (err) { + this.opts.pending.fail(correlationId, err instanceof Error ? err : new Error(String(err))); + await replyPromise.catch(() => undefined); + throw mapGenerateError(err); + } + + try { + const text = await replyPromise; + return { text, delivered: Boolean(request.deliverReply) }; + } catch (err) { + throw mapGenerateError(err); + } + } + + private async sendPrompt(prompt: string): Promise { + const url = joinUrl(this.opts.gatewayUrl, "/api/sendPrompt"); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), this.sendPromptTimeoutMs); + + let res: Response; + try { + res = await this.fetchImpl(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.opts.token}`, + }, + body: JSON.stringify({ + agentId: this.opts.agentId, + prompt, + }), + signal: controller.signal, + }); + } finally { + clearTimeout(timer); + } + + if (!res.ok) { + throw new GrokBotGatewayError(res.status); + } } } diff --git a/src/agent/openaiCompatible.test.ts b/src/agent/openaiCompatible.test.ts index d2bccac..d55b072 100644 --- a/src/agent/openaiCompatible.test.ts +++ b/src/agent/openaiCompatible.test.ts @@ -1,21 +1,7 @@ import { describe, expect, it } from "vitest"; -import { GrokBotBackend } from "./grokBot.js"; import { OpenAICompatibleBackend } from "./openaiCompatible.js"; import { createWebSearchProviders, webSearchToolDefinitions } from "./tools/webSearch.js"; -describe("GrokBotBackend", () => { - it("throws a clear not-implemented error", async () => { - const backend = new GrokBotBackend(); - await expect( - backend.generate({ - conversationKey: "c", - authorDisplayName: "n", - content: "hi", - }), - ).rejects.toThrow(/not implemented — awaiting Grok Bot Channels-style inbound API/i); - }); -}); - describe("OpenAICompatibleBackend", () => { it("calls chat completions and stores assistant reply", async () => { const calls: unknown[] = []; diff --git a/src/config.test.ts b/src/config.test.ts index c690288..8b93378 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -42,6 +42,11 @@ describe("loadConfig", () => { expect(cfg.systemPrompt).toMatch(/model `m`/); expect(cfg.temperature).toBe(0.7); expect(cfg.maxTokens).toBe(1024); + expect(cfg.bridgeHttpHost).toBe("0.0.0.0"); + expect(cfg.bridgeHttpPort).toBe(8788); + expect(cfg.grokBotTimeoutMs).toBe(120_000); + expect(cfg.grokBotGatewayUrl).toBeNull(); + expect(cfg.bridgeReplyToken).toBeNull(); }); it("fails closed without DISCORD_BOT_TOKEN", () => { @@ -67,12 +72,24 @@ describe("loadConfig", () => { ).toThrow(/API_BASE_URL/); }); - it("allows grok-bot backend without API settings", () => { - const soul = writeSoul(); - const cfg = loadConfig({ + function grokBotEnv(soul: string, overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv { + return { DISCORD_BOT_TOKEN: "tok", SYSTEM_PROMPT_FILE: soul, AGENT_BACKEND: "grok-bot", + GROK_BOT_GATEWAY_URL: "http://127.0.0.1:1340", + GROK_BOT_TOKEN: "gw-token", + GROK_BOT_AGENT_ID: "agent-from-env", + BRIDGE_PUBLIC_URL: "http://bridge.example:8788", + BRIDGE_REPLY_TOKEN: "reply-token", + ...overrides, + }; + } + + it("allows grok-bot backend without OpenAI API settings when gateway vars are set", () => { + const soul = writeSoul(); + const cfg = loadConfig({ + ...grokBotEnv(soul), DISCORD_ALLOW_ALL_USERS: "true", }); expect(cfg.agentBackend).toBe("grok-bot"); @@ -80,15 +97,56 @@ describe("loadConfig", () => { expect(cfg.allowDms).toBe(false); expect(cfg.dmOnly).toBe(false); expect(cfg.allowedGuilds).toEqual([]); + expect(cfg.grokBotGatewayUrl).toBe("http://127.0.0.1:1340"); + expect(cfg.grokBotAgentId).toBe("agent-from-env"); + expect(cfg.bridgePublicUrl).toBe("http://bridge.example:8788"); + expect(cfg.bridgeHttpHost).toBe("0.0.0.0"); + expect(cfg.bridgeHttpPort).toBe(8788); + expect(cfg.grokBotTimeoutMs).toBe(120_000); }); - it("requires ALLOW_DMS when DM_ONLY is set", () => { + it("fails closed when grok-bot required vars are missing", () => { const soul = writeSoul(); expect(() => loadConfig({ DISCORD_BOT_TOKEN: "tok", SYSTEM_PROMPT_FILE: soul, AGENT_BACKEND: "grok-bot", + }), + ).toThrow(/GROK_BOT_GATEWAY_URL/); + expect(() => loadConfig(grokBotEnv(soul, { GROK_BOT_TOKEN: "" }))).toThrow(/GROK_BOT_TOKEN/); + expect(() => loadConfig(grokBotEnv(soul, { GROK_BOT_AGENT_ID: "" }))).toThrow( + /GROK_BOT_AGENT_ID/, + ); + expect(() => loadConfig(grokBotEnv(soul, { BRIDGE_PUBLIC_URL: "" }))).toThrow( + /BRIDGE_PUBLIC_URL/, + ); + expect(() => loadConfig(grokBotEnv(soul, { BRIDGE_REPLY_TOKEN: "" }))).toThrow( + /BRIDGE_REPLY_TOKEN/, + ); + }); + + it("parses grok-bot timeout and bridge listen settings", () => { + const soul = writeSoul(); + const cfg = loadConfig( + grokBotEnv(soul, { + GROK_BOT_TIMEOUT_MS: "90000", + BRIDGE_HTTP_HOST: "127.0.0.1", + BRIDGE_HTTP_PORT: "9090", + }), + ); + expect(cfg.grokBotTimeoutMs).toBe(90_000); + expect(cfg.bridgeHttpHost).toBe("127.0.0.1"); + expect(cfg.bridgeHttpPort).toBe(9090); + }); + + it("requires ALLOW_DMS when DM_ONLY is set", () => { + const soul = writeSoul(); + expect(() => + loadConfig({ + DISCORD_BOT_TOKEN: "tok", + SYSTEM_PROMPT_FILE: soul, + ...grokBotEnv(soul), DISCORD_DM_ONLY: "true", DISCORD_ALLOW_DMS: "false", }), @@ -100,7 +158,7 @@ describe("loadConfig", () => { const cfg = loadConfig({ DISCORD_BOT_TOKEN: "tok", SYSTEM_PROMPT_FILE: soul, - AGENT_BACKEND: "grok-bot", + ...grokBotEnv(soul), DISCORD_ALLOW_ALL_USERS: "true", DISCORD_ALLOWED_GUILDS: "g1, g2", DISCORD_ALLOW_DMS: "true", diff --git a/src/config.ts b/src/config.ts index 0a61ae9..64ac486 100644 --- a/src/config.ts +++ b/src/config.ts @@ -27,6 +27,14 @@ export interface Config { rateLimitWindowMs: number; braveApiKey: string | null; tavilyApiKey: string | null; + grokBotGatewayUrl: string | null; + grokBotToken: string | null; + grokBotAgentId: string | null; + grokBotTimeoutMs: number; + bridgeHttpHost: string; + bridgeHttpPort: number; + bridgePublicUrl: string | null; + bridgeReplyToken: string | null; } function parseBool(value: string | undefined, defaultValue: boolean): boolean { @@ -91,12 +99,45 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { - Do not claim to be ChatGPT, OpenAI, Claude, or any other vendor unless the model id actually is that product.`; } + const grokBotGatewayUrl = env.GROK_BOT_GATEWAY_URL?.trim() || null; + const grokBotToken = env.GROK_BOT_TOKEN?.trim() || null; + const grokBotAgentId = env.GROK_BOT_AGENT_ID?.trim() || null; + const grokBotTimeoutMs = parseNumber(env.GROK_BOT_TIMEOUT_MS, 120_000); + const bridgeHttpHost = env.BRIDGE_HTTP_HOST?.trim() || "0.0.0.0"; + const bridgeHttpPort = parseNumber(env.BRIDGE_HTTP_PORT, 8788); + const bridgePublicUrl = env.BRIDGE_PUBLIC_URL?.trim() || null; + const bridgeReplyToken = env.BRIDGE_REPLY_TOKEN?.trim() || null; + if (agentBackend === "openai") { if (!apiBaseUrl) throw new Error("API_BASE_URL is required when AGENT_BACKEND=openai"); if (!apiKey) throw new Error("API_KEY is required when AGENT_BACKEND=openai"); if (!model) throw new Error("MODEL is required when AGENT_BACKEND=openai"); } + if (agentBackend === "grok-bot") { + if (!grokBotGatewayUrl) { + throw new Error("GROK_BOT_GATEWAY_URL is required when AGENT_BACKEND=grok-bot"); + } + if (!grokBotToken) { + throw new Error("GROK_BOT_TOKEN is required when AGENT_BACKEND=grok-bot"); + } + if (!grokBotAgentId) { + throw new Error("GROK_BOT_AGENT_ID is required when AGENT_BACKEND=grok-bot"); + } + if (!bridgePublicUrl) { + throw new Error("BRIDGE_PUBLIC_URL is required when AGENT_BACKEND=grok-bot"); + } + if (!bridgeReplyToken) { + throw new Error("BRIDGE_REPLY_TOKEN is required when AGENT_BACKEND=grok-bot"); + } + if (grokBotTimeoutMs <= 0) { + throw new Error("GROK_BOT_TIMEOUT_MS must be a positive number"); + } + if (!Number.isInteger(bridgeHttpPort) || bridgeHttpPort < 1 || bridgeHttpPort > 65535) { + throw new Error("BRIDGE_HTTP_PORT must be an integer between 1 and 65535"); + } + } + const allowDms = parseBool(env.DISCORD_ALLOW_DMS, false); const dmOnly = parseBool(env.DISCORD_DM_ONLY, false); if (dmOnly && !allowDms) { @@ -127,5 +168,13 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { rateLimitWindowMs: parseNumber(env.RATE_LIMIT_WINDOW_MS, 60_000), braveApiKey: env.BRAVE_API_KEY?.trim() || null, tavilyApiKey: env.TAVILY_API_KEY?.trim() || null, + grokBotGatewayUrl, + grokBotToken, + grokBotAgentId, + grokBotTimeoutMs, + bridgeHttpHost, + bridgeHttpPort, + bridgePublicUrl, + bridgeReplyToken, }; } diff --git a/src/discord/bot.ts b/src/discord/bot.ts index f552fa1..0a79aef 100644 --- a/src/discord/bot.ts +++ b/src/discord/bot.ts @@ -169,9 +169,12 @@ async function handleMessage( threadName: ctx.threadName, channelTopic: ctx.channelTopic, guildName: ctx.guildName, + deliverReply: (text) => sendSplitReply(message, text), }), ); - await sendSplitReply(message, result.text); + if (!result.delivered) { + await sendSplitReply(message, result.text); + } } catch (err) { const detail = err instanceof Error ? err.message : String(err); console.error("[bridge] agent error:", detail); diff --git a/src/http/pendingReplies.ts b/src/http/pendingReplies.ts new file mode 100644 index 0000000..f2ee265 --- /dev/null +++ b/src/http/pendingReplies.ts @@ -0,0 +1,81 @@ +export class ReplyTimeoutError extends Error { + readonly correlationId: string; + + constructor(correlationId: string) { + super("Grok Bot timed out waiting for a reply. Try again shortly."); + this.name = "ReplyTimeoutError"; + this.correlationId = correlationId; + } +} + +export class AgentCallbackError extends Error { + constructor(message: string) { + super(message); + this.name = "AgentCallbackError"; + } +} + +interface PendingEntry { + resolve: (text: string) => void; + reject: (error: Error) => void; + timer: ReturnType; + deliver?: (text: string) => Promise; +} + +/** + * In-process waiters for Grok Bot agent callbacks keyed by correlationId. + */ +export class PendingReplyStore { + private readonly pending = new Map(); + + register( + correlationId: string, + timeoutMs: number, + deliver?: (text: string) => Promise, + ): Promise { + if (this.pending.has(correlationId)) { + return Promise.reject(new Error("Duplicate correlationId")); + } + + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(correlationId); + reject(new ReplyTimeoutError(correlationId)); + }, timeoutMs); + this.pending.set(correlationId, { resolve, reject, timer, deliver }); + }); + } + + async complete(correlationId: string, text: string): Promise { + const entry = this.pending.get(correlationId); + if (!entry) return false; + clearTimeout(entry.timer); + this.pending.delete(correlationId); + try { + if (entry.deliver) { + await entry.deliver(text); + } + entry.resolve(text); + } catch (err) { + entry.reject(err instanceof Error ? err : new Error(String(err))); + } + return true; + } + + fail(correlationId: string, error: Error): boolean { + const entry = this.pending.get(correlationId); + if (!entry) return false; + clearTimeout(entry.timer); + this.pending.delete(correlationId); + entry.reject(error); + return true; + } + + has(correlationId: string): boolean { + return this.pending.has(correlationId); + } + + get size(): number { + return this.pending.size; + } +} diff --git a/src/http/replyServer.test.ts b/src/http/replyServer.test.ts new file mode 100644 index 0000000..bda97da --- /dev/null +++ b/src/http/replyServer.test.ts @@ -0,0 +1,144 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { PendingReplyStore, ReplyTimeoutError } from "./pendingReplies.js"; +import { startReplyServer, type StartedReplyServer } from "./replyServer.js"; + +const TOKEN = "test-reply-token"; + +async function listen( + pending: PendingReplyStore, + replyToken: string | null = TOKEN, +): Promise { + return startReplyServer({ + host: "127.0.0.1", + port: 0, + replyToken, + pending, + }); +} + +async function postReply( + server: StartedReplyServer, + opts: { + token?: string | null; + body?: unknown; + raw?: string; + headers?: Record; + } = {}, +): Promise<{ status: number; json: Record }> { + const headers: Record = { + "Content-Type": "application/json", + ...opts.headers, + }; + if (opts.token !== null) { + headers.Authorization = `Bearer ${opts.token ?? TOKEN}`; + } + const res = await fetch(`http://127.0.0.1:${server.port}/internal/reply`, { + method: "POST", + headers, + body: opts.raw ?? JSON.stringify(opts.body ?? {}), + }); + return { status: res.status, json: (await res.json()) as Record }; +} + +describe("POST /internal/reply", () => { + const servers: StartedReplyServer[] = []; + + afterEach(async () => { + while (servers.length > 0) { + const server = servers.pop(); + await server?.close(); + } + }); + + it("returns 401 when the bearer token is missing", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const res = await postReply(server, { token: null, body: { correlationId: "c", text: "hi" } }); + expect(res.status).toBe(401); + expect(res.json.error).toBe("unauthorized"); + }); + + it("returns 401 when the bearer token is wrong", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const res = await postReply(server, { + token: "wrong-token", + body: { correlationId: "c", text: "hi" }, + }); + expect(res.status).toBe(401); + expect(res.json.error).toBe("unauthorized"); + }); + + it("returns 401 when the server token is unset (fail closed)", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending, null); + servers.push(server); + + const res = await postReply(server, { + token: "anything", + body: { correlationId: "c", text: "hi" }, + }); + expect(res.status).toBe(401); + }); + + it("returns 400 when required fields are missing", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const missingId = await postReply(server, { body: { text: "hi" } }); + expect(missingId.status).toBe(400); + + const missingText = await postReply(server, { body: { correlationId: "c1" } }); + expect(missingText.status).toBe(400); + + const empty = await postReply(server, { body: { correlationId: " ", text: " " } }); + expect(empty.status).toBe(400); + }); + + it("returns 404 for an unknown correlationId", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const res = await postReply(server, { + body: { correlationId: "missing", text: "hello" }, + }); + expect(res.status).toBe(404); + expect(res.json.error).toBe("unknown_correlation_id"); + }); + + it("returns 404 for an expired correlationId", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const waiter = pending.register("expired", 20); + await expect(waiter).rejects.toBeInstanceOf(ReplyTimeoutError); + + const res = await postReply(server, { + body: { correlationId: "expired", text: "too late" }, + }); + expect(res.status).toBe(404); + }); + + it("resolves a pending generate waiter on a valid reply", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const waiter = pending.register("corr-1", 5_000); + const res = await postReply(server, { + body: { correlationId: "corr-1", text: "Pots are in houses and trader inventories." }, + }); + + expect(res.status).toBe(200); + expect(res.json.ok).toBe(true); + await expect(waiter).resolves.toBe("Pots are in houses and trader inventories."); + expect(pending.has("corr-1")).toBe(false); + }); +}); diff --git a/src/http/replyServer.ts b/src/http/replyServer.ts new file mode 100644 index 0000000..fc0e36c --- /dev/null +++ b/src/http/replyServer.ts @@ -0,0 +1,181 @@ +import { createHash, timingSafeEqual } from "node:crypto"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import { AgentCallbackError, type PendingReplyStore } from "./pendingReplies.js"; + +export interface ReplyServerOptions { + host: string; + port: number; + /** Fail closed when unset or empty — every request is 401. */ + replyToken: string | null; + pending: PendingReplyStore; +} + +export interface StartedReplyServer { + host: string; + port: number; + close(): Promise; +} + +const MAX_BODY_BYTES = 1_000_000; + +interface ReplyBody { + correlationId?: unknown; + text?: unknown; + error?: unknown; +} + +function sendJson(res: ServerResponse, status: number, body: Record): void { + const payload = JSON.stringify(body); + res.writeHead(status, { + "Content-Type": "application/json; charset=utf-8", + "Content-Length": Buffer.byteLength(payload), + }); + res.end(payload); +} + +function headerValue(req: IncomingMessage, name: string): string | undefined { + const raw = req.headers[name]; + if (Array.isArray(raw)) return raw[0]; + return raw; +} + +function extractBearer(header: string | undefined): string | null { + if (!header) return null; + const match = header.match(/^Bearer\s+(\S+)\s*$/i); + return match?.[1] ?? null; +} + +function tokenMatches(provided: string, expected: string): boolean { + const a = createHash("sha256").update(provided).digest(); + const b = createHash("sha256").update(expected).digest(); + return timingSafeEqual(a, b); +} + +function authorize(req: IncomingMessage, expected: string | null): boolean { + if (!expected) return false; + const provided = extractBearer(headerValue(req, "authorization")); + if (!provided) return false; + return tokenMatches(provided, expected); +} + +function readBody(req: IncomingMessage, maxBytes: number): Promise { + return new Promise((resolve, reject) => { + const chunks: Buffer[] = []; + let size = 0; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + if (size > maxBytes) { + req.destroy(); + reject(new Error("payload_too_large")); + return; + } + chunks.push(chunk); + }); + req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + req.on("error", reject); + }); +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.trim() !== ""; +} + +async function handleReply( + req: IncomingMessage, + res: ServerResponse, + opts: ReplyServerOptions, +): Promise { + if (req.method !== "POST") { + sendJson(res, 405, { error: "method_not_allowed" }); + return; + } + + if (!authorize(req, opts.replyToken)) { + sendJson(res, 401, { error: "unauthorized" }); + return; + } + + let raw: string; + try { + raw = await readBody(req, MAX_BODY_BYTES); + } catch { + sendJson(res, 400, { error: "invalid_body" }); + return; + } + + let parsed: ReplyBody; + try { + parsed = JSON.parse(raw) as ReplyBody; + } catch { + sendJson(res, 400, { error: "invalid_body" }); + return; + } + + if (!isNonEmptyString(parsed.correlationId)) { + sendJson(res, 400, { error: "invalid_body" }); + return; + } + + const correlationId = parsed.correlationId.trim(); + const text = typeof parsed.text === "string" ? parsed.text : ""; + const errorMessage = isNonEmptyString(parsed.error) ? parsed.error.trim() : null; + + if (!text.trim() && !errorMessage) { + sendJson(res, 400, { error: "invalid_body" }); + return; + } + + if (!opts.pending.has(correlationId)) { + sendJson(res, 404, { error: "unknown_correlation_id" }); + return; + } + + if (errorMessage && !text.trim()) { + opts.pending.fail(correlationId, new AgentCallbackError(errorMessage)); + sendJson(res, 200, { ok: true }); + return; + } + + if (!(await opts.pending.complete(correlationId, text))) { + sendJson(res, 404, { error: "unknown_correlation_id" }); + return; + } + + sendJson(res, 200, { ok: true }); +} + +export async function startReplyServer(opts: ReplyServerOptions): Promise { + const server: Server = createServer((req, res) => { + const url = req.url?.split("?")[0] ?? ""; + if (url !== "/internal/reply") { + sendJson(res, 404, { error: "not_found" }); + return; + } + void handleReply(req, res, opts).catch(() => { + if (!res.headersSent) { + sendJson(res, 500, { error: "internal_error" }); + } + }); + }); + + await new Promise((resolve, reject) => { + const onError = (err: Error) => reject(err); + server.once("error", onError); + server.listen(opts.port, opts.host, () => { + server.off("error", onError); + resolve(); + }); + }); + + const addr = server.address(); + const port = typeof addr === "object" && addr ? addr.port : opts.port; + + return { + host: opts.host, + port, + close: () => + new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }), + }; +} diff --git a/src/index.ts b/src/index.ts index 85c3347..20796c1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,13 @@ import "dotenv/config"; import type { AgentBackend } from "./agent/backend.js"; -import { GrokBotBackend } from "./agent/grokBot.js"; +import { GrokBotBackend, joinUrl } from "./agent/grokBot.js"; import { OpenAICompatibleBackend } from "./agent/openaiCompatible.js"; import { loadConfig } from "./config.js"; import { startBot } from "./discord/bot.js"; +import { PendingReplyStore } from "./http/pendingReplies.js"; +import { startReplyServer } from "./http/replyServer.js"; -function createBackend(config: ReturnType): AgentBackend { - if (config.agentBackend === "grok-bot") { - return new GrokBotBackend(); - } - +function createOpenAiBackend(config: ReturnType): AgentBackend { return new OpenAICompatibleBackend({ apiBaseUrl: config.apiBaseUrl!, apiKey: config.apiKey!, @@ -23,15 +21,48 @@ function createBackend(config: ReturnType): AgentBackend { }); } +async function createGrokBotBackend(config: ReturnType): Promise { + const pending = new PendingReplyStore(); + const replyUrl = joinUrl(config.bridgePublicUrl!, "/internal/reply"); + const server = await startReplyServer({ + host: config.bridgeHttpHost, + port: config.bridgeHttpPort, + replyToken: config.bridgeReplyToken, + pending, + }); + console.log(`[bridge] reply endpoint listening on ${server.host}:${server.port} path=/internal/reply`); + return new GrokBotBackend({ + gatewayUrl: config.grokBotGatewayUrl!, + token: config.grokBotToken!, + agentId: config.grokBotAgentId!, + timeoutMs: config.grokBotTimeoutMs, + replyUrl, + replyToken: config.bridgeReplyToken!, + pending, + }); +} + +async function createBackend(config: ReturnType): Promise { + if (config.agentBackend === "grok-bot") { + return createGrokBotBackend(config); + } + return createOpenAiBackend(config); +} + async function main(): Promise { const config = loadConfig(); + const grokBits = + config.agentBackend === "grok-bot" + ? ` gateway=${config.grokBotGatewayUrl} agentId=${config.grokBotAgentId} publicUrl=${config.bridgePublicUrl}` + : ""; console.log( `[bridge] backend=${config.agentBackend}` + (config.model ? ` model=${config.model}` : "") + (config.apiBaseUrl ? ` base=${config.apiBaseUrl}` : "") + + grokBits + ` soul=${config.systemPromptFile}`, ); - const backend = createBackend(config); + const backend = await createBackend(config); await startBot(config, backend); } From f6eaac98020b24fa58476dbf8b580614d47d2ded Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 14 Aug 2026 18:01:33 +0000 Subject: [PATCH 2/2] Keep pending Grok Bot replies until Discord delivery succeeds. complete() no longer drops the waiter before sendSplitReply finishes. A delivery failure returns HTTP 503 and leaves the correlationId retryable. Compose now maps host and container ports from BRIDGE_HTTP_PORT. Co-authored-by: Fly Over Coder --- .env.example | 1 + README.md | 2 +- docker-compose.yml | 3 +- docs/PHASE2-GROK-BOT-BACKEND.md | 3 +- src/agent/grokBot.test.ts | 2 +- src/http/pendingReplies.test.ts | 33 ++++++++++++++++++++ src/http/pendingReplies.ts | 53 ++++++++++++++++++++++++++------- src/http/replyServer.test.ts | 40 +++++++++++++++++++++++++ src/http/replyServer.ts | 7 ++++- 9 files changed, 128 insertions(+), 16 deletions(-) create mode 100644 src/http/pendingReplies.test.ts diff --git a/.env.example b/.env.example index 7750a47..9b30c3c 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,7 @@ MODEL=grok-2-latest # 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= diff --git a/README.md b/README.md index 0a50dfe..df88736 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ docker compose up --build | `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` — published by Docker Compose | +| `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 | diff --git a/docker-compose.yml b/docker-compose.yml index d911b77..a14a72e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,7 +6,8 @@ services: - .env ports: # Authenticated Grok Bot callback (POST /internal/reply). Not the Grok Bot gateway. - - "8788:8788" + # 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 diff --git a/docs/PHASE2-GROK-BOT-BACKEND.md b/docs/PHASE2-GROK-BOT-BACKEND.md index bc42d41..ed519cb 100644 --- a/docs/PHASE2-GROK-BOT-BACKEND.md +++ b/docs/PHASE2-GROK-BOT-BACKEND.md @@ -58,6 +58,7 @@ flowchart LR | 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 }` | This is **not** an unauthenticated public webhook. Do not log `BRIDGE_REPLY_TOKEN` or `GROK_BOT_TOKEN`. @@ -76,7 +77,7 @@ This is **not** an unauthenticated public webhook. Do not log `BRIDGE_REPLY_TOKE | `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 publishes `8788:8788`) | +| `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 | diff --git a/src/agent/grokBot.test.ts b/src/agent/grokBot.test.ts index b9e0c35..ba9337d 100644 --- a/src/agent/grokBot.test.ts +++ b/src/agent/grokBot.test.ts @@ -92,7 +92,7 @@ describe("GrokBotBackend", () => { expect(sent.prompt).toContain("conversationKey: channel:123"); const correlationId = correlationIdFromPrompt(sent.prompt); - await expect(pending.complete(correlationId, "Check houses near traders.")).resolves.toBe(true); + await expect(pending.complete(correlationId, "Check houses near traders.")).resolves.toBe("ok"); await expect(generatePromise).resolves.toEqual({ text: "Check houses near traders.", delivered: false, diff --git a/src/http/pendingReplies.test.ts b/src/http/pendingReplies.test.ts new file mode 100644 index 0000000..2dc2620 --- /dev/null +++ b/src/http/pendingReplies.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vitest"; +import { PendingReplyStore } from "./pendingReplies.js"; + +describe("PendingReplyStore.complete", () => { + it("does not resolve generate() when delivery fails, and a later retry can succeed", async () => { + const pending = new PendingReplyStore(); + let attempts = 0; + const waiter = pending.register("id-1", 5_000, async () => { + attempts += 1; + if (attempts === 1) throw new Error("transient discord error"); + }); + + await expect(pending.complete("id-1", "retry me")).resolves.toBe("delivery_failed"); + expect(pending.has("id-1")).toBe(true); + + let settled = false; + void waiter.then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(settled).toBe(false); + + await expect(pending.complete("id-1", "retry me")).resolves.toBe("ok"); + await expect(waiter).resolves.toBe("retry me"); + expect(attempts).toBe(2); + expect(pending.has("id-1")).toBe(false); + }); +}); diff --git a/src/http/pendingReplies.ts b/src/http/pendingReplies.ts index f2ee265..f25bdc5 100644 --- a/src/http/pendingReplies.ts +++ b/src/http/pendingReplies.ts @@ -15,15 +15,20 @@ export class AgentCallbackError extends Error { } } +export type CompleteResult = "missing" | "ok" | "delivery_failed"; + interface PendingEntry { resolve: (text: string) => void; reject: (error: Error) => void; timer: ReturnType; + deadlineMs: number; deliver?: (text: string) => Promise; + delivering: boolean; } /** * In-process waiters for Grok Bot agent callbacks keyed by correlationId. + * Entries stay registered until Discord delivery succeeds (or the waiter times out / is failed). */ export class PendingReplyStore { private readonly pending = new Map(); @@ -38,28 +43,41 @@ export class PendingReplyStore { } return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.pending.delete(correlationId); - reject(new ReplyTimeoutError(correlationId)); - }, timeoutMs); - this.pending.set(correlationId, { resolve, reject, timer, deliver }); + const entry = { + resolve, + reject, + deadlineMs: Date.now() + timeoutMs, + deliver, + delivering: false, + } as PendingEntry; + this.pending.set(correlationId, entry); + this.armTimeout(correlationId, entry); }); } - async complete(correlationId: string, text: string): Promise { + async complete(correlationId: string, text: string): Promise { const entry = this.pending.get(correlationId); - if (!entry) return false; + if (!entry) return "missing"; + if (entry.delivering) return "delivery_failed"; + + entry.delivering = true; clearTimeout(entry.timer); - this.pending.delete(correlationId); + try { if (entry.deliver) { await entry.deliver(text); } + this.pending.delete(correlationId); entry.resolve(text); - } catch (err) { - entry.reject(err instanceof Error ? err : new Error(String(err))); + return "ok"; + } catch { + entry.delivering = false; + if (!this.pending.has(correlationId)) { + return "missing"; + } + this.armTimeout(correlationId, entry); + return "delivery_failed"; } - return true; } fail(correlationId: string, error: Error): boolean { @@ -78,4 +96,17 @@ export class PendingReplyStore { get size(): number { return this.pending.size; } + + private armTimeout(correlationId: string, entry: PendingEntry): void { + const remaining = entry.deadlineMs - Date.now(); + if (remaining <= 0) { + this.pending.delete(correlationId); + entry.reject(new ReplyTimeoutError(correlationId)); + return; + } + entry.timer = setTimeout(() => { + this.pending.delete(correlationId); + entry.reject(new ReplyTimeoutError(correlationId)); + }, remaining); + } } diff --git a/src/http/replyServer.test.ts b/src/http/replyServer.test.ts index bda97da..4d86742 100644 --- a/src/http/replyServer.test.ts +++ b/src/http/replyServer.test.ts @@ -141,4 +141,44 @@ describe("POST /internal/reply", () => { await expect(waiter).resolves.toBe("Pots are in houses and trader inventories."); expect(pending.has("corr-1")).toBe(false); }); + + it("keeps the pending entry when Discord delivery fails so a later retry can complete", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + let attempts = 0; + const waiter = pending.register("corr-retry", 5_000, async () => { + attempts += 1; + if (attempts === 1) throw new Error("discord 502"); + }); + + const first = await postReply(server, { + body: { correlationId: "corr-retry", text: "hello from Discord" }, + }); + expect(first.status).toBe(503); + expect(first.json.error).toBe("delivery_failed"); + expect(pending.has("corr-retry")).toBe(true); + + let settled = false; + void waiter.then( + () => { + settled = true; + }, + () => { + settled = true; + }, + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(settled).toBe(false); + + const second = await postReply(server, { + body: { correlationId: "corr-retry", text: "hello from Discord" }, + }); + expect(second.status).toBe(200); + expect(second.json.ok).toBe(true); + await expect(waiter).resolves.toBe("hello from Discord"); + expect(attempts).toBe(2); + expect(pending.has("corr-retry")).toBe(false); + }); }); diff --git a/src/http/replyServer.ts b/src/http/replyServer.ts index fc0e36c..e0eeefa 100644 --- a/src/http/replyServer.ts +++ b/src/http/replyServer.ts @@ -136,10 +136,15 @@ async function handleReply( return; } - if (!(await opts.pending.complete(correlationId, text))) { + const result = await opts.pending.complete(correlationId, text); + if (result === "missing") { sendJson(res, 404, { error: "unknown_correlation_id" }); return; } + if (result === "delivery_failed") { + sendJson(res, 503, { error: "delivery_failed" }); + return; + } sendJson(res, 200, { ok: true }); }