From 97f102a45645e53861af389d2caf8d6b6b01384b Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 14:29:47 -0500 Subject: [PATCH] Scope callback tokens and bound reply fan-out --- .env.example | 9 ++- README.md | 14 +++- docs/PHASE2-GROK-BOT-BACKEND.md | 10 +-- docs/PLAN.md | 2 +- src/agent/grokBot.test.ts | 63 ++++++++++++++-- src/agent/grokBot.ts | 36 +++++---- src/agent/memory.test.ts | 14 ++++ src/agent/memory.ts | 33 ++++++++- src/agent/openaiCompatible.test.ts | 86 ++++++++++++++++++++- src/agent/openaiCompatible.ts | 42 +++++++++-- src/config.test.ts | 29 ++++++++ src/config.ts | 44 +++++++++++ src/discord/bot.ts | 10 ++- src/discord/rateLimit.test.ts | 11 +++ src/discord/rateLimit.ts | 41 +++++++++- src/discord/reply.ts | 13 +++- src/http/pendingReplies.test.ts | 71 ++++++++++++++++-- src/http/pendingReplies.ts | 115 ++++++++++++++++++++++++++--- src/http/replyServer.test.ts | 96 ++++++++++++++++++------ src/http/replyServer.ts | 88 +++++++++++++++------- src/index.ts | 8 +- src/util/splitMessage.test.ts | 12 +++ src/util/splitMessage.ts | 24 +++++- 23 files changed, 751 insertions(+), 120 deletions(-) diff --git a/.env.example b/.env.example index 5e8e264..2a62bd3 100644 --- a/.env.example +++ b/.env.example @@ -33,22 +33,29 @@ MODEL=grok-2-latest # BRIDGE_PUBLIC_URL must be reachable from the Grok Bot computer. # Colocated host process: http://127.0.0.1:8788 with BRIDGE_HTTP_HOST=127.0.0.1 (host loopback only; not Docker). # Split-machine: when the bridge runs elsewhere, localhost on the Grok Bot computer is not the bridge. -# BRIDGE_REPLY_TOKEN is a shared secret you create — treat like a password; do not log it. +# BRIDGE_REPLY_TOKEN is a server-side key used to protect one-time callback capabilities. +# Create it locally, treat it like a password, and do not log it. # BRIDGE_HTTP_HOST=127.0.0.1 # Compose publishes host:container as ${BRIDGE_HTTP_PORT:-8788}:${BRIDGE_HTTP_PORT:-8788} # BRIDGE_HTTP_PORT=8788 # BRIDGE_PUBLIC_URL=http://127.0.0.1:8788 # BRIDGE_REPLY_TOKEN= +# CALLBACK_MAX_TEXT_CHARS=15000 +# DISCORD_REPLY_MAX_CHUNKS=8 # Neutral default; see examples/team-assistant and examples/gaming-helper SYSTEM_PROMPT_FILE=SOUL.md TEMPERATURE=0.7 MAX_TOKENS=1024 MEMORY_MAX_MESSAGES=20 +# MEMORY_MAX_KEYS=1000 RATE_LIMIT_PER_USER=5 RATE_LIMIT_WINDOW_MS=60000 +# RATE_LIMIT_MAX_KEYS=10000 # Optional web search for the OpenAI-compatible path (omit both = no tools) # BRAVE_API_KEY= # TAVILY_API_KEY= +# WEB_SEARCH_MAX_CALLS_PER_ROUND=2 +# WEB_SEARCH_MAX_CALLS_PER_REQUEST=4 diff --git a/README.md b/README.md index de64e96..83c4132 100644 --- a/README.md +++ b/README.md @@ -95,15 +95,21 @@ docker compose up --build | `BRIDGE_HTTP_HOST` | no | Default `0.0.0.0`. Colocated host process: bind `127.0.0.1` so the callback is localhost-only. | | `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. Colocated host process: `http://127.0.0.1:8788`. When the bridge runs on a different machine, that machine's `localhost` is not the bridge. | -| `BRIDGE_REPLY_TOKEN` | if grok-bot | Shared secret for `Authorization: Bearer` on `POST /internal/reply` (password) | +| `BRIDGE_REPLY_TOKEN` | if grok-bot | Server-side key used to protect per-request callback capabilities (password; never sent in prompts) | +| `CALLBACK_MAX_TEXT_CHARS` | no | Default `15000`. Reject larger Grok Bot callback replies before Discord delivery | +| `DISCORD_REPLY_MAX_CHUNKS` | no | Default `8`. Maximum Discord messages sent for one generated reply; longer replies are truncated with a marker | | `SYSTEM_PROMPT_FILE` | no | Default `SOUL.md` (neutral); swap for your agent persona | | `TEMPERATURE` | no | Default `0.7` | | `MAX_TOKENS` | no | Default `1024` | | `MEMORY_MAX_MESSAGES` | no | Default `20` (per channel/thread key) | +| `MEMORY_MAX_KEYS` | no | Default `1000`. Least-recently-used conversation keys are evicted above this cap | | `RATE_LIMIT_PER_USER` | no | Default `5` / window | | `RATE_LIMIT_WINDOW_MS` | no | Default `60000` | +| `RATE_LIMIT_MAX_KEYS` | no | Default `10000`. New keys fail closed while this many rate-limit buckets remain active | | `BRAVE_API_KEY` | no | Enables Brave web search tool | | `TAVILY_API_KEY` | no | Enables Tavily web search tool | +| `WEB_SEARCH_MAX_CALLS_PER_ROUND` | no | Default `2` web searches in one model tool round | +| `WEB_SEARCH_MAX_CALLS_PER_REQUEST` | no | Default `4` web searches for one Discord request | Access control fails closed: if `DISCORD_ALLOW_ALL_USERS` is false and both user/role allowlists are empty, nobody is served. @@ -116,7 +122,7 @@ Web search tools are registered **only** when at least one of `BRAVE_API_KEY` / 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 `. +2. The prompt includes a machine-readable block: `correlationId`, `replyUrl` (`BRIDGE_PUBLIC_URL/internal/reply`), and a fresh one-time bearer capability scoped to that request. 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). @@ -159,7 +165,7 @@ Then fill in: - `GROK_BOT_TOKEN` — bearer from that computer's `gateway.json` (treat like a password). Grok Bot computers commonly store this at `/home/box/sand-data/gateway.json`; use whatever path that computer actually uses. - `GROK_BOT_AGENT_ID` — from `POST /api/listAgents` on the gateway. Do not hardcode a real id in this repo. -- `BRIDGE_REPLY_TOKEN` — generate a random secret (`openssl rand -hex 32` or equivalent). Do not commit it. +- `BRIDGE_REPLY_TOKEN` — generate a random server-side key (`openssl rand -hex 32` or equivalent). It is not sent in prompts. Do not commit it. - Discord allowlists (`DISCORD_ALLOWED_USERS` / roles / guilds, or DMs). Keep the Discord application **private**. **Run** @@ -194,7 +200,7 @@ In this host-process mode, **never** expose `:1340` or `:8788` beyond localhost. ## Security - **Never commit** `.env`, tokens, or API keys. `.gitignore` excludes `.env` and `*.log`. -- Treat `GROK_BOT_TOKEN` and `BRIDGE_REPLY_TOKEN` like passwords. Do not log them. +- Treat `GROK_BOT_TOKEN` and `BRIDGE_REPLY_TOKEN` like passwords. The bridge keeps `BRIDGE_REPLY_TOKEN` server-side and sends only per-request callback capabilities. Do not log them. - `POST /internal/reply` is authenticated and fail-closed (missing/wrong token → 401). It is not a public webhook. - In colocated mode, bind the callback to `127.0.0.1` and do not expose `:1340` or `:8788` beyond localhost. - Keep the Discord application **private** until you trust your allowlists. diff --git a/docs/PHASE2-GROK-BOT-BACKEND.md b/docs/PHASE2-GROK-BOT-BACKEND.md index de3c1fb..a309d51 100644 --- a/docs/PHASE2-GROK-BOT-BACKEND.md +++ b/docs/PHASE2-GROK-BOT-BACKEND.md @@ -43,7 +43,7 @@ flowchart LR 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 `. +4. The Grok Bot agent `POST`s `{ correlationId, text }` to `BRIDGE_PUBLIC_URL/internal/reply` with the one-time bearer capability from that request's prompt. 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. @@ -54,14 +54,14 @@ flowchart LR | 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 | +| Auth | `Authorization: Bearer ` — **fail closed** if missing 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 }` | -This is **not** an unauthenticated public webhook. Do not log `BRIDGE_REPLY_TOKEN` or `GROK_BOT_TOKEN`. +This is **not** an unauthenticated public webhook. `BRIDGE_REPLY_TOKEN` remains server-side and protects the one-time capabilities. Do not log it, the capabilities, or `GROK_BOT_TOKEN`. `replyUrl` given to the agent is `BRIDGE_PUBLIC_URL + /internal/reply`. That URL must be reachable from the Grok Bot computer. Two topologies: @@ -86,7 +86,7 @@ This is **not** an unauthenticated public webhook. Do not log `BRIDGE_REPLY_TOKE | `BRIDGE_HTTP_HOST` | no | Default `0.0.0.0`. Colocated host process: `127.0.0.1` | | `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. Colocated host process: `http://127.0.0.1:8788` | -| `BRIDGE_REPLY_TOKEN` | yes | Shared secret for the callback (generate locally; do not commit) | +| `BRIDGE_REPLY_TOKEN` | yes | Server-side capability key (generate locally; do not commit or place in prompts) | OpenAI-compatible remains the default. grok-bot fails closed if required vars are missing. @@ -126,7 +126,7 @@ The bridge embeds a JSON block between `---BEGIN DISCORD_BRIDGE_REPLY---` / `--- - `correlationId` - `replyUrl` -- `authorization` (`Bearer `) +- `authorization` (`Bearer `) - `httpMethod` / `contentType` / example `body` Plus Discord context already on `AgentRequest`: `conversationKey`, `channelName`, `threadName`, `channelTopic`, `guildName`, `authorDisplayName`, `content`. diff --git a/docs/PLAN.md b/docs/PLAN.md index 92a64f1..adae837 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -87,7 +87,7 @@ flowchart LR | `BRIDGE_HTTP_HOST` | no | Default `0.0.0.0`. Colocated host process: `127.0.0.1` | | `BRIDGE_HTTP_PORT` | no | Default `8788` | | `BRIDGE_PUBLIC_URL` | if grok-bot | Reachable from the Grok Bot computer. Colocated host process: `http://127.0.0.1:8788`. When the bridge runs on a different machine, that machine's `localhost` is not the bridge. | -| `BRIDGE_REPLY_TOKEN` | if grok-bot | Bearer for `POST /internal/reply` | +| `BRIDGE_REPLY_TOKEN` | if grok-bot | Server-side key for per-request callback capabilities | | `API_BASE_URL` | if openai | e.g. `https://api.x.ai/v1` | | `API_KEY` | if openai | Provider API key | | `MODEL` | if openai | Model id | diff --git a/src/agent/grokBot.test.ts b/src/agent/grokBot.test.ts index ba9337d..eda7936 100644 --- a/src/agent/grokBot.test.ts +++ b/src/agent/grokBot.test.ts @@ -25,7 +25,6 @@ function backendOpts(overrides: Partial { it("includes correlationId, replyUrl, Discord context, and bearer instructions", () => { const prompt = buildGrokBotPrompt( @@ -62,7 +67,7 @@ describe("buildGrokBotPrompt", () => { describe("GrokBotBackend", () => { it("POSTs sendPrompt with correlationId and replyUrl, then resolves from the callback", async () => { - const pending = new PendingReplyStore(); + const pending = new PendingReplyStore("reusable-config-secret"); const calls: Array<{ url: string; init: RequestInit }> = []; const fetchImpl: typeof fetch = async (url, init) => { @@ -90,9 +95,16 @@ describe("GrokBotBackend", () => { 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"); + expect(sent.prompt).not.toContain("reusable-config-secret"); const correlationId = correlationIdFromPrompt(sent.prompt); - await expect(pending.complete(correlationId, "Check houses near traders.")).resolves.toBe("ok"); + await expect( + pending.complete( + correlationId, + capabilityTokenFromPrompt(sent.prompt), + "Check houses near traders.", + ), + ).resolves.toBe("ok"); await expect(generatePromise).resolves.toEqual({ text: "Check houses near traders.", delivered: false, @@ -104,7 +116,6 @@ describe("GrokBotBackend", () => { const server = await startReplyServer({ host: "127.0.0.1", port: 0, - replyToken: "reply-token", pending, }); @@ -121,11 +132,12 @@ describe("GrokBotBackend", () => { await vi.waitFor(() => expect(calls).toHaveLength(1)); const correlationId = correlationIdFromPrompt(calls[0]!); + const capabilityToken = capabilityTokenFromPrompt(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", + Authorization: `Bearer ${capabilityToken}`, }, body: JSON.stringify({ correlationId, text: "Traders sell pots." }), }); @@ -158,11 +170,50 @@ describe("GrokBotBackend", () => { }); 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 pending.complete( + correlationIdFromPrompt(body.prompt), + capabilityTokenFromPrompt(body.prompt), + "Posted first.", + ); await expect(generatePromise).resolves.toEqual({ text: "Posted first.", delivered: true }); expect(delivered).toEqual(["Posted first."]); }); + it("lets an authenticated delivery finish when the gateway request fails late", async () => { + const pending = new PendingReplyStore(); + let prompt = ""; + let rejectGateway: ((error: Error) => void) | undefined; + const fetchImpl: typeof fetch = async (_url, init) => { + const body = JSON.parse(String(init?.body)) as { prompt: string }; + prompt = body.prompt; + return new Promise((_resolve, reject) => { + rejectGateway = reject; + }); + }; + let finishDelivery: (() => void) | undefined; + const grok = new GrokBotBackend(backendOpts({ pending, fetchImpl })); + const generatePromise = grok.generate({ + ...request, + deliverReply: async () => + new Promise((resolve) => { + finishDelivery = resolve; + }), + }); + await vi.waitFor(() => expect(prompt).not.toBe("")); + + const completePromise = pending.complete( + correlationIdFromPrompt(prompt), + capabilityTokenFromPrompt(prompt), + "delivered", + ); + await vi.waitFor(() => expect(finishDelivery).toBeDefined()); + rejectGateway?.(new Error("late gateway failure")); + finishDelivery?.(); + + await expect(completePromise).resolves.toBe("ok"); + await expect(generatePromise).resolves.toEqual({ text: "delivered", delivered: true }); + }); + 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 })); diff --git a/src/agent/grokBot.ts b/src/agent/grokBot.ts index 927c3ce..24720fa 100644 --- a/src/agent/grokBot.ts +++ b/src/agent/grokBot.ts @@ -9,7 +9,6 @@ export interface GrokBotBackendOptions { agentId: string; timeoutMs: number; replyUrl: string; - replyToken: string; pending: PendingReplyStore; fetchImpl?: typeof fetch; sendPromptTimeoutMs?: number; @@ -33,12 +32,12 @@ export function buildGrokBotPrompt( request: AgentRequest, correlationId: string, replyUrl: string, - replyToken: string, + capabilityToken: string, ): string { const callback = { correlationId, replyUrl, - authorization: `Bearer ${replyToken}`, + authorization: `Bearer ${capabilityToken}`, httpMethod: "POST", contentType: "application/json", body: { @@ -104,28 +103,39 @@ export class GrokBotBackend implements AgentBackend { async generate(request: AgentRequest): Promise { const correlationId = randomUUID(); + const registration = this.opts.pending.register( + correlationId, + this.opts.timeoutMs, + request.deliverReply, + ); const prompt = buildGrokBotPrompt( request, correlationId, this.opts.replyUrl, - this.opts.replyToken, - ); - const replyPromise = this.opts.pending.register( - correlationId, - this.opts.timeoutMs, - request.deliverReply, + registration.capabilityToken, ); 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); + const failed = this.opts.pending.fail( + correlationId, + err instanceof Error ? err : new Error(String(err)), + ); + if (failed) { + await registration.reply.catch(() => undefined); + throw mapGenerateError(err); + } + try { + const text = await registration.reply; + return { text, delivered: Boolean(request.deliverReply) }; + } catch (callbackError) { + throw mapGenerateError(callbackError); + } } try { - const text = await replyPromise; + const text = await registration.reply; return { text, delivered: Boolean(request.deliverReply) }; } catch (err) { throw mapGenerateError(err); diff --git a/src/agent/memory.test.ts b/src/agent/memory.test.ts index c6389ea..108fde0 100644 --- a/src/agent/memory.test.ts +++ b/src/agent/memory.test.ts @@ -9,4 +9,18 @@ describe("ConversationMemory", () => { mem.append("c", { role: "user", content: "3" }); expect(mem.get("c").map((m) => m.content)).toEqual(["2", "3"]); }); + + it("evicts the least recently used conversation above the key cap", () => { + const mem = new ConversationMemory(2, 2); + mem.append("old", { role: "user", content: "old" }); + mem.append("kept", { role: "user", content: "kept" }); + expect(mem.get("old")).toHaveLength(1); + + mem.append("new", { role: "user", content: "new" }); + + expect(mem.size).toBe(2); + expect(mem.get("kept")).toEqual([]); + expect(mem.get("old")[0]?.content).toBe("old"); + expect(mem.get("new")[0]?.content).toBe("new"); + }); }); diff --git a/src/agent/memory.ts b/src/agent/memory.ts index 6e8d840..2d22579 100644 --- a/src/agent/memory.ts +++ b/src/agent/memory.ts @@ -21,12 +21,23 @@ export interface ChatMessage { export class ConversationMemory { private readonly store = new Map(); - constructor(private readonly maxMessages: number) { - if (maxMessages < 1) throw new Error("maxMessages must be >= 1"); + constructor( + private readonly maxMessages: number, + private readonly maxKeys = 1_000, + ) { + if (!Number.isInteger(maxMessages) || maxMessages < 1) { + throw new Error("maxMessages must be a positive integer"); + } + if (!Number.isInteger(maxKeys) || maxKeys < 1) { + throw new Error("maxKeys must be a positive integer"); + } } get(key: string): ChatMessage[] { - return [...(this.store.get(key) ?? [])]; + const list = this.store.get(key); + if (!list) return []; + this.touch(key, list); + return [...list]; } append(key: string, message: ChatMessage): void { @@ -35,11 +46,25 @@ export class ConversationMemory { while (list.length > this.maxMessages) { list.shift(); } - this.store.set(key, list); + this.touch(key, list); + while (this.store.size > this.maxKeys) { + const oldestKey = this.store.keys().next().value as string | undefined; + if (oldestKey === undefined) break; + this.store.delete(oldestKey); + } } clear(key?: string): void { if (key === undefined) this.store.clear(); else this.store.delete(key); } + + get size(): number { + return this.store.size; + } + + private touch(key: string, messages: ChatMessage[]): void { + this.store.delete(key); + this.store.set(key, messages); + } } diff --git a/src/agent/openaiCompatible.test.ts b/src/agent/openaiCompatible.test.ts index d55b072..7c3efc2 100644 --- a/src/agent/openaiCompatible.test.ts +++ b/src/agent/openaiCompatible.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vitest"; import { OpenAICompatibleBackend } from "./openaiCompatible.js"; -import { createWebSearchProviders, webSearchToolDefinitions } from "./tools/webSearch.js"; +import { + createWebSearchProviders, + webSearchToolDefinitions, + type WebSearchProvider, +} from "./tools/webSearch.js"; describe("OpenAICompatibleBackend", () => { it("calls chat completions and stores assistant reply", async () => { @@ -81,6 +85,12 @@ describe("OpenAICompatibleBackend", () => { maxTokens: 64, memoryMaxMessages: 10, braveApiKey: "brave", + webSearchProviders: [ + { + name: "test", + search: async () => [], + }, + ], fetchImpl, maxToolRounds: 3, }); @@ -94,6 +104,80 @@ describe("OpenAICompatibleBackend", () => { expect(calls).toBe(4); }); + it("bounds web_search calls per round and per request with tool-result errors", async () => { + let providerCalls = 0; + const provider: WebSearchProvider = { + name: "test", + search: async (query) => { + providerCalls += 1; + return [{ title: query, url: "https://example.com", snippet: "result" }]; + }, + }; + const requests: Array<{ messages: Array<{ role: string; content: string }> }> = []; + let completionCall = 0; + const fetchImpl: typeof fetch = async (_url, init) => { + completionCall += 1; + requests.push(JSON.parse(String(init?.body))); + if (completionCall <= 2) { + const count = completionCall === 1 ? 3 : 2; + return new Response( + JSON.stringify({ + choices: [ + { + message: { + role: "assistant", + content: "", + tool_calls: Array.from({ length: count }, (_, index) => ({ + id: `call_${completionCall}_${index}`, + type: "function", + function: { + name: "web_search", + arguments: JSON.stringify({ query: `query ${completionCall}-${index}` }), + }, + })), + }, + }, + ], + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + } + return new Response( + JSON.stringify({ choices: [{ message: { role: "assistant", content: "bounded" } }] }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }; + + const backend = new OpenAICompatibleBackend({ + apiBaseUrl: "https://api.example.com/v1", + apiKey: "k", + model: "m", + systemPrompt: "sys", + temperature: 0.2, + maxTokens: 64, + memoryMaxMessages: 10, + webSearchProviders: [provider], + fetchImpl, + maxWebSearchCallsPerRound: 2, + maxWebSearchCallsPerRequest: 3, + }); + + await expect( + backend.generate({ conversationKey: "chan", authorDisplayName: "Nate", content: "search" }), + ).resolves.toEqual({ text: "bounded" }); + expect(providerCalls).toBe(3); + + const toolResults = requests[2]!.messages + .filter((message) => message.role === "tool") + .map((message) => JSON.parse(message.content) as { error?: string }); + expect(toolResults).toContainEqual({ + error: "web_search call budget exceeded for this round", + }); + expect(toolResults).toContainEqual({ + error: "web_search call budget exceeded for this request", + }); + }); + it("includes channel context in the user message", async () => { const calls: Array<{ messages: Array<{ role: string; content: string }> }> = []; const fetchImpl: typeof fetch = async (_url, init) => { diff --git a/src/agent/openaiCompatible.ts b/src/agent/openaiCompatible.ts index 0cf56a2..dd0f622 100644 --- a/src/agent/openaiCompatible.ts +++ b/src/agent/openaiCompatible.ts @@ -16,10 +16,14 @@ export interface OpenAICompatibleOptions { temperature: number; maxTokens: number; memoryMaxMessages: number; + memoryMaxKeys?: number; braveApiKey?: string | null; tavilyApiKey?: string | null; fetchImpl?: typeof fetch; maxToolRounds?: number; + maxWebSearchCallsPerRound?: number; + maxWebSearchCallsPerRequest?: number; + webSearchProviders?: WebSearchProvider[]; } interface ChatCompletionChoice { @@ -42,15 +46,27 @@ export class OpenAICompatibleBackend implements AgentBackend { private readonly providers: WebSearchProvider[]; private readonly fetchImpl: typeof fetch; private readonly maxToolRounds: number; + private readonly maxWebSearchCallsPerRound: number; + private readonly maxWebSearchCallsPerRequest: number; constructor(private readonly opts: OpenAICompatibleOptions) { - this.memory = new ConversationMemory(opts.memoryMaxMessages); - this.providers = createWebSearchProviders({ - braveApiKey: opts.braveApiKey, - tavilyApiKey: opts.tavilyApiKey, - }); + this.memory = new ConversationMemory(opts.memoryMaxMessages, opts.memoryMaxKeys); + this.providers = + opts.webSearchProviders ?? + createWebSearchProviders({ + braveApiKey: opts.braveApiKey, + tavilyApiKey: opts.tavilyApiKey, + }); this.fetchImpl = opts.fetchImpl ?? fetch; this.maxToolRounds = opts.maxToolRounds ?? 3; + this.maxWebSearchCallsPerRound = opts.maxWebSearchCallsPerRound ?? 2; + this.maxWebSearchCallsPerRequest = opts.maxWebSearchCallsPerRequest ?? 4; + if (!Number.isInteger(this.maxWebSearchCallsPerRound) || this.maxWebSearchCallsPerRound < 1) { + throw new Error("maxWebSearchCallsPerRound must be a positive integer"); + } + if (!Number.isInteger(this.maxWebSearchCallsPerRequest) || this.maxWebSearchCallsPerRequest < 1) { + throw new Error("maxWebSearchCallsPerRequest must be a positive integer"); + } } async generate(request: AgentRequest): Promise { @@ -70,6 +86,7 @@ export class OpenAICompatibleBackend implements AgentBackend { const tools = webSearchToolDefinitions(this.providers); let rounds = 0; + let webSearchCallsThisRequest = 0; while (rounds < this.maxToolRounds) { rounds += 1; @@ -82,6 +99,7 @@ export class OpenAICompatibleBackend implements AgentBackend { const toolCalls = message.tool_calls ?? []; if (toolCalls.length > 0) { + let webSearchCallsThisRound = 0; messages.push({ role: "assistant", content: message.content ?? "", @@ -91,7 +109,19 @@ export class OpenAICompatibleBackend implements AgentBackend { for (const call of toolCalls) { let toolResult: string; if (call.function.name === "web_search") { - toolResult = await runWebSearchTool(this.providers, call.function.arguments); + if (webSearchCallsThisRound >= this.maxWebSearchCallsPerRound) { + toolResult = JSON.stringify({ + error: "web_search call budget exceeded for this round", + }); + } else if (webSearchCallsThisRequest >= this.maxWebSearchCallsPerRequest) { + toolResult = JSON.stringify({ + error: "web_search call budget exceeded for this request", + }); + } else { + webSearchCallsThisRound += 1; + webSearchCallsThisRequest += 1; + toolResult = await runWebSearchTool(this.providers, call.function.arguments); + } } else { toolResult = JSON.stringify({ error: `unknown tool: ${call.function.name}` }); } diff --git a/src/config.test.ts b/src/config.test.ts index 8b93378..f9193d6 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -42,6 +42,12 @@ describe("loadConfig", () => { expect(cfg.systemPrompt).toMatch(/model `m`/); expect(cfg.temperature).toBe(0.7); expect(cfg.maxTokens).toBe(1024); + expect(cfg.memoryMaxKeys).toBe(1_000); + expect(cfg.rateLimitMaxKeys).toBe(10_000); + expect(cfg.discordReplyMaxChunks).toBe(8); + expect(cfg.callbackMaxTextChars).toBe(15_000); + expect(cfg.webSearchMaxCallsPerRound).toBe(2); + expect(cfg.webSearchMaxCallsPerRequest).toBe(4); expect(cfg.bridgeHttpHost).toBe("0.0.0.0"); expect(cfg.bridgeHttpPort).toBe(8788); expect(cfg.grokBotTimeoutMs).toBe(120_000); @@ -168,4 +174,27 @@ describe("loadConfig", () => { expect(cfg.allowDms).toBe(true); expect(cfg.dmOnly).toBe(true); }); + + it("parses hardening bounds and rejects invalid values", () => { + const soul = writeSoul(); + const cfg = loadConfig({ + ...grokBotEnv(soul), + MEMORY_MAX_KEYS: "25", + RATE_LIMIT_MAX_KEYS: "50", + DISCORD_REPLY_MAX_CHUNKS: "6", + CALLBACK_MAX_TEXT_CHARS: "12000", + WEB_SEARCH_MAX_CALLS_PER_ROUND: "1", + WEB_SEARCH_MAX_CALLS_PER_REQUEST: "3", + }); + expect(cfg.memoryMaxKeys).toBe(25); + expect(cfg.rateLimitMaxKeys).toBe(50); + expect(cfg.discordReplyMaxChunks).toBe(6); + expect(cfg.callbackMaxTextChars).toBe(12_000); + expect(cfg.webSearchMaxCallsPerRound).toBe(1); + expect(cfg.webSearchMaxCallsPerRequest).toBe(3); + + expect(() => loadConfig(grokBotEnv(soul, { DISCORD_REPLY_MAX_CHUNKS: "0" }))).toThrow( + /DISCORD_REPLY_MAX_CHUNKS/, + ); + }); }); diff --git a/src/config.ts b/src/config.ts index 64ac486..11a95a4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -23,8 +23,14 @@ export interface Config { temperature: number; maxTokens: number; memoryMaxMessages: number; + memoryMaxKeys: number; rateLimitPerUser: number; rateLimitWindowMs: number; + rateLimitMaxKeys: number; + discordReplyMaxChunks: number; + callbackMaxTextChars: number; + webSearchMaxCallsPerRound: number; + webSearchMaxCallsPerRequest: number; braveApiKey: string | null; tavilyApiKey: string | null; grokBotGatewayUrl: string | null; @@ -60,6 +66,18 @@ function parseNumber(value: string | undefined, defaultValue: number): number { return n; } +function parsePositiveInteger( + value: string | undefined, + defaultValue: number, + name: string, +): number { + const parsed = parseNumber(value, defaultValue); + if (!Number.isInteger(parsed) || parsed < 1) { + throw new Error(`${name} must be a positive integer`); + } + return parsed; +} + function loadSystemPrompt(filePath: string): string { const absolute = resolve(process.cwd(), filePath); try { @@ -164,8 +182,34 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config { temperature: parseNumber(env.TEMPERATURE, 0.7), maxTokens: parseNumber(env.MAX_TOKENS, 1024), memoryMaxMessages: parseNumber(env.MEMORY_MAX_MESSAGES, 20), + memoryMaxKeys: parsePositiveInteger(env.MEMORY_MAX_KEYS, 1_000, "MEMORY_MAX_KEYS"), rateLimitPerUser: parseNumber(env.RATE_LIMIT_PER_USER, 5), rateLimitWindowMs: parseNumber(env.RATE_LIMIT_WINDOW_MS, 60_000), + rateLimitMaxKeys: parsePositiveInteger( + env.RATE_LIMIT_MAX_KEYS, + 10_000, + "RATE_LIMIT_MAX_KEYS", + ), + discordReplyMaxChunks: parsePositiveInteger( + env.DISCORD_REPLY_MAX_CHUNKS, + 8, + "DISCORD_REPLY_MAX_CHUNKS", + ), + callbackMaxTextChars: parsePositiveInteger( + env.CALLBACK_MAX_TEXT_CHARS, + 15_000, + "CALLBACK_MAX_TEXT_CHARS", + ), + webSearchMaxCallsPerRound: parsePositiveInteger( + env.WEB_SEARCH_MAX_CALLS_PER_ROUND, + 2, + "WEB_SEARCH_MAX_CALLS_PER_ROUND", + ), + webSearchMaxCallsPerRequest: parsePositiveInteger( + env.WEB_SEARCH_MAX_CALLS_PER_REQUEST, + 4, + "WEB_SEARCH_MAX_CALLS_PER_REQUEST", + ), braveApiKey: env.BRAVE_API_KEY?.trim() || null, tavilyApiKey: env.TAVILY_API_KEY?.trim() || null, grokBotGatewayUrl, diff --git a/src/discord/bot.ts b/src/discord/bot.ts index 0a79aef..e197b86 100644 --- a/src/discord/bot.ts +++ b/src/discord/bot.ts @@ -85,7 +85,11 @@ export function attachMessageHandler( config: Config, backend: AgentBackend, ): void { - const limiter = new RateLimiter(config.rateLimitPerUser, config.rateLimitWindowMs); + const limiter = new RateLimiter( + config.rateLimitPerUser, + config.rateLimitWindowMs, + config.rateLimitMaxKeys, + ); client.on("messageCreate", async (message: OmitPartialGroupDMChannel) => { try { @@ -169,11 +173,11 @@ async function handleMessage( threadName: ctx.threadName, channelTopic: ctx.channelTopic, guildName: ctx.guildName, - deliverReply: (text) => sendSplitReply(message, text), + deliverReply: (text) => sendSplitReply(message, text, config.discordReplyMaxChunks), }), ); if (!result.delivered) { - await sendSplitReply(message, result.text); + await sendSplitReply(message, result.text, config.discordReplyMaxChunks); } } catch (err) { const detail = err instanceof Error ? err.message : String(err); diff --git a/src/discord/rateLimit.test.ts b/src/discord/rateLimit.test.ts index 84ed816..f086649 100644 --- a/src/discord/rateLimit.test.ts +++ b/src/discord/rateLimit.test.ts @@ -15,4 +15,15 @@ describe("RateLimiter", () => { expect(limiter.tryConsume("u", 50)).toBe(false); expect(limiter.tryConsume("u", 101)).toBe(true); }); + + it("prunes expired buckets and fails closed at the active-key cap", () => { + const limiter = new RateLimiter(2, 100, 2); + expect(limiter.tryConsume("a", 0)).toBe(true); + expect(limiter.tryConsume("b", 1)).toBe(true); + expect(limiter.tryConsume("c", 2)).toBe(false); + expect(limiter.size).toBe(2); + + expect(limiter.tryConsume("c", 102)).toBe(true); + expect(limiter.size).toBe(1); + }); }); diff --git a/src/discord/rateLimit.ts b/src/discord/rateLimit.ts index 4ba5e4f..644cc55 100644 --- a/src/discord/rateLimit.ts +++ b/src/discord/rateLimit.ts @@ -1,26 +1,63 @@ export class RateLimiter { private readonly hits = new Map(); + private nextSweepAt = 0; constructor( private readonly maxPerWindow: number, private readonly windowMs: number, - ) {} + private readonly maxKeys = 10_000, + ) { + if (!Number.isInteger(maxPerWindow) || maxPerWindow < 1) { + throw new Error("maxPerWindow must be a positive integer"); + } + if (!Number.isFinite(windowMs) || windowMs <= 0) { + throw new Error("windowMs must be positive"); + } + if (!Number.isInteger(maxKeys) || maxKeys < 1) { + throw new Error("maxKeys must be a positive integer"); + } + } /** Returns true if the request is allowed (and records it). */ tryConsume(key: string, now = Date.now()): boolean { + if (now >= this.nextSweepAt) { + this.pruneExpired(now); + this.nextSweepAt = now + Math.min(this.windowMs, 60_000); + } + const cutoff = now - this.windowMs; const prior = (this.hits.get(key) ?? []).filter((t) => t > cutoff); if (prior.length >= this.maxPerWindow) { this.hits.set(key, prior); return false; } + if (!this.hits.has(key) && this.hits.size >= this.maxKeys) { + this.pruneExpired(now); + if (this.hits.size >= this.maxKeys) return false; + } prior.push(now); this.hits.set(key, prior); return true; } reset(key?: string): void { - if (key === undefined) this.hits.clear(); + if (key === undefined) { + this.hits.clear(); + this.nextSweepAt = 0; + } else this.hits.delete(key); } + + get size(): number { + return this.hits.size; + } + + private pruneExpired(now: number): void { + const cutoff = now - this.windowMs; + for (const [key, timestamps] of this.hits) { + const active = timestamps.filter((timestamp) => timestamp > cutoff); + if (active.length === 0) this.hits.delete(key); + else if (active.length !== timestamps.length) this.hits.set(key, active); + } + } } diff --git a/src/discord/reply.ts b/src/discord/reply.ts index cabe86e..722f906 100644 --- a/src/discord/reply.ts +++ b/src/discord/reply.ts @@ -1,15 +1,22 @@ import type { Message, TextChannel } from "discord.js"; import { splitMessage } from "../util/splitMessage.js"; -export async function sendSplitReply(message: Message, text: string): Promise { - const chunks = splitMessage(text); +export async function sendSplitReply( + message: Message, + text: string, + maxChunks?: number, +): Promise { + const chunks = splitMessage(text, undefined, maxChunks); if (chunks.length === 0) return; const channel = message.channel as TextChannel; let first = true; for (const chunk of chunks) { if (first) { - await message.reply({ content: chunk, allowedMentions: { repliedUser: false } }); + await message.reply({ + content: chunk, + allowedMentions: { parse: [], repliedUser: false }, + }); first = false; } else { await channel.send({ content: chunk, allowedMentions: { parse: [] } }); diff --git a/src/http/pendingReplies.test.ts b/src/http/pendingReplies.test.ts index 2dc2620..40432a2 100644 --- a/src/http/pendingReplies.test.ts +++ b/src/http/pendingReplies.test.ts @@ -1,20 +1,22 @@ import { describe, expect, it } from "vitest"; -import { PendingReplyStore } from "./pendingReplies.js"; +import { PendingReplyStore, ReplyTimeoutError } 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 () => { + const registration = 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"); + await expect( + pending.complete("id-1", registration.capabilityToken, "retry me"), + ).resolves.toBe("delivery_failed"); expect(pending.has("id-1")).toBe(true); let settled = false; - void waiter.then( + void registration.reply.then( () => { settled = true; }, @@ -25,9 +27,66 @@ describe("PendingReplyStore.complete", () => { 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"); + await expect( + pending.complete("id-1", registration.capabilityToken, "retry me"), + ).resolves.toBe("ok"); + await expect(registration.reply).resolves.toBe("retry me"); expect(attempts).toBe(2); expect(pending.has("id-1")).toBe(false); }); + + it("isolates capabilities by correlationId and invalidates them after completion", async () => { + const pending = new PendingReplyStore("server-side-key"); + const first = pending.register("id-1", 5_000); + const second = pending.register("id-2", 5_000); + + expect(first.capabilityToken).not.toBe(second.capabilityToken); + await expect(pending.complete("id-1", second.capabilityToken, "wrong token")).resolves.toBe( + "unauthorized", + ); + await expect(pending.complete("id-1", first.capabilityToken, "first")).resolves.toBe("ok"); + await expect(first.reply).resolves.toBe("first"); + await expect(pending.complete("id-1", first.capabilityToken, "replay")).resolves.toBe( + "missing", + ); + + await expect(pending.complete("id-2", second.capabilityToken, "second")).resolves.toBe("ok"); + await expect(second.reply).resolves.toBe("second"); + }); + + it("bounds delivery retries for one capability", async () => { + const pending = new PendingReplyStore(); + let attempts = 0; + const registration = pending.register("bounded-retries", 5_000, async () => { + attempts += 1; + throw new Error("delivery failed"); + }); + + await expect( + pending.complete("bounded-retries", registration.capabilityToken, "reply"), + ).resolves.toBe("delivery_failed"); + await expect( + pending.complete("bounded-retries", registration.capabilityToken, "reply"), + ).resolves.toBe("delivery_failed"); + await expect( + pending.complete("bounded-retries", registration.capabilityToken, "reply"), + ).resolves.toBe("delivery_failed"); + expect(attempts).toBe(2); + + pending.fail("bounded-retries", new Error("test cleanup")); + await expect(registration.reply).rejects.toThrow("test cleanup"); + }); + + it("expires a capability while Discord delivery is still pending", async () => { + const pending = new PendingReplyStore(); + const registration = pending.register("delivery-timeout", 20, async () => { + await new Promise((resolve) => setTimeout(resolve, 80)); + }); + + await expect( + pending.complete("delivery-timeout", registration.capabilityToken, "slow"), + ).resolves.toBe("missing"); + await expect(registration.reply).rejects.toBeInstanceOf(ReplyTimeoutError); + expect(pending.has("delivery-timeout")).toBe(false); + }); }); diff --git a/src/http/pendingReplies.ts b/src/http/pendingReplies.ts index f25bdc5..2ebcf4a 100644 --- a/src/http/pendingReplies.ts +++ b/src/http/pendingReplies.ts @@ -1,3 +1,5 @@ +import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; + export class ReplyTimeoutError extends Error { readonly correlationId: string; @@ -15,15 +17,23 @@ export class AgentCallbackError extends Error { } } -export type CompleteResult = "missing" | "ok" | "delivery_failed"; +export type CompleteResult = "missing" | "unauthorized" | "ok" | "delivery_failed"; +const MAX_DELIVERY_ATTEMPTS = 2; + +export interface PendingReplyRegistration { + capabilityToken: string; + reply: Promise; +} interface PendingEntry { + capabilityDigest: Buffer; resolve: (text: string) => void; reject: (error: Error) => void; timer: ReturnType; deadlineMs: number; deliver?: (text: string) => Promise; delivering: boolean; + deliveryAttempts: number; } /** @@ -32,41 +42,64 @@ interface PendingEntry { */ export class PendingReplyStore { private readonly pending = new Map(); + private readonly missingCapabilityDigest = randomBytes(32); + + constructor(private readonly capabilityKey: string = randomBytes(32).toString("base64url")) {} register( correlationId: string, timeoutMs: number, deliver?: (text: string) => Promise, - ): Promise { + ): PendingReplyRegistration { if (this.pending.has(correlationId)) { - return Promise.reject(new Error("Duplicate correlationId")); + throw new Error("Duplicate correlationId"); } - return new Promise((resolve, reject) => { + const capabilityToken = randomBytes(32).toString("base64url"); + const reply = new Promise((resolve, reject) => { const entry = { + capabilityDigest: this.digestCapability(capabilityToken), resolve, reject, deadlineMs: Date.now() + timeoutMs, deliver, delivering: false, + deliveryAttempts: 0, } as PendingEntry; this.pending.set(correlationId, entry); this.armTimeout(correlationId, entry); }); + void reply.catch(() => undefined); + return { capabilityToken, reply }; } - async complete(correlationId: string, text: string): Promise { + async complete( + correlationId: string, + capabilityToken: string, + text: string, + ): Promise { const entry = this.pending.get(correlationId); + const authResult = this.authorize(entry, capabilityToken); + if (authResult !== "ok") return authResult; if (!entry) return "missing"; if (entry.delivering) return "delivery_failed"; + if (entry.deliveryAttempts >= MAX_DELIVERY_ATTEMPTS) return "delivery_failed"; entry.delivering = true; - clearTimeout(entry.timer); + entry.deliveryAttempts += 1; try { if (entry.deliver) { - await entry.deliver(text); + await this.deliverBeforeDeadline(entry, text); + } + if (Date.now() >= entry.deadlineMs) { + this.expire(correlationId, entry); + return "missing"; } + if (this.pending.get(correlationId) !== entry) { + return "missing"; + } + clearTimeout(entry.timer); this.pending.delete(correlationId); entry.resolve(text); return "ok"; @@ -75,14 +108,30 @@ export class PendingReplyStore { if (!this.pending.has(correlationId)) { return "missing"; } - this.armTimeout(correlationId, entry); return "delivery_failed"; } } + verifyCapability( + correlationId: string, + capabilityToken: string, + ): "missing" | "unauthorized" | "ok" { + return this.authorize(this.pending.get(correlationId), capabilityToken); + } + + failCallback(correlationId: string, capabilityToken: string, error: Error): CompleteResult { + const entry = this.pending.get(correlationId); + const authResult = this.authorize(entry, capabilityToken); + if (authResult !== "ok") return authResult; + if (entry?.delivering) return "delivery_failed"; + this.fail(correlationId, error); + return "ok"; + } + fail(correlationId: string, error: Error): boolean { const entry = this.pending.get(correlationId); if (!entry) return false; + if (entry.delivering) return false; clearTimeout(entry.timer); this.pending.delete(correlationId); entry.reject(error); @@ -100,13 +149,55 @@ export class PendingReplyStore { 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)); + this.expire(correlationId, entry); return; } entry.timer = setTimeout(() => { - this.pending.delete(correlationId); - entry.reject(new ReplyTimeoutError(correlationId)); + this.expire(correlationId, entry); }, remaining); } + + private async deliverBeforeDeadline(entry: PendingEntry, text: string): Promise { + const remaining = entry.deadlineMs - Date.now(); + if (remaining <= 0) throw new Error("delivery_deadline_exceeded"); + + let deadlineTimer: ReturnType | undefined; + try { + await Promise.race([ + Promise.resolve().then(() => entry.deliver!(text)), + new Promise((_, reject) => { + deadlineTimer = setTimeout( + () => reject(new Error("delivery_deadline_exceeded")), + remaining, + ); + }), + ]); + } finally { + if (deadlineTimer) clearTimeout(deadlineTimer); + } + } + + private expire(correlationId: string, entry: PendingEntry): void { + if (this.pending.get(correlationId) !== entry) return; + clearTimeout(entry.timer); + this.pending.delete(correlationId); + entry.reject(new ReplyTimeoutError(correlationId)); + } + + private digestCapability(capabilityToken: string): Buffer { + return createHmac("sha256", this.capabilityKey).update(capabilityToken).digest(); + } + + private authorize( + entry: PendingEntry | undefined, + capabilityToken: string, + ): "missing" | "unauthorized" | "ok" { + const providedDigest = this.digestCapability(capabilityToken); + const matches = timingSafeEqual( + providedDigest, + entry?.capabilityDigest ?? this.missingCapabilityDigest, + ); + if (!entry) return "missing"; + return matches ? "ok" : "unauthorized"; + } } diff --git a/src/http/replyServer.test.ts b/src/http/replyServer.test.ts index 4d86742..2ff4db2 100644 --- a/src/http/replyServer.test.ts +++ b/src/http/replyServer.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, it } from "vitest"; +import { createConnection } from "node:net"; import { PendingReplyStore, ReplyTimeoutError } from "./pendingReplies.js"; import { startReplyServer, type StartedReplyServer } from "./replyServer.js"; @@ -6,13 +7,13 @@ const TOKEN = "test-reply-token"; async function listen( pending: PendingReplyStore, - replyToken: string | null = TOKEN, + maxTextChars?: number, ): Promise { return startReplyServer({ host: "127.0.0.1", port: 0, - replyToken, pending, + maxTextChars, }); } @@ -64,6 +65,7 @@ describe("POST /internal/reply", () => { const pending = new PendingReplyStore(); const server = await listen(pending); servers.push(server); + const registration = pending.register("c", 5_000); const res = await postReply(server, { token: "wrong-token", @@ -71,18 +73,8 @@ describe("POST /internal/reply", () => { }); 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); + pending.fail("c", new Error("test cleanup")); + await expect(registration.reply).rejects.toThrow("test cleanup"); }); it("returns 400 when required fields are missing", async () => { @@ -117,10 +109,11 @@ describe("POST /internal/reply", () => { const server = await listen(pending); servers.push(server); - const waiter = pending.register("expired", 20); - await expect(waiter).rejects.toBeInstanceOf(ReplyTimeoutError); + const registration = pending.register("expired", 20); + await expect(registration.reply).rejects.toBeInstanceOf(ReplyTimeoutError); const res = await postReply(server, { + token: registration.capabilityToken, body: { correlationId: "expired", text: "too late" }, }); expect(res.status).toBe(404); @@ -131,14 +124,15 @@ describe("POST /internal/reply", () => { const server = await listen(pending); servers.push(server); - const waiter = pending.register("corr-1", 5_000); + const registration = pending.register("corr-1", 5_000); const res = await postReply(server, { + token: registration.capabilityToken, 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."); + await expect(registration.reply).resolves.toBe("Pots are in houses and trader inventories."); expect(pending.has("corr-1")).toBe(false); }); @@ -148,12 +142,13 @@ describe("POST /internal/reply", () => { servers.push(server); let attempts = 0; - const waiter = pending.register("corr-retry", 5_000, async () => { + const registration = pending.register("corr-retry", 5_000, async () => { attempts += 1; if (attempts === 1) throw new Error("discord 502"); }); const first = await postReply(server, { + token: registration.capabilityToken, body: { correlationId: "corr-retry", text: "hello from Discord" }, }); expect(first.status).toBe(503); @@ -161,7 +156,7 @@ describe("POST /internal/reply", () => { expect(pending.has("corr-retry")).toBe(true); let settled = false; - void waiter.then( + void registration.reply.then( () => { settled = true; }, @@ -173,12 +168,71 @@ describe("POST /internal/reply", () => { expect(settled).toBe(false); const second = await postReply(server, { + token: registration.capabilityToken, 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"); + await expect(registration.reply).resolves.toBe("hello from Discord"); expect(attempts).toBe(2); expect(pending.has("corr-retry")).toBe(false); }); + + it("rejects oversized callback text without consuming the capability", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending, 12); + servers.push(server); + const registration = pending.register("bounded", 5_000); + + const oversized = await postReply(server, { + token: registration.capabilityToken, + body: { correlationId: "bounded", text: "x".repeat(13) }, + }); + expect(oversized.status).toBe(413); + expect(oversized.json.error).toBe("reply_too_large"); + + const valid = await postReply(server, { + token: registration.capabilityToken, + body: { correlationId: "bounded", text: "fits" }, + }); + expect(valid.status).toBe(200); + await expect(registration.reply).resolves.toBe("fits"); + }); + + it("returns 413 as soon as the request body exceeds the byte limit", async () => { + const pending = new PendingReplyStore(); + const server = await listen(pending); + servers.push(server); + + const response = await new Promise((resolve, reject) => { + const socket = createConnection({ host: "127.0.0.1", port: server.port }); + let received = ""; + const timer = setTimeout(() => { + socket.destroy(); + reject(new Error("timed out waiting for early 413")); + }, 2_000); + socket.on("connect", () => { + const body = "x".repeat(1_000_001); + socket.write( + `POST /internal/reply HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer test\r\nContent-Length: ${body.length + 1}\r\nConnection: close\r\n\r\n`, + ); + socket.write(body); + }); + socket.on("data", (chunk) => { + received += chunk.toString("utf8"); + if (received.includes(" 413 ")) { + clearTimeout(timer); + socket.destroy(); + resolve(received); + } + }); + socket.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + }); + + expect(response).toContain("HTTP/1.1 413"); + expect(response).toContain("payload_too_large"); + }); }); diff --git a/src/http/replyServer.ts b/src/http/replyServer.ts index e0eeefa..5a5691f 100644 --- a/src/http/replyServer.ts +++ b/src/http/replyServer.ts @@ -1,13 +1,11 @@ -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; + maxTextChars?: number; } export interface StartedReplyServer { @@ -17,6 +15,7 @@ export interface StartedReplyServer { } const MAX_BODY_BYTES = 1_000_000; +export const DEFAULT_MAX_CALLBACK_TEXT_CHARS = 15_000; interface ReplyBody { correlationId?: unknown; @@ -45,34 +44,31 @@ function extractBearer(header: string | undefined): string | null { 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) => { + let settled = false; + + const onData = (chunk: Buffer) => { size += chunk.length; if (size > maxBytes) { - req.destroy(); + settled = true; + chunks.length = 0; + req.off("data", onData); + req.resume(); reject(new Error("payload_too_large")); return; } chunks.push(chunk); + }; + req.on("data", onData); + req.on("end", () => { + if (!settled) resolve(Buffer.concat(chunks).toString("utf8")); + }); + req.on("error", (error) => { + if (!settled) reject(error); }); - req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); - req.on("error", reject); }); } @@ -90,7 +86,8 @@ async function handleReply( return; } - if (!authorize(req, opts.replyToken)) { + const capabilityToken = extractBearer(headerValue(req, "authorization")); + if (!capabilityToken) { sendJson(res, 401, { error: "unauthorized" }); return; } @@ -98,8 +95,11 @@ async function handleReply( let raw: string; try { raw = await readBody(req, MAX_BODY_BYTES); - } catch { - sendJson(res, 400, { error: "invalid_body" }); + } catch (err) { + const tooLarge = err instanceof Error && err.message === "payload_too_large"; + sendJson(res, tooLarge ? 413 : 400, { + error: tooLarge ? "payload_too_large" : "invalid_body", + }); return; } @@ -125,22 +125,53 @@ async function handleReply( return; } - if (!opts.pending.has(correlationId)) { + const authResult = opts.pending.verifyCapability(correlationId, capabilityToken); + if (authResult === "missing") { sendJson(res, 404, { error: "unknown_correlation_id" }); return; } + if (authResult === "unauthorized") { + sendJson(res, 401, { error: "unauthorized" }); + return; + } + + const maxTextChars = opts.maxTextChars ?? DEFAULT_MAX_CALLBACK_TEXT_CHARS; + if (text.length > maxTextChars) { + sendJson(res, 413, { error: "reply_too_large" }); + return; + } if (errorMessage && !text.trim()) { - opts.pending.fail(correlationId, new AgentCallbackError(errorMessage)); + const result = opts.pending.failCallback( + correlationId, + capabilityToken, + new AgentCallbackError(errorMessage), + ); + if (result === "missing") { + sendJson(res, 404, { error: "unknown_correlation_id" }); + return; + } + if (result === "unauthorized") { + sendJson(res, 401, { error: "unauthorized" }); + return; + } + if (result === "delivery_failed") { + sendJson(res, 503, { error: "delivery_failed" }); + return; + } sendJson(res, 200, { ok: true }); return; } - const result = await opts.pending.complete(correlationId, text); + const result = await opts.pending.complete(correlationId, capabilityToken, text); if (result === "missing") { sendJson(res, 404, { error: "unknown_correlation_id" }); return; } + if (result === "unauthorized") { + sendJson(res, 401, { error: "unauthorized" }); + return; + } if (result === "delivery_failed") { sendJson(res, 503, { error: "delivery_failed" }); return; @@ -150,6 +181,11 @@ async function handleReply( } export async function startReplyServer(opts: ReplyServerOptions): Promise { + const maxTextChars = opts.maxTextChars ?? DEFAULT_MAX_CALLBACK_TEXT_CHARS; + if (!Number.isInteger(maxTextChars) || maxTextChars < 1) { + throw new Error("maxTextChars must be a positive integer"); + } + const server: Server = createServer((req, res) => { const url = req.url?.split("?")[0] ?? ""; if (url !== "/internal/reply") { diff --git a/src/index.ts b/src/index.ts index 20796c1..ba73006 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,19 +16,22 @@ function createOpenAiBackend(config: ReturnType): AgentBacken temperature: config.temperature, maxTokens: config.maxTokens, memoryMaxMessages: config.memoryMaxMessages, + memoryMaxKeys: config.memoryMaxKeys, + maxWebSearchCallsPerRound: config.webSearchMaxCallsPerRound, + maxWebSearchCallsPerRequest: config.webSearchMaxCallsPerRequest, braveApiKey: config.braveApiKey, tavilyApiKey: config.tavilyApiKey, }); } async function createGrokBotBackend(config: ReturnType): Promise { - const pending = new PendingReplyStore(); + const pending = new PendingReplyStore(config.bridgeReplyToken!); const replyUrl = joinUrl(config.bridgePublicUrl!, "/internal/reply"); const server = await startReplyServer({ host: config.bridgeHttpHost, port: config.bridgeHttpPort, - replyToken: config.bridgeReplyToken, pending, + maxTextChars: config.callbackMaxTextChars, }); console.log(`[bridge] reply endpoint listening on ${server.host}:${server.port} path=/internal/reply`); return new GrokBotBackend({ @@ -37,7 +40,6 @@ async function createGrokBotBackend(config: ReturnType): Prom agentId: config.grokBotAgentId!, timeoutMs: config.grokBotTimeoutMs, replyUrl, - replyToken: config.bridgeReplyToken!, pending, }); } diff --git a/src/util/splitMessage.test.ts b/src/util/splitMessage.test.ts index 8ae8621..9ba992c 100644 --- a/src/util/splitMessage.test.ts +++ b/src/util/splitMessage.test.ts @@ -28,4 +28,16 @@ describe("splitMessage", () => { expect(chunks.join("")).toBe(text); expect(chunks.every((c) => c.length <= 20)).toBe(true); }); + + it("caps chunk fan-out and marks the truncated final chunk", () => { + const chunks = splitMessage("X".repeat(200), 40, 3); + expect(chunks).toHaveLength(3); + expect(chunks[2]).toContain("[Reply truncated.]"); + expect(chunks.every((chunk) => chunk.length <= 40)).toBe(true); + }); + + it("rejects non-positive split bounds", () => { + expect(() => splitMessage("hello", 0)).toThrow(/positive integer/); + expect(() => splitMessage("hello", 10, 0)).toThrow(/positive integer/); + }); }); diff --git a/src/util/splitMessage.ts b/src/util/splitMessage.ts index 93d0156..b52f70a 100644 --- a/src/util/splitMessage.ts +++ b/src/util/splitMessage.ts @@ -1,10 +1,21 @@ -const DISCORD_SAFE_LIMIT = 1900; +export const DISCORD_SAFE_LIMIT = 1900; +export const DEFAULT_MAX_DISCORD_CHUNKS = 8; +const TRUNCATION_SUFFIX = "\n\n[Reply truncated.]"; /** * Split text into Discord-safe chunks (~1900 chars), preferring paragraph * then newline then space boundaries. */ -export function splitMessage(text: string, limit = DISCORD_SAFE_LIMIT): string[] { +export function splitMessage( + text: string, + limit = DISCORD_SAFE_LIMIT, + maxChunks = DEFAULT_MAX_DISCORD_CHUNKS, +): string[] { + if (!Number.isInteger(limit) || limit < 1) throw new Error("limit must be a positive integer"); + if (!Number.isInteger(maxChunks) || maxChunks < 1) { + throw new Error("maxChunks must be a positive integer"); + } + const trimmed = text.trim(); if (!trimmed) return []; if (trimmed.length <= limit) return [trimmed]; @@ -13,6 +24,13 @@ export function splitMessage(text: string, limit = DISCORD_SAFE_LIMIT): string[] let remaining = trimmed; while (remaining.length > limit) { + if (chunks.length === maxChunks - 1) { + const suffix = TRUNCATION_SUFFIX.length < limit ? TRUNCATION_SUFFIX : "…"; + const available = Math.max(0, limit - suffix.length); + chunks.push(`${remaining.slice(0, available).trimEnd()}${suffix}`); + return chunks; + } + const window = remaining.slice(0, limit); let cut = window.lastIndexOf("\n\n") >= 0 @@ -30,6 +48,6 @@ export function splitMessage(text: string, limit = DISCORD_SAFE_LIMIT): string[] remaining = remaining.slice(cut).trimStart(); } - if (remaining) chunks.push(remaining); + if (remaining && chunks.length < maxChunks) chunks.push(remaining); return chunks; }