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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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 <BRIDGE_REPLY_TOKEN>`.
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).

Expand Down Expand Up @@ -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**
Expand Down Expand Up @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions docs/PHASE2-GROK-BOT-BACKEND.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <BRIDGE_REPLY_TOKEN>`.
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.

Expand All @@ -54,14 +54,14 @@ flowchart LR
| Rule | Behavior |
|------|----------|
| Listen | `BRIDGE_HTTP_HOST` / `BRIDGE_HTTP_PORT` (defaults `0.0.0.0` / `8788`) |
| Auth | `Authorization: Bearer <BRIDGE_REPLY_TOKEN>` — **fail closed** if unset or wrong → 401 |
| Auth | `Authorization: Bearer <per-request capability>` — **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:

Expand All @@ -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.

Expand Down Expand Up @@ -126,7 +126,7 @@ The bridge embeds a JSON block between `---BEGIN DISCORD_BRIDGE_REPLY---` / `---

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

Plus Discord context already on `AgentRequest`: `conversationKey`, `channelName`, `threadName`, `channelTopic`, `guildName`, `authorDisplayName`, `content`.
Expand Down
2 changes: 1 addition & 1 deletion docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
63 changes: 57 additions & 6 deletions src/agent/grokBot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ function backendOpts(overrides: Partial<ConstructorParameters<typeof GrokBotBack
agentId: "agent-from-env",
timeoutMs: 5_000,
replyUrl: "http://bridge.example:8788/internal/reply",
replyToken: "reply-token",
pending: new PendingReplyStore(),
...overrides,
};
Expand All @@ -37,6 +36,12 @@ function correlationIdFromPrompt(prompt: string): string {
return match[1];
}

function capabilityTokenFromPrompt(prompt: string): string {
const match = prompt.match(/"authorization": "Bearer ([^"]+)"/);
if (!match?.[1]) throw new Error("prompt missing capability token");
return match[1];
}

describe("buildGrokBotPrompt", () => {
it("includes correlationId, replyUrl, Discord context, and bearer instructions", () => {
const prompt = buildGrokBotPrompt(
Expand All @@ -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) => {
Expand Down Expand Up @@ -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,
Expand All @@ -104,7 +116,6 @@ describe("GrokBotBackend", () => {
const server = await startReplyServer({
host: "127.0.0.1",
port: 0,
replyToken: "reply-token",
pending,
});

Expand All @@ -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." }),
});
Expand Down Expand Up @@ -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<Response>((_resolve, reject) => {
rejectGateway = reject;
});
};
let finishDelivery: (() => void) | undefined;
const grok = new GrokBotBackend(backendOpts({ pending, fetchImpl }));
const generatePromise = grok.generate({
...request,
deliverReply: async () =>
new Promise<void>((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 }));
Expand Down
36 changes: 23 additions & 13 deletions src/agent/grokBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export interface GrokBotBackendOptions {
agentId: string;
timeoutMs: number;
replyUrl: string;
replyToken: string;
pending: PendingReplyStore;
fetchImpl?: typeof fetch;
sendPromptTimeoutMs?: number;
Expand All @@ -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: {
Expand Down Expand Up @@ -104,28 +103,39 @@ export class GrokBotBackend implements AgentBackend {

async generate(request: AgentRequest): Promise<AgentResponse> {
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);
Expand Down
14 changes: 14 additions & 0 deletions src/agent/memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});
Loading
Loading