The Open Framework for Building Agents
[1/4] feat(eve): answer Discord messages through a Gateway relay (#4934)
Ben Pankow2b07d0a67799
diff --git a/.changeset/discord-gateway-relay.md b/.changeset/discord-gateway-relay.mdnew file mode 100644index 000000000..a16afcbd4--- /dev/null+++ b/.changeset/discord-gateway-relay.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The Discord channel can now answer DMs, mentions, and thread replies. `discordChannel({ gateway: {} })` accepts messages forwarded from the Discord Gateway, and `experimental_runDiscordGatewayRelay` from the new `eve/channels/discord/gateway` entry point holds that connection, for example in a Vercel Daemon. In text channels, a mention starts a thread that holds the conversation, and a reply to any bot message continues the session that posted it; set `gateway.startThread: false` to answer in the channel, or return `conversation` or `startThread` from `gateway.onMessage` to decide per message. `defaultDiscordMessageAuth` gives a message's author the same principal `defaultDiscordAuth` gives them for commands and button presses.diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdxindex 8b7df2e62..0ef312a39 100644--- a/docs/channels/discord.mdx+++ b/docs/channels/discord.mdx@@ -1,10 +1,10 @@---title: "Discord"-description: "Reach your agent from Discord HTTP Interactions, including slash commands, components, and modals."+description: "Reach your agent from Discord messages, DMs, and mentions, and from slash commands, components, and modals."type: integration----The Discord channel wires your agent into Discord's HTTP Interactions, including slash and application commands, message components, and modal submissions. Discord enforces a three-second ACK deadline, so the channel acknowledges the command right away and runs the eve work in the background. Credentials and inbound request verification run through [Vercel Connect](../guides/auth-and-route-protection), so Discord's bot token stays out of your environment and Connect verifies Discord's signature before forwarding an interaction to eve. See [Channels](./overview) for the contract this builds on.+The Discord channel wires your agent into Discord's HTTP Interactions, including slash and application commands, message components, and modal submissions. Discord enforces a three-second ACK deadline, so the channel acknowledges the command right away and runs the eve work in the background. Credentials and inbound request verification run through [Vercel Connect](../guides/auth-and-route-protection), so Discord's bot token stays out of your environment and Connect verifies Discord's signature before forwarding an interaction to eve. To also answer DMs and mentions, add a [Discord Gateway relay](#reply-to-dms-and-mentions-experimental). See [Channels](./overview) for the contract this builds on.## Set up Discord@@ -53,6 +53,267 @@ curl -X PUT "https://discord.com/api/v10/applications/$DISCORD_APPLICATION_ID/coThen configure the public `https://…/eve/v1/discord` route as the application's Interactions Endpoint URL. Pass `credentials: { applicationId, botToken, publicKey }` to `discordChannel`, or set the corresponding `DISCORD_APPLICATION_ID`, `DISCORD_BOT_TOKEN`, and `DISCORD_PUBLIC_KEY` environment variables.+## Reply to DMs and mentions (experimental)++Discord sends ordinary messages, such as DMs, mentions, and thread replies, only over its [Gateway WebSocket](https://discord.com/developers/docs/events/gateway), not as HTTP Interactions. Gateway support is experimental, and its API may change. To receive them, run `experimental_runDiscordGatewayRelay` from `eve/channels/discord/gateway` in a process that stays connected, and enable the matching route on the channel. The relay forwards each `MESSAGE_CREATE` dispatch to the agent unchanged, and the channel replies through the same handlers it uses for commands, including HITL buttons and error messages.++```text+Discord Gateway ── WebSocket ──▶ relay (Vercel Daemon) ── POST /eve/v1/discord/gateway ──▶ agent ── REST ──▶ Discord+```++### Enable the Gateway route++Add `gateway` to the channel. It mounts `POST /eve/v1/discord/gateway`. Because each forwarded message names its author, the route by default accepts only `localDev()` and Vercel OIDC tokens from the same project and environment, which excludes preview deployments calling production:++```ts title="agent/channels/discord.ts"+import { connectDiscordCredentials } from "@vercel/connect/eve";+import { discordChannel } from "eve/channels/discord";++export default discordChannel({+ credentials: connectDiscordCredentials("discord/my-agent"),+ gateway: {},+});+```++Vercel Connect is optional here too: without `credentials`, the channel reads `DISCORD_APPLICATION_ID` and `DISCORD_BOT_TOKEN`, and the relay reads `DISCORD_BOT_TOKEN`. Pass `gateway.auth` to accept a relay that [runs outside Vercel](#run-the-relay-outside-vercel), and `gateway.route` to change the path. Whoever passes `gateway.auth` can send messages as any Discord user, so keep it as narrow as the default.++### Run the relay as a Vercel Daemon++A Vercel Daemon keeps the relay connected. Daemons are in beta. Put the relay in its own directory with the same credentials as the agent:++```ts title="daemon/main.ts"+import { connectDiscordCredentials } from "@vercel/connect/eve";+import { experimental_runDiscordGatewayRelay } from "eve/channels/discord/gateway";++await experimental_runDiscordGatewayRelay({+ credentials: connectDiscordCredentials("discord/my-agent"),+ url: process.env.EVE_URL,+});+```++```json title="daemon/package.json"+{+ "private": true,+ "type": "module",+ "dependencies": {+ "@vercel/connect": "<same version as your agent>",+ "eve": "<same version as your agent>"+ }+}+```++Run `npm install` in `daemon/` to create the `package-lock.json` the image installs from:++```dockerfile title="daemon/Dockerfile"+FROM node:24-slim+WORKDIR /app+ENV NODE_ENV=production+COPY package.json package-lock.json ./+RUN npm ci --omit=dev+COPY main.ts ./+USER node+CMD ["node", "main.ts"]+```++Register the daemon in `vercel.json` with exactly one instance:++```json title="vercel.json"+{+ "framework": "eve",+ "daemons": {+ "discord-gateway": {+ "root": "daemon",+ "entrypoint": "Dockerfile",+ "instances": { "iad1": 1 }+ }+ }+}+```++On Vercel, the relay sends messages to `https://$VERCEL_PROJECT_PRODUCTION_URL` and signs each request with the project's Vercel OIDC token, so the agent and relay need no shared secret. Set `url` to send them elsewhere.++The bot needs the **Send Messages in Threads** permission to reply in threads, in addition to **View Channels** and **Send Messages**, and **Create Public Threads** to [start threads](#reply-in-threads). This install URL grants all four plus **Read Message History**; replace `<APPLICATION_ID>`:++```text+https://discord.com/oauth2/authorize?client_id=<APPLICATION_ID>&scope=bot+applications.commands&permissions=309237713920+```++### Run the relay outside Vercel++`experimental_runDiscordGatewayRelay` runs on any host that keeps a Node.js 24 process up, such as a VM, a container platform, or a home server, while the agent stays on Vercel. Run exactly one relay per bot. Three things change off Vercel:++- **Credentials.** Vercel Connect authenticates callers with your project's Vercel OIDC token, which other hosts don't have, so give the relay the bot token directly. The agent can keep using Connect.+- **URL.** The relay can't read `VERCEL_PROJECT_PRODUCTION_URL`, so pass the agent's URL as `url`.+- **Auth.** The route's default auth accepts only your Vercel project's own runtime. Use a shared secret instead: `basic()` from `eve/agents/auth` signs the relay's requests, and `httpBasic()` on `gateway.auth` checks them.++Generate a long random secret, for example with `openssl rand -hex 32`, and set it as `DISCORD_RELAY_SECRET` on both the agent's Vercel project and the relay's host. On the agent:++```ts title="agent/channels/discord.ts"+import { connectDiscordCredentials } from "@vercel/connect/eve";+import { httpBasic, localDev } from "eve/channels/auth";+import { discordChannel } from "eve/channels/discord";++export default discordChannel({+ credentials: connectDiscordCredentials("discord/my-agent"),+ gateway: {+ auth: [+ localDev(),+ httpBasic({ username: "discord-relay", password: process.env.DISCORD_RELAY_SECRET! }),+ ],+ },+});+```++On the relay, set `DISCORD_BOT_TOKEN` to the token from **Bot** → **Reset Token** in the Discord Developer Portal, and `EVE_URL` to the agent's production URL:++```ts title="relay/main.ts"+import { basic } from "eve/agents/auth";+import { experimental_runDiscordGatewayRelay } from "eve/channels/discord/gateway";++await experimental_runDiscordGatewayRelay({+ // Reads DISCORD_BOT_TOKEN when `credentials` is omitted.+ url: process.env.EVE_URL,+ auth: basic({ username: "discord-relay", password: process.env.DISCORD_RELAY_SECRET! }),+});+```++The relay's `package.json` needs only `eve`. Build the image from the same Dockerfile as the [daemon](#run-the-relay-as-a-vercel-daemon), then run it with a restart policy so a crash or host reboot brings it back:++```bash+docker run -d --restart unless-stopped \+ -e DISCORD_BOT_TOKEN -e DISCORD_RELAY_SECRET -e EVE_URL=https://my-agent.vercel.app \+ discord-relay+```++The relay stops on `SIGTERM` after delivering what it has in flight. It exits with an error when Discord refuses the bot token or intents, and restarting it won't help until you fix the configuration. If Deployment Protection covers the URL the relay posts to, create a Protection Bypass for Automation secret, and pass `auth` a function that returns the Basic `authorization` header together with an `x-vercel-protection-bypass` header carrying that secret.++### Who the bot answers++By default the channel answers a message when it is a DM, mentions the bot, replies to one of the bot's messages, or arrives in a thread where the bot already has a conversation. It strips the bot's mention from the text, and it never answers messages from bots, including its own. Messages group into sessions this way:++| Message | Session |+| ------------------------------------ | -------------------------------------------------------------------------------------- |+| A DM | One per DM channel |+| A message in a thread | One per thread |+| A mention in a text channel | A new [thread](#reply-in-threads) started from the message, one session for the thread |+| A reply to the bot in a text channel | The session that posted the replied-to message |++A mention in a text channel starts a thread, as the Slack channel does, so each conversation stays out of the channel and two people, or one person's unrelated questions, don't share context. Every message the bot posts continues its session when someone replies to it, including slash command responses in the channel. A reply to a bot message that no live session owns starts a new thread.++Mention the bot's user, not the role with the same name that Discord creates for it. Discord's autocomplete offers both, and a role mention doesn't address the bot.++Discord sends the text of messages that neither mention the bot nor arrive as a DM only to bots with the privileged **Message Content** intent. Without it, thread follow-ups that skip the mention, and replies whose author turned off the reply ping, arrive empty and are ignored. To request the intent, enable **Message Content Intent** under **Bot** in the Discord Developer Portal, then pass `messageContent: true` to `experimental_runDiscordGatewayRelay`. Discord refuses the relay's connection if you request the intent before enabling it, and the relay stops with an error naming the close code.++To choose which messages run the agent, under what `auth`, or which session they join, set `gateway.onMessage(ctx, message)`. It runs for every message from a person and returns `{ auth }` to dispatch or `null` to ignore. `message.addressed` reports whether the default would answer, and `message.referencedMessageId` names the message it replies to. `defaultDiscordMessageAuth(message)` gives the author the same principal `defaultDiscordAuth` gives them for commands and button presses, so requester-only approvals work across both:++```ts+import { defaultDiscordMessageAuth, discordChannel } from "eve/channels/discord";++export default discordChannel({+ gateway: {+ onMessage: (_ctx, message) =>+ message.addressed && message.guildId === "123456789012345678"+ ? { auth: defaultDiscordMessageAuth(message) }+ : null,+ },+});+```++Return `conversation` to change how messages group. Messages with the same key share a session within their Discord channel. A message ID is the key of the session that owns that message, `"channel"` is one session for the whole channel, and any other string is your own grouping. Omit it to keep the default above. For example, to give each person one ongoing session per channel:++```ts+import { defaultDiscordMessageAuth, discordChannel } from "eve/channels/discord";++export default discordChannel({+ gateway: {+ onMessage: (_ctx, message) =>+ message.addressed+ ? { auth: defaultDiscordMessageAuth(message), conversation: `user:${message.author.id}` }+ : null,+ },+});+```++### Reply in threads++By default, the bot answers a mention in a text channel in a new thread. The channel starts a public thread from the person's message, named after its first line, and adds the person to it. The thread holds one session, so later messages in it continue the conversation. Threads apply only to messages that would start a new session in a text channel. DMs, messages already in a thread, and replies that continue a session stay where they are. If Discord refuses to create the thread, for example because the bot lacks **Create Public Threads**, the bot answers in the channel instead.++To answer in the channel instead, set `gateway.startThread` to `false`. A mention then starts a session in the channel, and replies to the bot's messages continue it:++```ts title="agent/channels/discord.ts"+import { connectDiscordCredentials } from "@vercel/connect/eve";+import { discordChannel } from "eve/channels/discord";++export default discordChannel({+ credentials: connectDiscordCredentials("discord/my-agent"),+ gateway: { startThread: false },+});+```++`onMessage` can decide per message by returning `startThread`, which overrides `gateway.startThread`. Return `false` to answer in the channel, `true` for a thread, or options to name the thread and set how long Discord waits before archiving it:++```ts+import { defaultDiscordMessageAuth, discordChannel } from "eve/channels/discord";++export default discordChannel({+ gateway: {+ onMessage: (_ctx, message) =>+ message.addressed+ ? {+ auth: defaultDiscordMessageAuth(message),+ startThread: message.attachments.length > 0 && {+ name: `Review: ${message.attachments[0]!.filename}`,+ autoArchiveMinutes: 1440,+ },+ }+ : null,+ },+});+```++### Forward messages from your own relay++The route accepts any relay that holds a Gateway connection, such as an existing discord.js bot, so you don't have to run `experimental_runDiscordGatewayRelay`. Forward each Gateway dispatch payload unchanged, as the JSON body of a `POST` to `/eve/v1/discord/gateway`:++```json+{+ "op": 0,+ "t": "MESSAGE_CREATE",+ "s": 42,+ "d": { "id": "…", "channel_id": "…", "author": { "…": "…" } }+}+```++The route handles `MESSAGE_CREATE` and acknowledges other dispatch types without acting on them. Authenticate the request as `gateway.auth` requires; by default, that is a Vercel OIDC token from the same project and environment. The relay needs the `GUILD_MESSAGES` (`1 << 9`) and `DIRECT_MESSAGES` (`1 << 12`) intents, plus `MESSAGE_CONTENT` (`1 << 15`) for messages that don't mention the bot. Use the response status to decide whether to retry:++| Status | Meaning | Relay should |+| ------ | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| `202` | A turn started. The body is `{ accepted: true, sessionId }`. | Stop. |+| `200` | Ignored on purpose. The body is `{ accepted: false, reason }`, for example `not_accepted`. | Stop. |+| `400` | The body is not JSON. | Not retry. |+| `401` | Authentication failed. | Fix credentials, not retry. |+| `413` | The body is over 1 MB. | Not retry. |+| `429` | Rate limited before the route ran. | Retry with backoff. |+| `5xx` | Unknown. The route answers `500` before dispatch when `onMessage` throws, but a platform `502` or `504` can come after a turn started. | Not retry, unless your relay deduplicates. |++eve does not deduplicate messages. If the relay retries after eve already started a turn, for example because the response was lost, the agent answers twice. `experimental_runDiscordGatewayRelay` retries only a `429`, or a connection that failed before the request reached eve.++### Run the relay locally++Pull a development OIDC token with `vercel env pull .env.local`, start `eve dev`, then run the relay against it from another terminal:++```bash+EVE_URL=http://localhost:2000 node --env-file=.env.local daemon/main.ts+```++Scale the production daemon to zero while you do this. Every connection receives every message, so two relays make the agent answer twice.++### Limitations++- Run one relay per bot. Each connection receives every message. Bots large enough to need Discord's sharding are out of scope.+- Messages sent while no relay is connected are not delivered. On a deploy, Vercel sends `SIGTERM` to the old daemon and starts the new one at the same time. The old relay disconnects right away, so messages sent while the new daemon boots and connects, usually a few seconds, are lost. A crash or restart leaves the same gap. The relay does not resume the previous Gateway session in a new process, so Discord does not replay these messages.+- `experimental_runDiscordGatewayRelay` drops a message, rather than retrying it, when eve answers with a `5xx`, takes longer than 30 seconds to accept it, or the connection fails after the request is sent. eve may have started the turn already, and a retry could answer twice. The relay logs each dropped message.+## How the channel handles messages### Dispatchdiff --git a/docs/channels/overview.mdx b/docs/channels/overview.mdxindex 7bb817be4..0ea548dc1 100644--- a/docs/channels/overview.mdx+++ b/docs/channels/overview.mdx@@ -98,7 +98,7 @@ eve's first-class channels use eve-owned runtimes for webhook handling, verifica| Slack mentions, DMs, buttons | [Slack](./slack) || iMessage and SMS | [Linq](./linq) || iMessage | [Photon](./photon) |-| Discord slash commands, components | [Discord](./discord) |+| Discord messages, DMs, slash commands | [Discord](./discord) || Microsoft Teams messages + Adaptive Cards | [Teams](./teams) || Telegram bot messages | [Telegram](./telegram) || SMS or speech-transcribed phone calls | [Twilio](./twilio) |diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex 2d67b699c..4da343d3a 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -511,6 +511,11 @@"import": "./dist/src/public/channels/discord/index.js","default": "./dist/src/public/channels/discord/index.js"},+ "./channels/discord/gateway": {+ "types": "./dist/src/public/channels/discord/gateway/index.d.ts",+ "import": "./dist/src/public/channels/discord/gateway/index.js",+ "default": "./dist/src/public/channels/discord/gateway/index.js"+ },"./channels/twilio": {"types": "./dist/src/public/channels/twilio/index.d.ts","import": "./dist/src/public/channels/twilio/index.js",diff --git a/packages/eve/src/internal/attachments/limited-read.ts b/packages/eve/src/internal/attachments/limited-read.tsindex f50b800c2..c30dfc424 100644--- a/packages/eve/src/internal/attachments/limited-read.ts+++ b/packages/eve/src/internal/attachments/limited-read.ts@@ -7,12 +7,12 @@ export function maxBytesOf(policy: UploadPolicy): number {}/**- * Reads a download's body, failing as soon as it passes `maxBytes`. Checks a+ * Reads a download's or request's body, failing as soon as it passes `maxBytes`. Checks a* declared `content-length` first, then counts what streams in, so a body that* misstates or omits its length still stops at the limit.*/export async function readLimitedBytes(- response: Response,+ response: Pick<Response, "body" | "headers">,maxBytes: number,adapterKind: string,): Promise<Buffer> {diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.mdindex 81b94e2fd..407d6eefd 100644--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md@@ -15,107 +15,107 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform## Questions-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| a rendered question shows every option a person can choose | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| pressing a rendered option answers the pending question with that option | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| a text reply matching an option answers the only pending question | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| a text reply that matches no option answers the question with the person's words | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| a text reply answers an open-ended question with the person's words | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| pressing options of two pending questions answers each with its own option | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| text replies answer two pending questions one at a time, in the order shown | —<sup>[3](#note-3)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| pressing an option of an answered question sends it to the agent as new input | —<sup>[4](#note-4)</sup> | —<sup>[5](#note-5)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| a message while a question without free text is pending withdraws it, and the next message gets a reply | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| a rendered question shows every option a person can choose | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing a rendered option answers the pending question with that option | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| a text reply matching an option answers the only pending question | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| a text reply that matches no option answers the question with the person's words | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| a text reply answers an open-ended question with the person's words | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing options of two pending questions answers each with its own option | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| text replies answer two pending questions one at a time, in the order shown | —<sup>[3](#note-3)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing an option of an answered question sends it to the agent as new input | —<sup>[4](#note-4)</sup> | —<sup>[5](#note-5)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| a message while a question without free text is pending withdraws it, and the next message gets a reply | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |## Tool approvals-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| a tool approval shows the tool's prompt with a choice to approve and one to cancel | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| pressing Approve runs the gated tool | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing Cancel stops the gated tool without running it | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| a text reply of approve runs the gated tool | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| a text reply of cancel stops the gated tool without running it | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| pressing Approve twice runs the gated tool once | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing Approve on one of two pending approvals runs only that tool | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| text replies answer two pending approvals one at a time, in the order shown | —<sup>[6](#note-6)</sup> | —<sup>[7](#note-7)</sup> | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ❌<sup>[8](#note-8)</sup> | ❌<sup>[8](#note-8)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| answering an approval and a question pending together settles both | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| text replies answer a question and an approval raised together, in the order shown | —<sup>[6](#note-6)</sup> | ✅ | ✅ | | ✅ | —<sup>[2](#note-2)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| a message while an approval is pending cancels it, so typing approve afterwards runs nothing and the next message gets a reply | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| pressing Approve on an approval a message cancelled runs nothing | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| a tool approval shows the tool's prompt with a choice to approve and one to cancel | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing Approve runs the gated tool | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing Cancel stops the gated tool without running it | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| a text reply of approve runs the gated tool | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| a text reply of cancel stops the gated tool without running it | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing Approve twice runs the gated tool once | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing Approve on one of two pending approvals runs only that tool | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| text replies answer two pending approvals one at a time, in the order shown | —<sup>[6](#note-6)</sup> | —<sup>[7](#note-7)</sup> | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ❌<sup>[8](#note-8)</sup> | ❌<sup>[8](#note-8)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| answering an approval and a question pending together settles both | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| text replies answer a question and an approval raised together, in the order shown | —<sup>[6](#note-6)</sup> | ✅ | ✅ | | ✅ | —<sup>[2](#note-2)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |+| a message while an approval is pending cancels it, so typing approve afterwards runs nothing and the next message gets a reply | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing Approve on an approval a message cancelled runs nothing | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |## Approval permissions-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| the requester typing approve on a requester-only approval runs the tool | —<sup>[6](#note-6)</sup> | ✅ | ✅ | | ✅ | —<sup>[2](#note-2)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| another person pressing Cancel or Approve on a requester-only approval leaves it pending | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |-| another person typing cancel or approve doesn't settle a requester-only approval | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[9](#note-9)</sup> | —<sup>[2](#note-2)</sup> | | —<sup>[9](#note-9)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> |-| another person's rejected press leaves the approval's buttons in place | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |-| another person pressing Approve on an open approval runs the tool | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| the requester typing approve on a requester-only approval runs the tool | —<sup>[6](#note-6)</sup> | ✅ | ✅ | | ✅ | —<sup>[2](#note-2)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |+| another person pressing Cancel or Approve on a requester-only approval leaves it pending | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | ✅ | | ✅ | | —<sup>[10](#note-10)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |+| another person typing cancel or approve doesn't settle a requester-only approval | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[9](#note-9)</sup> | —<sup>[2](#note-2)</sup> | | ✅ | | —<sup>[9](#note-9)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> |+| another person's rejected press leaves the approval's buttons in place | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | ✅ | | ✅ | | —<sup>[10](#note-10)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |+| another person pressing Approve on an open approval runs the tool | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[10](#note-10)</sup> | ✅ | | ✅ | | —<sup>[10](#note-10)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |## Answered prompts-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| pressing an option clears the question's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| answering a question by text clears its buttons | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing an option names who answered on the question | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | | ✅ | | ❌<sup>[14](#note-14)</sup> | | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| answering a question by text names who answered on the question | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing Approve clears the approval's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| approving by text clears the approval's buttons | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing Approve names who approved on the approval | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| approving by text names who approved on the approval | —<sup>[6](#note-6)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| pressing an option clears the question's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| answering a question by text clears its buttons | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing an option names who answered on the question | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | ❌<sup>[14](#note-14)</sup> | | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | | ✅ | | ❌<sup>[14](#note-14)</sup> | | ❌<sup>[14](#note-14)</sup> | | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| answering a question by text names who answered on the question | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing Approve clears the approval's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| approving by text clears the approval's buttons | —<sup>[6](#note-6)</sup> | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing Approve names who approved on the approval | —<sup>[12](#note-12)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | ❌<sup>[14](#note-14)</sup> | | ❌<sup>[14](#note-14)</sup> | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ❌<sup>[14](#note-14)</sup> | | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| approving by text names who approved on the approval | —<sup>[6](#note-6)</sup> | —<sup>[13](#note-13)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | ❌<sup>[14](#note-14)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |## Inactive prompts-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| pressing Approve after the session's run ended outside eve runs nothing and clears the approval's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing an option after the session's run ended outside eve clears the question's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| pressing an option after the session's run ended outside eve tells the person it is no longer active | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| a question pressed after the session's run ended outside eve keeps its prompt and says it is no longer active | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| pressing Approve after the session's run ended outside eve runs nothing and clears the approval's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing an option after the session's run ended outside eve clears the question's buttons | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| pressing an option after the session's run ended outside eve tells the person it is no longer active | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| a question pressed after the session's run ended outside eve keeps its prompt and says it is no longer active | ✅ | ✅ | ❌<sup>[15](#note-15)</sup> | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |## Budget prompts-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| running out of budget opens budget prompt | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| pressing approve on budget prompt allows agent to continue | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| reply of approve on budget prompt allows agent to continue | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| pressing stop on budget prompt halts work, next message asks again | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |-| reply of stop on budget prompt halts work, next message asks again | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| query sent during budget prompt answered after budget approval | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| running out of budget opens budget prompt | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing approve on budget prompt allows agent to continue | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ✅ | | ✅ | | —<sup>[1](#note-1)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| reply of approve on budget prompt allows agent to continue | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| pressing stop on budget prompt halts work, next message asks again | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> |+| reply of stop on budget prompt halts work, next message asks again | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| query sent during budget prompt answered after budget approval | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |## Sign-ins-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ✅ |-| a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ✅ |-| only the person signing in sees the sign-in link and code | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | ❌<sup>[20](#note-20)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |-| someone else pressing a sign-in isn't shown its link or code | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[22](#note-22)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |-| a sign-in without a link shows its instructions | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |-| after signing in, the agent carries on with the request | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |-| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |-| message after ignored sign-in gets an answer, signing in late doesn't run | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| message after ignored sign-in tells user it was cancelled | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ✅ |+| a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ✅ |+| only the person signing in sees the sign-in link and code | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | —<sup>[19](#note-19)</sup> | ✅ | ✅ | ❌<sup>[20](#note-20)</sup> | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> |+| someone else pressing a sign-in isn't shown its link or code | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[22](#note-22)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[22](#note-22)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[21](#note-21)</sup> | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[22](#note-22)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[1](#note-1)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> |+| a sign-in without a link shows its instructions | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |+| after signing in, the agent carries on with the request | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ | ✅ |+| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |+| message after ignored sign-in gets an answer, signing in late doesn't run | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ❌<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| message after ignored sign-in tells user it was cancelled | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[2](#note-2)</sup> | —<sup>[2](#note-2)</sup> | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ |## Tool callers-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| a tool sees the person who sent the message as its caller | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |-| another person's message reaches tools as a different caller, and each person stays the same caller | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[9](#note-9)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| a tool sees the person who sent the message as its caller | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |+| another person's message reaches tools as a different caller, and each person stays the same caller | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> | ✅ | | —<sup>[9](#note-9)</sup> | ✅ | | ✅ | | —<sup>[9](#note-9)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[9](#note-9)</sup> |## Attachments-| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `github` | `linear` | `photon` | `twilio` |-| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |-| an image a person sends reaches the agent with its bytes and type | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |-| a PDF a person sends reaches the agent with its bytes and type | —<sup>[23](#note-23)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |-| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[23](#note-23)</sup> | —<sup>[24](#note-24)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |-| a file sent earlier in the conversation is still there on a later message | —<sup>[23](#note-23)</sup> | ✅ | ✅ | | ✅ | —<sup>[25](#note-25)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[23](#note-23)</sup> | ✅ | ✅ | ✅ |+| Rule | `tui` | `web chat` | `chat-sdk` | `chat-sdk-dm` | `chat-sdk-text` | `discord` | `discord-dm` | `discord-gateway` | `discord-gateway-dm` | `linq` | `linq-dm` | `slack` | `slack-dm` | `teams` | `teams-dm` | `telegram` | `telegram-dm` | `discord-gateway-threads` | `github` | `linear` | `photon` | `twilio` |+| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |+| an image a person sends reaches the agent with its bytes and type | —<sup>[24](#note-24)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[24](#note-24)</sup> | ✅ | ✅ | ✅ |+| a PDF a person sends reaches the agent with its bytes and type | —<sup>[24](#note-24)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[24](#note-24)</sup> | ✅ | ✅ | ✅ |+| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[24](#note-24)</sup> | —<sup>[25](#note-25)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[24](#note-24)</sup> | ✅ | ✅ | ✅ |+| a file sent earlier in the conversation is still there on a later message | —<sup>[24](#note-24)</sup> | ✅ | ✅ | | ✅ | —<sup>[26](#note-26)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[24](#note-24)</sup> | ✅ | ✅ | ✅ |## Notes@@ -141,6 +141,7 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform20. <a id="note-20"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified21. <a id="note-21"></a>the sign-in goes privately to the person signing in, so the thread shows nothing to press22. <a id="note-22"></a>the channel shows no sign-in, so there's nothing to press-23. <a id="note-23"></a>the platform has no files a person can send-24. <a id="note-24"></a>the browser sends a file's bytes with the message, so there is no download to fail-25. <a id="note-25"></a>each slash command starts its own session, so no later message shares one with the file+23. <a id="note-23"></a>the channel shows no sign-in, so the person's next message has nothing to reply to and starts a new session, leaving the sign-in open+24. <a id="note-24"></a>the platform has no files a person can send+25. <a id="note-25"></a>the browser sends a file's bytes with the message, so there is no download to fail+26. <a id="note-26"></a>each slash command starts its own session, so no later message shares one with the filediff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.tsindex 3a4d4d936..520f71365 100644--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts@@ -163,6 +163,23 @@ const DISCORD_BROKEN = {),};+/** Gateway messages are plain text, so they reach rules interactions can't. */+const DISCORD_GATEWAY_BROKEN = {+ ...DISCORD_BROKEN,+ ...unnamedAnsweredPrompts(UNNAMED_RESPONDER, ["approvalText", "questionText"]),+ ...noSignInRenderer("message after ignored sign-in tells user it was cancelled"),+};++/** In a server, a person continues by replying to the bot's message, and there is none for a sign-in. */+const DISCORD_GATEWAY_SHARED_BROKEN = {+ ...DISCORD_GATEWAY_BROKEN,+ "message after ignored sign-in gets an answer, signing in late doesn't run": {+ reason:+ "the channel shows no sign-in, so the person's next message has nothing to reply to and starts a new session, leaving the sign-in open",+ symptom: /read_calendar ran after its sign-in was cancelled/u,+ },+};+const SIGN_IN_PRESS_RULE = "someone else pressing a sign-in isn't shown its link or code";/** The challenge goes privately to the person signing in, so the thread has no sign-in to press. */@@ -171,8 +188,12 @@ const SIGN_IN_SENT_PRIVATELY = {"the sign-in goes privately to the person signing in, so the thread shows nothing to press",} satisfies Partial<Record<ContractRuleName, string>>;-const DISCORD_UNSUPPORTED = {+const DISCORD_GATEWAY_UNSUPPORTED = {[SIGN_IN_PRESS_RULE]: "the channel shows no sign-in, so there's nothing to press",+} satisfies Partial<Record<ContractRuleName, string>>;++const DISCORD_UNSUPPORTED = {+ ...DISCORD_GATEWAY_UNSUPPORTED,"a file sent earlier in the conversation is still there on a later message":"each slash command starts its own session, so no later message shares one with the file",} satisfies Partial<Record<ContractRuleName, string>>;@@ -228,7 +249,19 @@ const channelConformance = {{ driver: chatSdkTextDriver },],"chat-sdk-dm": [{ dm: true, driver: () => chatSdkDriver("private"), broken: CHAT_SDK_BROKEN }],- discord: [{ driver: discordDriver, broken: DISCORD_BROKEN, unsupported: DISCORD_UNSUPPORTED }],+ discord: [+ { driver: () => discordDriver(), broken: DISCORD_BROKEN, unsupported: DISCORD_UNSUPPORTED },+ {+ driver: () => discordDriver("shared", "gateway"),+ broken: DISCORD_GATEWAY_SHARED_BROKEN,+ unsupported: DISCORD_GATEWAY_UNSUPPORTED,+ },+ {+ driver: () => discordDriver("shared", "gateway-threads"),+ broken: DISCORD_GATEWAY_BROKEN,+ unsupported: DISCORD_GATEWAY_UNSUPPORTED,+ },+ ],"discord-dm": [{dm: true,@@ -236,6 +269,12 @@ const channelConformance = {broken: DISCORD_BROKEN,unsupported: DISCORD_UNSUPPORTED,},+ {+ dm: true,+ driver: () => discordDriver("private", "gateway"),+ broken: DISCORD_GATEWAY_BROKEN,+ unsupported: DISCORD_GATEWAY_UNSUPPORTED,+ },],github: [{diff --git a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts b/packages/eve/src/internal/testing/channel-conformance/discord-driver.tsindex 22b7494c6..f33dacef8 100644--- a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts+++ b/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts@@ -1,6 +1,6 @@import { generateKeyPairSync, sign, type KeyObject } from "node:crypto";-import { discordChannel } from "#public/channels/discord/index.js";+import { discordContinuationToken, discordChannel } from "#public/channels/discord/index.js";import {type ChannelDriver,type Person,@@ -46,11 +46,32 @@ function testKeys(): { privateKey: KeyObject; publicKeyHex: string } {}/**- * Drives Discord's signed application-command and component interaction- * webhooks, in a server text channel by default or in a DM.+ * How a person's messages reach eve: as `/ask` slash commands, or as ordinary+ * messages a Gateway relay forwards, optionally answered in a new thread.*/-export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): ChannelDriver {+export type DiscordTransport = "interactions" | "gateway" | "gateway-threads";++/** The relay's identity; the conformance route trusts it the way production trusts the daemon. */+const RELAY_AUTH = {+ attributes: {},+ authenticator: "conformance-relay",+ principalId: "relay",+ principalType: "service",+} as const;++/**+ * Drives Discord, in a server text channel by default or in a DM. Messages+ * arrive as signed application-command interactions or, with a Gateway+ * transport, as forwarded `MESSAGE_CREATE` dispatches; presses are always+ * component interactions.+ */+export function discordDriver(+ surface: Exclude<Surface, "public"> = "shared",+ transport: DiscordTransport = "interactions",+): ChannelDriver {const dm = surface === "private";+ const gateway = transport !== "interactions";+ const threads = transport === "gateway-threads";// In a server, Discord names the actor as a member; in a DM, as a user.const where = (user: (typeof PEOPLE)[Person] = PERSON) =>dm@@ -65,6 +86,13 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Cconst uploads = new Map<string, SentFile>();/** The message each interaction token's `@original` response is, once known. */const originals = new Map<string, string>();+ /** The thread the bot started for the conversation, once it has. */+ let threadId: string | undefined;+ /** The bot's latest channel message, which a person in a server replies to so the bot hears them. */+ let lastBotMessage: string | undefined;+ let dispatchSequence = 0;+ /** Where the conversation happens now: the channel, or the thread the bot moved it to. */+ const conversationChannel = () => threadId ?? channelId;function signed(body: string): Request {const timestamp = String(Math.floor(Date.now() / 1000));@@ -92,16 +120,77 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Cconst text = await request.text();const body = text === "" ? {} : JSON.parse(text);const path = url.pathname;+ const method = `${request.method} ${path}`;if (path.endsWith("/typing")) {- return { body, method: `POST ${path}`, response: {} };+ return { body, method, response: {} };+ }+ const channelLookup = /^\/api\/v\d+\/channels\/([^/]+)$/u.exec(path);+ if (request.method === "GET" && channelLookup !== null) {+ const id = channelLookup[1]!;+ return { body, method, response: { id, type: dm ? 1 : id === threadId ? 11 : 0 } };+ }+ if (path.endsWith("/threads")) {+ threadId = `T_CONFORMANCE_${channelId}`;+ return { body, method, response: { id: threadId, type: 11 } };+ }+ if (path.includes("/thread-members/")) return { body, method, response: {} };+ const id = writtenMessageId(request.method, path);+ if (request.method === "POST" && /\/channels\/[^/]+\/messages$/u.test(path)) {+ lastBotMessage = id;}return {body,- method: `${request.method} ${path}`,- response: { channel_id: channelId, id: writtenMessageId(request.method, path) },+ method,+ response: { channel_id: /\/channels\/([^/]+)\//u.exec(path)?.[1] ?? channelId, id },};}+ /** `person`'s message as the relay forwards it: the Gateway dispatch, unchanged. */+ function gatewayMessage(text: string, person: Person, files: readonly SentFile[]): Request {+ dispatchSequence += 1;+ const id = `U_MESSAGE_${channelId}_${dispatchSequence}`;+ // In a server, a person mentions the bot once, then replies to its latest+ // message, unless the bot moved the conversation into a thread, where every+ // message reaches it. The mention sits on its own line so the test model's+ // line-based directives still read the message.+ const replyTo = !dm && !threads ? lastBotMessage : undefined;+ const mention = !dm && replyTo === undefined && threadId === undefined;+ return new Request("https://agent.example.com/eve/v1/discord/gateway", {+ body: JSON.stringify({+ d: {+ attachments: files.map((file, index) => {+ const attachmentId = `A_${id}_${index}`;+ const url = `https://cdn.discordapp.com/attachments/${channelId}/${attachmentId}/${file.name}?ex=signed`;+ uploads.set(url, file);+ return {+ content_type: file.mediaType,+ filename: file.name,+ id: attachmentId,+ size: file.bytes.length,+ url,+ };+ }),+ author: PEOPLE[person],+ channel_id: conversationChannel(),+ content: mention ? `${text}\n<@APP1>` : text,+ ...(!dm && { guild_id: "G_CONFORMANCE" }),+ id,+ mentions: mention ? [{ id: "APP1" }] : [],+ ...(replyTo !== undefined && {+ message_reference: { message_id: replyTo, type: 0 },+ referenced_message: { author: { bot: true, id: "APP1" }, id: replyTo },+ }),+ type: replyTo === undefined ? 0 : 19,+ },+ op: 0,+ s: dispatchSequence,+ t: "MESSAGE_CREATE",+ }),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ }+/** Edits keep the id of the message they rewrite; everything else posts a new message. */function writtenMessageId(method: string, path: string): string {const original = /^\/api\/v\d+\/webhooks\/[^/]+\/([^/]+)\/messages\/@original$/u.exec(path);@@ -129,16 +218,28 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): C}return {- name: dm ? "discord-dm" : "discord",+ name: `discord${gateway ? `-${transport}` : ""}${dm ? "-dm" : ""}`,personId: PERSON.id,- capabilities: dm ? ["attachments", "buttons"] : ["attachments", "another-person", "buttons"],+ capabilities: [+ "attachments",+ ...(dm ? [] : (["another-person"] as const)),+ "buttons",+ ...(gateway ? (["text-replies"] as const) : []),+ ],surface,createChannel: (record) =>discordChannel({api: { fetch: recordingFetch(record, decode) },credentials: { applicationId: "APP1", botToken: "bot-token", publicKey: publicKeyHex },+ ...(gateway && { gateway: { auth: () => RELAY_AUTH, startThread: threads } }),}),+ // A reply to the bot's message continues the session that posted it.+ nextAddress: () =>+ gateway && !dm && !threads && lastBotMessage !== undefined+ ? discordContinuationToken(channelId, lastBotMessage)+ : undefined,message: (text, person, files = []) => {+ if (gateway) return gatewayMessage(text, person, files);const id = nextInteraction();// Each file rides an attachment option (type 11) whose value names it in `resolved`.const attached = files.map((file, index) => {@@ -216,7 +317,7 @@ export function discordDriver(surface: Exclude<Surface, "public"> = "shared"): Creturn signed(JSON.stringify({application_id: "APP1",- channel_id: channelId,+ channel_id: conversationChannel(),data:handle.value === undefined? { component_type: 2, custom_id: handle.customId }@@ -277,5 +378,9 @@ function visibleChoices(* channel message when the interaction token fails.*/function isMessageWrite(call: PlatformCall): boolean {- return /^(PATCH|POST) /u.test(call.method) && !call.method.endsWith("/typing");+ return (+ /^(PATCH|POST) /u.test(call.method) &&+ !call.method.endsWith("/typing") &&+ !call.method.endsWith("/threads")+ );}diff --git a/packages/eve/src/internal/testing/mock-vercel-oidc-issuer.ts b/packages/eve/src/internal/testing/mock-vercel-oidc-issuer.tsnew file mode 100644index 000000000..8b6b90d4b--- /dev/null+++ b/packages/eve/src/internal/testing/mock-vercel-oidc-issuer.ts@@ -0,0 +1,74 @@+import { exportJWK, generateKeyPair, SignJWT } from "jose";+import { vi } from "vitest";++/**+ * Installs a mocked Vercel OIDC issuer for unit-tier verifier tests.+ *+ * Generates a fresh RSA keypair, exports the public key as a JWK, and+ * installs a `globalThis.fetch` spy that responds to the issuer's+ * discovery and JWKS endpoints. Each call uses a unique team slug so+ * jose's module-level JWKS cache (keyed on the JWKS URL) does not bleed+ * keys across tests when several cases run in the same file.+ */+export async function installMockedVercelIssuer(+ slug: string,+ issuerMode: "global" | "team" = "team",+): Promise<{+ readonly issuer: string;+ readonly signToken: (+ claims: Record<string, unknown>,+ options?: { readonly audience?: string },+ ) => Promise<string>;+ readonly restore: () => void;+}> {+ const teamSlug = `${slug}-${crypto.randomUUID()}`;+ const issuer =+ issuerMode === "global" ? "https://oidc.vercel.com" : `https://oidc.vercel.com/${teamSlug}`;+ const audience = `https://vercel.com/${teamSlug}`;+ const jwksUrl = `${issuer}/.well-known/jwks.json`;+ const discoveryUrl = `${issuer}/.well-known/openid-configuration`;+ const keyId = `test-key-${teamSlug}`;++ const { privateKey, publicKey } = await generateKeyPair("RS256");+ const publicJwk = await exportJWK(publicKey);++ const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;++ if (url === discoveryUrl) {+ return new Response(JSON.stringify({ issuer, jwks_uri: jwksUrl }), {+ headers: { "content-type": "application/json" },+ status: 200,+ });+ }++ if (url === jwksUrl) {+ return new Response(JSON.stringify({ keys: [{ ...publicJwk, kid: keyId, use: "sig" }] }), {+ headers: { "content-type": "application/json" },+ status: 200,+ });+ }++ return new Response("not found", { status: 404 });+ });++ return {+ issuer,+ restore() {+ fetchSpy.mockRestore();+ },+ async signToken(claims, options) {+ const { sub, ...rest } = claims;+ return await new SignJWT(rest)+ .setProtectedHeader({ alg: "RS256", kid: keyId })+ .setAudience(options?.audience ?? audience)+ .setExpirationTime("5m")+ .setIssuedAt()+ .setIssuer(issuer)+ .setSubject(+ typeof sub === "string" ? sub : "owner:acme:project:test:environment:production",+ )+ .sign(privateKey);+ },+ };+}diff --git a/packages/eve/src/public/channels/auth.test.ts b/packages/eve/src/public/channels/auth.test.tsindex 95c7ed0fe..98ddff721 100644--- a/packages/eve/src/public/channels/auth.test.ts+++ b/packages/eve/src/public/channels/auth.test.ts@@ -1,6 +1,8 @@-import { exportJWK, exportSPKI, generateKeyPair, SignJWT } from "jose";+import { exportSPKI, generateKeyPair, SignJWT } from "jose";import { afterEach, describe, expect, it, vi } from "vitest";+import { installMockedVercelIssuer } from "#internal/testing/mock-vercel-oidc-issuer.js";+import { EVE_SESSION_ROUTE_PATH } from "#protocol/routes.js";import type { SessionAuthContext } from "#channel/types.js";import { withVercelOidcProjectResolver } from "#channel/auth/vercel-oidc-project.js";@@ -1304,78 +1306,6 @@ describe("verifyVercelOidc", () => {});});-/**- * Installs a mocked Vercel OIDC issuer for unit-tier verifier tests.- *- * Generates a fresh RSA keypair, exports the public key as a JWK, and- * installs a `globalThis.fetch` spy that responds to the issuer's- * discovery and JWKS endpoints. Each call uses a unique team slug so- * jose's module-level JWKS cache (keyed on the JWKS URL) does not bleed- * keys across tests when several cases run in the same file.- */-async function installMockedVercelIssuer(- slug: string,- issuerMode: "global" | "team" = "team",-): Promise<{- readonly issuer: string;- readonly signToken: (- claims: Record<string, unknown>,- options?: { readonly audience?: string },- ) => Promise<string>;- readonly restore: () => void;-}> {- const teamSlug = `${slug}-${crypto.randomUUID()}`;- const issuer =- issuerMode === "global" ? "https://oidc.vercel.com" : `https://oidc.vercel.com/${teamSlug}`;- const audience = `https://vercel.com/${teamSlug}`;- const jwksUrl = `${issuer}/.well-known/jwks.json`;- const discoveryUrl = `${issuer}/.well-known/openid-configuration`;- const keyId = `test-key-${teamSlug}`;-- const { privateKey, publicKey } = await generateKeyPair("RS256");- const publicJwk = await exportJWK(publicKey);-- const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;-- if (url === discoveryUrl) {- return new Response(JSON.stringify({ issuer, jwks_uri: jwksUrl }), {- headers: { "content-type": "application/json" },- status: 200,- });- }-- if (url === jwksUrl) {- return new Response(JSON.stringify({ keys: [{ ...publicJwk, kid: keyId, use: "sig" }] }), {- headers: { "content-type": "application/json" },- status: 200,- });- }-- return new Response("not found", { status: 404 });- });-- return {- issuer,- restore() {- fetchSpy.mockRestore();- },- async signToken(claims, options) {- const { sub, ...rest } = claims;- return await new SignJWT(rest)- .setProtectedHeader({ alg: "RS256", kid: keyId })- .setAudience(options?.audience ?? audience)- .setExpirationTime("5m")- .setIssuedAt()- .setIssuer(issuer)- .setSubject(- typeof sub === "string" ? sub : "owner:acme:project:test:environment:production",- )- .sign(privateKey);- },- };-}-describe("vercelSubject", () => {it("formats a strict project subject with explicit environment", () => {expect(diff --git a/packages/eve/src/public/channels/discord/defaults.ts b/packages/eve/src/public/channels/discord/defaults.tsindex a2ec201b0..81194b7a5 100644--- a/packages/eve/src/public/channels/discord/defaults.ts+++ b/packages/eve/src/public/channels/discord/defaults.ts@@ -9,7 +9,12 @@ import {import type {DiscordCommandInteraction,DiscordInteractionBase,+ DiscordUser,} from "#public/channels/discord/inbound.js";+import type {+ DiscordGatewayMessage,+ DiscordMessageResult,+} from "#public/channels/discord/messages.js";import { renderInputRequestComponents } from "#public/channels/discord/hitl.js";import type {DiscordChannelEvents,@@ -25,31 +30,51 @@ const log = createLogger("discord.defaults");* Builds the default {@link SessionAuthContext} for the user behind a Discord* interaction (a command, button press, select, or modal submission):* authenticator `discord-interaction`, guild-scoped issuer/principalId when- * invoked in a guild (else user-scoped), and `principalType` `service` for bot- * actors or `user` otherwise. Copies the channel, interaction, user, guild,- * and member-nick attributes.+ * invoked in a guild (else user-scoped), and `principalType` `service` for bot actors or+ * `user` otherwise. Copies the channel, interaction, user, guild, and+ * member-nick attributes. A message from the same person gets the same+ * principal from {@link defaultDiscordMessageAuth}.*/export function defaultDiscordAuth(interaction: DiscordInteractionBase): SessionAuthContext {const attributes: Record<string, string> = {channel_id: interaction.channelId,interaction_id: interaction.id,- user_id: interaction.user.id,- username: interaction.user.username,};- if (interaction.guildId !== undefined) attributes.guild_id = interaction.guildId;if (interaction.member?.nick !== undefined) attributes.member_nick = interaction.member.nick;+ return discordUserAuth(interaction.user, interaction.guildId, attributes);+}- const issuer = interaction.guildId ? `discord:${interaction.guildId}` : "discord";- const principalId = interaction.guildId- ? `discord:${interaction.guildId}:${interaction.user.id}`- : `discord:${interaction.user.id}`;+/**+ * Builds the default {@link SessionAuthContext} for the author of a Discord+ * message forwarded from the Gateway. The principal matches what+ * {@link defaultDiscordAuth} builds for the same person, so their button+ * presses answer approvals their messages asked for.+ */+export function defaultDiscordMessageAuth(message: DiscordGatewayMessage): SessionAuthContext {+ return discordUserAuth(message.author, message.guildId, {+ channel_id: message.channelId,+ message_id: message.id,+ });+}+function discordUserAuth(+ user: DiscordUser,+ guildId: string | undefined,+ attributes: Record<string, string>,+): SessionAuthContext {+ const allAttributes: Record<string, string> = {+ ...attributes,+ user_id: user.id,+ username: user.username,+ };+ if (guildId !== undefined) allAttributes.guild_id = guildId;return {- attributes,+ attributes: allAttributes,+ // Shared by messages too, so changing it would orphan every existing Discord principal.authenticator: "discord-interaction",- issuer,- principalId,- principalType: interaction.user.isBot ? "service" : "user",+ issuer: guildId ? `discord:${guildId}` : "discord",+ principalId: guildId ? `discord:${guildId}:${user.id}` : `discord:${user.id}`,+ principalType: user.isBot ? "service" : "user",};}@@ -81,6 +106,14 @@ export async function editDiscordResolvedPrompt(}}+/** Default Gateway message hook: dispatch messages addressed to the bot with Discord user auth. */+export function defaultOnMessage(+ _ctx: DiscordContext,+ message: DiscordGatewayMessage,+): DiscordMessageResult {+ return message.addressed ? { auth: defaultDiscordMessageAuth(message) } : null;+}+/** Built-in Discord event handlers for typing, replies, HITL, and terminal errors. */export const defaultEvents: DiscordChannelEvents = {async "turn.started"(_event, channel, _ctx) {@@ -143,7 +176,7 @@ export const defaultEvents: DiscordChannelEvents = {[`This session could not recover from an error${hint}.`,"",- "Start a new command to continue.",+ "Send a new message or command to continue.",...(errorId ? ["", `Error id: ${errorId}`] : []),].join("\n"),);diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.tsindex 8b91ed7ee..6eba84b5f 100644--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts@@ -16,8 +16,14 @@ import {DISCORD_HITL_FREEFORM_TEXT_INPUT_ID,renderInputRequestComponents,} from "#public/channels/discord/hitl.js";-import { defaultDiscordAuth, discordChannel } from "#public/channels/discord/index.js";+import {+ defaultDiscordAuth,+ defaultDiscordMessageAuth,+ discordChannel,+ type DiscordGatewayConfig,+} from "#public/channels/discord/index.js";import { captureLogRecords } from "#internal/testing/log-records.js";+import { installMockedVercelIssuer } from "#internal/testing/mock-vercel-oidc-issuer.js";import { mockAgentRouteArgs } from "#internal/testing/mocks/mock-route-args.js";function asCompiled<T = unknown>(channel: unknown): CompiledChannel<T> {@@ -703,7 +709,424 @@ describe("discordChannel() default event handlers", () => {});});+const RELAY_AUTH = {+ attributes: {},+ authenticator: "test-relay",+ principalId: "relay",+ principalType: "service",+} as const;++function messageCreate(message: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ d: {+ attachments: [],+ author: { id: "U01", username: "ada" },+ channel_id: "C01",+ content: "<@APP1> hello",+ guild_id: "G01",+ id: "M01",+ mentions: [{ id: "APP1" }],+ type: 0,+ ...message,+ },+ op: 0,+ s: 7,+ t: "MESSAGE_CREATE",+ };+}++/** A Gateway-enabled channel whose Discord channel lookups report `channelType`. */+function gatewayChannel(+ options: {+ readonly channelType?: number;+ readonly threadCreation?: "ok" | "refused";+ readonly gateway?: DiscordGatewayConfig;+ } = {},+) {+ const discordFetch = vi.fn<typeof fetch>(async (input) => {+ const path = new URL(String(input)).pathname;+ if (path.endsWith("/threads")) {+ return options.threadCreation === "refused"+ ? Response.json({ message: "Missing Permissions" }, { status: 403 })+ : Response.json({ id: "T01", type: 11 });+ }+ if (path.includes("/thread-members/")) return new Response(null, { status: 204 });+ return Response.json({ id: "C01", type: options.channelType ?? 0 });+ });+ const channel = discordChannel({+ api: { fetch: discordFetch },+ credentials: { applicationId: "APP1", botToken: "bot-token" },+ gateway: { auth: () => RELAY_AUTH, ...options.gateway },+ });+ return { channel, discordFetch };+}++async function fireGateway(+ channel: unknown,+ body: unknown,+ options: { readonly activeTokens?: readonly string[]; readonly bearer?: string } = {},+): Promise<{ response: Response; send: ReturnType<typeof vi.fn> }> {+ const route = asCompiled(channel).routes.find(+ (candidate) => isHttpRouteDefinition(candidate) && candidate.path === "/eve/v1/discord/gateway",+ );+ if (!route || !isHttpRouteDefinition(route)) throw new Error("Expected a Gateway route.");+ const send = vi.fn().mockResolvedValue({ id: "s1" });+ const response = await route.handler(+ new Request("https://example.com/eve/v1/discord/gateway", {+ body: JSON.stringify(body),+ headers: options.bearer === undefined ? {} : { authorization: `Bearer ${options.bearer}` },+ method: "POST",+ }),+ {+ ...mockAgentRouteArgs(),+ attachSession: vi.fn() as any,+ ...mockChannelContext(send),+ resolveSession: async (token: string) =>+ options.activeTokens?.includes(token) ? ({ id: "existing" } as any) : undefined,+ to: vi.fn() as any,+ params: {},+ requestIp: null,+ waitUntil: vi.fn(),+ },+ );+ return { response, send };+}++describe("discordChannel() Gateway route", () => {+ it("mounts only when gateway is configured", () => {+ expect(discordChannel({ gateway: {} }).routes.map((route) => route.path)).toEqual([+ "/eve/v1/discord",+ "/eve/v1/discord/gateway",+ ]);+ });++ it("dispatches a direct message to one session per DM channel", async () => {+ const { channel, discordFetch } = gatewayChannel();++ const { response, send } = await fireGateway(+ channel,+ messageCreate({ channel_id: "D01", content: "hi there", guild_id: undefined, mentions: [] }),+ );++ expect(response.status).toBe(202);+ expect(discordFetch).not.toHaveBeenCalled();+ const [token, input] = send.mock.calls[0]!;+ expect(token).toBe("D01:channel");+ expect(input).toMatchObject({+ auth: { authenticator: "discord-interaction", principalId: "discord:U01" },+ message: "hi there",+ state: {+ audience: "private",+ channelId: "D01",+ conversationId: "channel",+ guildId: null,+ hasMessageAnchor: true,+ interactionToken: null,+ },+ });+ expect((input as { context: string[] }).context[0]).toContain("message_id: M01");+ });++ it.each([+ {+ name: "without threads, a mention in a channel starts a new session keyed by the message",+ message: {},+ activeTokens: [],+ token: "C01:M01",+ },+ {+ name: "a reply to the bot continues the session that posted the replied-to message",+ message: {+ content: "and then?",+ mentions: [],+ message_reference: { message_id: "B01" },+ referenced_message: { author: { id: "APP1" }, id: "B01" },+ type: 19,+ },+ activeTokens: ["C01:B01"],+ token: "C01:B01",+ },+ {+ name: "without threads, a reply to a bot message no session owns starts a new session",+ message: {+ content: "and then?",+ mentions: [],+ message_reference: { message_id: "B01" },+ referenced_message: { author: { id: "APP1" }, id: "B01" },+ type: 19,+ },+ activeTokens: [],+ token: "C01:M01",+ },+ ])("$name", async ({ message, activeTokens, token }) => {+ const { channel } = gatewayChannel({ channelType: 0, gateway: { startThread: false } });++ const { send } = await fireGateway(channel, messageCreate(message), { activeTokens });++ expect(send).toHaveBeenCalledTimes(1);+ expect(send.mock.calls[0]![0]).toBe(token);+ expect(send.mock.calls[0]![1]).toMatchObject({+ auth: { principalId: "discord:G01:U01" },+ message: expect.stringMatching(/^(hello|and then\?)$/),+ });+ });++ it("starts one session for a whole thread", async () => {+ const { channel } = gatewayChannel({ channelType: 11 });++ const { send } = await fireGateway(channel, messageCreate());++ expect(send.mock.calls[0]![0]).toBe("C01:channel");+ });++ describe("startThread", () => {+ const calls = (discordFetch: ReturnType<typeof gatewayChannel>["discordFetch"]) =>+ discordFetch.mock.calls.map(([input, init]) => ({+ body: init?.body === undefined ? undefined : JSON.parse(String(init.body)),+ method: init?.method,+ path: new URL(String(input)).pathname,+ }));++ it("answers a mention in a new thread that holds the session by default", async () => {+ const { channel, discordFetch } = gatewayChannel();++ const { send } = await fireGateway(+ channel,+ messageCreate({ content: "<@APP1> Plan the launch\nwith details" }),+ );++ expect(calls(discordFetch)).toEqual([+ { body: undefined, method: "GET", path: "/api/v10/channels/C01" },+ {+ body: { name: "Plan the launch" },+ method: "POST",+ path: "/api/v10/channels/C01/messages/M01/threads",+ },+ { body: undefined, method: "PUT", path: "/api/v10/channels/T01/thread-members/U01" },+ ]);+ const [token, input] = send.mock.calls[0]!;+ expect(token).toBe("T01:channel");+ expect(input).toMatchObject({ state: { channelId: "T01", conversationId: "channel" } });+ });++ it("lets onMessage start a thread with options or opt out of the default", async () => {+ const { channel, discordFetch } = gatewayChannel({+ gateway: {+ startThread: true,+ onMessage: (_ctx, message) => ({+ auth: defaultDiscordMessageAuth(message),+ startThread: message.content.startsWith("quick")+ ? false+ : { autoArchiveMinutes: 60, name: "Support" },+ }),+ },+ });++ const quick = await fireGateway(channel, messageCreate({ content: "<@APP1> quick one" }));+ const threaded = await fireGateway(channel, messageCreate({ id: "M02" }));++ expect(quick.send.mock.calls[0]![0]).toBe("C01:M01");+ expect(threaded.send.mock.calls[0]![0]).toBe("T01:channel");+ expect(calls(discordFetch)).toContainEqual({+ body: { auto_archive_duration: 60, name: "Support" },+ method: "POST",+ path: "/api/v10/channels/C01/messages/M02/threads",+ });+ });++ it.each([+ { name: "a message already in a thread", channelType: 11, token: "C01:channel" },+ { name: "a refused thread creation", threadCreation: "refused" as const, token: "C01:M01" },+ ])(+ "answers where the message is after $name",+ async ({ channelType, threadCreation, token }) => {+ const { channel } = gatewayChannel({+ channelType,+ gateway: { startThread: true },+ threadCreation,+ });++ const { send } = await fireGateway(channel, messageCreate());++ expect(send.mock.calls[0]![0]).toBe(token);+ },+ );+ });++ it("continues a thread conversation without a mention", async () => {+ const { channel, discordFetch } = gatewayChannel();++ const { send } = await fireGateway(+ channel,+ messageCreate({ content: "one more thing", mentions: [] }),+ { activeTokens: ["C01:channel"] },+ );++ expect(discordFetch).not.toHaveBeenCalled();+ expect(send.mock.calls[0]![0]).toBe("C01:channel");+ });++ it("ignores channel messages that are not for the bot", async () => {+ const { channel } = gatewayChannel();++ const { response, send } = await fireGateway(+ channel,+ messageCreate({ content: "just chatting", mentions: [] }),+ );++ await expect(response.json()).resolves.toEqual({ accepted: false, reason: "not_accepted" });+ expect(send).not.toHaveBeenCalled();+ });++ it("never dispatches messages from bots, including its own replies", async () => {+ const onMessage = vi.fn(() => ({ auth: null }));+ const { channel } = gatewayChannel({ gateway: { onMessage } });++ const { send } = await fireGateway(+ channel,+ messageCreate({ author: { bot: true, id: "APP1", username: "eve" } }),+ );++ expect(onMessage).not.toHaveBeenCalled();+ expect(send).not.toHaveBeenCalled();+ });++ it("lets onMessage accept messages the default would ignore and choose their session", async () => {+ const { channel, discordFetch } = gatewayChannel({+ gateway: {+ onMessage: (_ctx, message) => ({+ auth: defaultDiscordMessageAuth(message),+ context: [`addressed: ${message.addressed}`],+ conversation: `user:${message.author.id}`,+ startThread: false,+ }),+ },+ });++ const { send } = await fireGateway(+ channel,+ messageCreate({ content: "anyone around?", mentions: [] }),+ );++ expect(discordFetch).not.toHaveBeenCalled();+ expect(send.mock.calls[0]![0]).toBe("C01:user:U01");+ expect(send.mock.calls[0]![1]).toMatchObject({+ context: [expect.stringContaining("<discord_context>"), "addressed: false"],+ message: "anyone around?",+ });+ });++ it("rejects dispatches over 1 MB", async () => {+ const { channel } = gatewayChannel();++ const { response, send } = await fireGateway(+ channel,+ messageCreate({ content: "x".repeat(1024 * 1024) }),+ );++ expect(response.status).toBe(413);+ expect(send).not.toHaveBeenCalled();+ });++ it("aliases every reply in a Gateway session without re-keying it", async () => {+ let nextId = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => Response.json({ channel_id: "C01", id: `B0${++nextId}` })),+ );+ const adapter = withState(+ getAdapter(discordChannel({ credentials: { applicationId: "APP1", botToken: "bot-token" } })),+ {+ applicationId: "APP1",+ channelId: "C01",+ conversationId: "M01",+ guildId: "G01",+ hasMessageAnchor: true,+ initialResponseSent: true,+ interactionToken: null,+ },+ );+ const { accessor, writes } = captureAccessor("discord:C01:M01");++ await callEvent(+ adapter,+ makeEvent("message.completed", {+ finishReason: "stop",+ message: `${"a".repeat(1990)}\n${"b".repeat(100)}`,+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ buildAdapterContext(adapter, accessor),+ );++ expect((adapter.state as { conversationId: string }).conversationId).toBe("M01");+ expect(writes.filter(([key]) => key === "eve.continuationToken")).toEqual([+ ["eve.continuationToken", "discord:C01:B01"],+ ["eve.continuationToken", "discord:C01:B02"],+ ]);+ });++ it("accepts only this project's runtime in the same environment by default", async () => {+ vi.stubEnv("VERCEL_ENV", "production");+ vi.stubEnv("VERCEL_PROJECT_ID", "prj_bot");+ vi.stubEnv("VERCEL_TARGET_ENV", "production");+ const issuer = await installMockedVercelIssuer("discord-gateway-route");+ const tokenFrom = (environment: string) =>+ issuer.signToken({+ environment,+ project_id: "prj_bot",+ sub: `owner:acme:project:bot:environment:${environment}`,+ });+ const channel = discordChannel({+ credentials: { applicationId: "APP1", botToken: "bot-token" },+ gateway: {},+ });+ const dm = messageCreate({ guild_id: undefined });++ try {+ const unauthenticated = await fireGateway(channel, dm);+ const preview = await fireGateway(channel, dm, { bearer: await tokenFrom("preview") });+ const production = await fireGateway(channel, dm, { bearer: await tokenFrom("production") });++ expect(unauthenticated.response.status).toBe(401);+ expect(preview.response.status).toBe(401);+ expect(preview.send).not.toHaveBeenCalled();+ expect(production.response.status).toBe(202);+ } finally {+ issuer.restore();+ }+ });+});+describe("defaultDiscordAuth", () => {+ it("gives a person the same principal for messages and interactions", () => {+ const user = { id: "U01", isBot: false, username: "ada" };+ const fromInteraction = defaultDiscordAuth({+ applicationId: "APP1",+ channelId: "C01",+ guildId: "G01",+ id: "I01",+ raw: {},+ token: "tok",+ user,+ });+ const fromMessage = defaultDiscordMessageAuth({+ addressed: true,+ attachments: [],+ author: user,+ channelId: "C02",+ content: "hi",+ guildId: "G01",+ id: "M01",+ raw: {},+ });++ for (const field of ["authenticator", "issuer", "principalId", "principalType"] as const) {+ expect(fromMessage[field]).toBe(fromInteraction[field]);+ }+ });+it("derives guild-scoped user auth", () => {const auth = defaultDiscordAuth({applicationId: "APP1",diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex 19875d2a4..063641e86 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -56,6 +56,10 @@ import {discordJsonBody,readMessageContent,} from "#public/channels/discord/responses.js";+import {+ createDiscordGatewayRoute,+ type DiscordGatewayConfig,+} from "#public/channels/discord/messages.js";import { type DiscordWebhookVerifier } from "#public/channels/discord/verify.js";import { verifyDiscordInbound } from "#public/channels/discord/verifyInbound.js";import { readNonEmptyString } from "#shared/guards.js";@@ -219,6 +223,13 @@ export interface DiscordChannelConfig {interaction: DiscordInputResponseInteraction,): DiscordInputResponseResult | Promise<DiscordInputResponseResult>;+ /**+ * Accepts ordinary messages (DMs, mentions, and thread follow-ups) that a+ * relay forwards from the Discord Gateway, such as `experimental_runDiscordGatewayRelay`+ * from `eve/channels/discord/gateway`. Mounts `POST /eve/v1/discord/gateway`.+ */+ readonly gateway?: DiscordGatewayConfig;+readonly events?: DiscordChannelEvents;}@@ -267,7 +278,10 @@ export interface DiscordChannel extends Channel<DiscordReceiveTarget,DiscordInstrumentationMetadata> {}-/** Discord channel factory for HTTP Interactions and proactive channel messages. */+/**+ * Discord channel factory for HTTP Interactions, proactive channel messages,+ * and, with `gateway`, ordinary messages forwarded from the Discord Gateway.+ */export function discordChannel(config: DiscordChannelConfig = {}): DiscordChannel {const onCommand = config.onCommand ?? defaultOnCommand;const onInputResponse =@@ -326,6 +340,15 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanne});},),+ ...(config.gateway === undefined+ ? []+ : [+ createDiscordGatewayRoute({+ buildContext: (state) => ({ discord: buildDiscordHandle({ config, state }) }),+ config,+ gateway: config.gateway,+ }),+ ]),],async receive(input, { from }) {@@ -396,13 +419,12 @@ function buildDiscordHandle(input: {const credentials = mergeCredentials(input.config.credentials, state);/**- * The first posted message anchors the conversation. A press finds its- * session by the id of the message it is on, so every later message with- * components, such as a second pending question, is aliased too.+ * The first posted message anchors the conversation. Every posted message+ * is aliased too: a press finds its session by the id of the message it is+ * on, and a Gateway reply by the id of the message it replies to.*/- function anchor(posted: DiscordPostedMessage, body: DiscordMessageBody): void {+ function anchor(posted: DiscordPostedMessage): void {if (!posted.id) return;- if (state.hasMessageAnchor && body.components === undefined) return;if (!state.hasMessageAnchor) {state.conversationId = posted.id;state.hasMessageAnchor = true;@@ -425,7 +447,7 @@ function buildDiscordHandle(input: {fetch: api?.fetch,channelId,});- anchor(posted, body);+ anchor(posted);return posted;}@@ -443,7 +465,7 @@ function buildDiscordHandle(input: {interactionToken,});state.initialResponseSent = true;- anchor(posted, body);+ anchor(posted);return posted;}@@ -460,7 +482,7 @@ function buildDiscordHandle(input: {fetch: api?.fetch,interactionToken,});- anchor(posted, body);+ anchor(posted);return posted;}diff --git a/packages/eve/src/public/channels/discord/gateway/connection.ts b/packages/eve/src/public/channels/discord/gateway/connection.tsnew file mode 100644index 000000000..6d7634a08--- /dev/null+++ b/packages/eve/src/public/channels/discord/gateway/connection.ts@@ -0,0 +1,265 @@+import { createLogger } from "#internal/logging.js";+import { callDiscordApi, type DiscordFetch } from "#public/channels/discord/api.js";+import { isNonEmptyString, isObject } from "#shared/guards.js";++const log = createLogger("discord.gateway");++const MAX_RECONNECT_DELAY_MS = 60_000;+// Discord ends the session on 1000 and 1001; any 4xxx close we send keeps it resumable.+const RESUMABLE_CLOSE = 4000;+// Bad token, bad shard, sharding required, bad API version, bad or disallowed intents.+const FATAL_CLOSE_CODES = new Set([4004, 4010, 4011, 4012, 4013, 4014]);+// A dead peer never answers a close frame, so the socket would sit in CLOSING.+const CLOSE_HANDSHAKE_TIMEOUT_MS = 3_000;+// Invalid sequence and session timed out: reconnect, but identify from scratch.+const SESSION_RESET_CLOSE_CODES = new Set([4007, 4009]);++/** Raised when Discord refuses the bot outright, so reconnecting cannot help. */+export class DiscordGatewayFatalError extends Error {}++/** A Gateway dispatch (op 0) as Discord sends it. */+export interface DiscordGatewayDispatch {+ readonly op: 0;+ readonly t: string;+ readonly s: number;+ readonly d: unknown;+}++export interface GatewayConnectionOptions {+ readonly apiBaseUrl?: string;+ readonly fetch?: DiscordFetch;+ readonly intents: number;+ readonly resolveToken: () => Promise<string>;+ readonly onDispatch: (dispatch: DiscordGatewayDispatch) => void;+ readonly signal: AbortSignal;+}++interface GatewayPayload {+ readonly op: number;+ readonly d: unknown;+ readonly s?: number | null;+ readonly t?: string | null;+}++interface GatewaySession {+ readonly id: string;+ readonly resumeUrl: string;+}++type GatewayUrlResult = { readonly url: string } | { readonly fatal: string };++/**+ * Holds one Discord Gateway session until `signal` aborts, resuming across+ * reconnects so dispatches are not lost while the process lives.+ */+export async function runGatewayConnection(options: GatewayConnectionOptions): Promise<void> {+ let session: GatewaySession | undefined;+ let sequence: number | null = null;+ let failures = 0;+ let nextDelayMs: number | undefined;++ while (!options.signal.aborted) {+ let token: string;+ let url: string;+ try {+ token = await options.resolveToken();+ if (session !== undefined) {+ url = session.resumeUrl;+ } else {+ const result = await discoverGatewayUrl(token);+ if ("fatal" in result) throw new DiscordGatewayFatalError(result.fatal);+ url = result.url;+ }+ } catch (error) {+ if (error instanceof DiscordGatewayFatalError) throw error;+ log.warn("Discord Gateway connect failed", { error });+ await sleep(backoff(failures++), options.signal);+ continue;+ }++ if (options.signal.aborted) return;+ const closed = await connect(url, token);+ if (options.signal.aborted) return;++ if (FATAL_CLOSE_CODES.has(closed.code)) {+ throw new DiscordGatewayFatalError(+ `Discord closed the Gateway with ${closed.code} (${closed.reason}). Check the bot ` ++ "token and that every requested intent is enabled under Bot in the Discord Developer Portal.",+ );+ }+ if (SESSION_RESET_CLOSE_CODES.has(closed.code)) {+ session = undefined;+ sequence = null;+ }++ const delayMs = nextDelayMs ?? backoff(failures++);+ nextDelayMs = undefined;+ log.warn("Discord Gateway closed", {+ code: closed.code,+ reason: closed.reason,+ retryInMs: Math.round(delayMs),+ });+ await sleep(delayMs, options.signal);+ }++ async function discoverGatewayUrl(token: string): Promise<GatewayUrlResult> {+ const response = await callDiscordApi({+ apiBaseUrl: options.apiBaseUrl,+ botToken: token,+ fetch: options.fetch,+ method: "GET",+ path: "/gateway/bot",+ });+ if (response.status === 401) {+ return { fatal: "Discord rejected the bot token while looking up the Gateway URL." };+ }+ if (!response.ok || !isObject(response.body) || !isNonEmptyString(response.body.url)) {+ throw new Error(`Discord Gateway URL lookup failed with HTTP ${response.status}.`);+ }+ return { url: response.body.url };+ }++ function connect(baseUrl: string, token: string): Promise<{ code: number; reason: string }> {+ return new Promise((resolve) => {+ const url = new URL(baseUrl);+ url.searchParams.set("v", "10");+ url.searchParams.set("encoding", "json");++ const socket = new WebSocket(url);+ let heartbeatTimer: NodeJS.Timeout | undefined;+ let closeTimer: NodeJS.Timeout | undefined;+ let heartbeatAcked = true;+ let settled = false;++ const settle = (code: number, reason: string) => {+ if (settled) return;+ settled = true;+ clearTimeout(heartbeatTimer);+ clearTimeout(closeTimer);+ options.signal.removeEventListener("abort", onAbort);+ resolve({ code, reason });+ };++ const send = (payload: { op: number; d: unknown }) => {+ if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(payload));+ };+ const close = (code: number, reason: string) => {+ if (socket.readyState === WebSocket.CLOSING || socket.readyState === WebSocket.CLOSED) {+ return;+ }+ socket.close(code, reason);+ closeTimer = setTimeout(() => settle(code, reason), CLOSE_HANDSHAKE_TIMEOUT_MS);+ };+ const onAbort = () => close(1000, "shutdown");+ options.signal.addEventListener("abort", onAbort, { once: true });++ const heartbeat = (intervalMs: number) => {+ if (!heartbeatAcked) {+ close(RESUMABLE_CLOSE, "heartbeat not acknowledged");+ return;+ }+ heartbeatAcked = false;+ send({ op: 1, d: sequence });+ heartbeatTimer = setTimeout(() => heartbeat(intervalMs), intervalMs);+ };++ const identifyOrResume = () => {+ if (session !== undefined && sequence !== null) {+ send({ op: 6, d: { seq: sequence, session_id: session.id, token } });+ return;+ }+ send({+ op: 2,+ d: {+ intents: options.intents,+ properties: { browser: "eve", device: "eve", os: process.platform },+ token,+ },+ });+ };++ socket.addEventListener("message", (event) => {+ if (settled) return;+ let payload: GatewayPayload;+ try {+ payload = JSON.parse(String(event.data)) as GatewayPayload;+ } catch {+ log.warn("Discord Gateway sent a payload that is not JSON");+ return;+ }+ if (typeof payload.s === "number") sequence = payload.s;++ switch (payload.op) {+ case 0:+ onDispatch(payload);+ return;+ case 1:+ send({ op: 1, d: sequence });+ return;+ case 7:+ nextDelayMs = 0;+ close(RESUMABLE_CLOSE, "reconnect requested");+ return;+ case 9:+ if (payload.d !== true) {+ session = undefined;+ sequence = null;+ }+ nextDelayMs = 1_000 + Math.random() * 4_000;+ close(RESUMABLE_CLOSE, "invalid session");+ return;+ case 10: {+ const intervalMs = Number(+ isObject(payload.d) ? payload.d.heartbeat_interval : undefined,+ );+ heartbeatTimer = setTimeout(() => heartbeat(intervalMs), intervalMs * Math.random());+ identifyOrResume();+ return;+ }+ case 11:+ heartbeatAcked = true;+ return;+ }+ });++ socket.addEventListener("close", (event) => settle(event.code, event.reason));+ });+ }++ function onDispatch(payload: GatewayPayload): void {+ if (payload.t === "READY") {+ const ready = isObject(payload.d) ? payload.d : {};+ if (isNonEmptyString(ready.session_id) && isNonEmptyString(ready.resume_gateway_url)) {+ session = { id: ready.session_id, resumeUrl: ready.resume_gateway_url };+ }+ failures = 0;+ log.info("Discord Gateway ready", { sessionId: session?.id });+ return;+ }+ if (payload.t === "RESUMED") {+ failures = 0;+ log.info("Discord Gateway resumed", { sequence });+ return;+ }+ if (typeof payload.t === "string" && typeof payload.s === "number") {+ options.onDispatch({ d: payload.d, op: 0, s: payload.s, t: payload.t });+ }+ }+}++function backoff(failures: number): number {+ return Math.min(MAX_RECONNECT_DELAY_MS, 1_000 * 2 ** failures) * (0.5 + Math.random() / 2);+}++/** Resolves after `ms`, or as soon as `signal` aborts. */+export function sleep(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve) => {+ const timer = setTimeout(done, ms);+ signal?.addEventListener("abort", done, { once: true });+ function done() {+ clearTimeout(timer);+ signal?.removeEventListener("abort", done);+ resolve();+ }+ });+}diff --git a/packages/eve/src/public/channels/discord/gateway/forwarder.ts b/packages/eve/src/public/channels/discord/gateway/forwarder.tsnew file mode 100644index 000000000..b29ac1852--- /dev/null+++ b/packages/eve/src/public/channels/discord/gateway/forwarder.ts@@ -0,0 +1,128 @@+import { createLogger } from "#internal/logging.js";+import type { DiscordGatewayDispatch } from "#public/channels/discord/gateway/connection.js";+import { sleep } from "#public/channels/discord/gateway/connection.js";++const log = createLogger("discord.gateway");++const MAX_PENDING = 500;+const MAX_ATTEMPTS = 5;+// Generous so a cold start answers before the relay gives up; a timed-out request is not retried.+const REQUEST_TIMEOUT_MS = 30_000;+// Only a rate limit proves eve turned the request away; a 5xx can come after a turn started.+const RATE_LIMITED = 429;+// Failures that happen before the request reaches eve, so retrying cannot start a second turn.+const UNSENT_ERROR_CODES = new Set([+ "ECONNREFUSED",+ "ENOTFOUND",+ "EAI_AGAIN",+ "UND_ERR_CONNECT_TIMEOUT",+]);++export interface Forwarder {+ enqueue(dispatch: DiscordGatewayDispatch): void;+ /** Resolves once the backlog is delivered or `timeoutMs` elapses. */+ drain(timeoutMs: number): Promise<void>;+}++/**+ * Delivers dispatches to eve one at a time, in Gateway order. A bounded+ * backlog keeps a long eve outage from growing the relay's memory without limit.+ */+export function createForwarder(options: {+ readonly url: URL;+ readonly headers: () => Promise<Readonly<Record<string, string>>>;+}): Forwarder {+ let tail = Promise.resolve();+ let pending = 0;++ return {+ enqueue(dispatch) {+ if (pending >= MAX_PENDING) {+ log.error("Discord Gateway backlog is full; dropped a dispatch", {+ event: dispatch.t,+ sequence: dispatch.s,+ });+ return;+ }+ pending += 1;+ tail = tail+ .then(() => deliver(dispatch))+ .finally(() => {+ pending -= 1;+ });+ },+ async drain(timeoutMs) {+ if (pending > 0) {+ const timeout = new AbortController();+ await Promise.race([tail, sleep(timeoutMs, timeout.signal)]);+ timeout.abort();+ }+ if (pending > 0)+ log.warn("Discord Gateway relay stopped with undelivered dispatches", { pending });+ },+ };++ async function deliver(dispatch: DiscordGatewayDispatch): Promise<void> {+ const body = JSON.stringify(dispatch);+ const fields = { event: dispatch.t, sequence: dispatch.s };++ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {+ try {+ const response = await fetch(options.url, {+ body,+ headers: { "content-type": "application/json", ...(await options.headers()) },+ method: "POST",+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ if (response.ok) return;++ const detail = (await response.text()).slice(0, 200);+ if (response.status >= 500) {+ // A gateway timeout or crash after dispatch would answer the message twice on retry.+ log.error("Gave up forwarding a Discord dispatch that eve may have received", {+ ...fields,+ detail,+ status: response.status,+ });+ return;+ }+ if (response.status !== RATE_LIMITED) {+ log.error("eve rejected a forwarded Discord dispatch", {+ ...fields,+ detail,+ hint:+ response.status === 401 || response.status === 403+ ? "eve did not accept the relay's credentials. On Vercel, check that the relay runs in the same project as the agent."+ : `Check that ${options.url.href} is the agent's discordChannel({ gateway }) route.`,+ status: response.status,+ });+ return;+ }+ log.warn("Retrying a forwarded Discord dispatch", {+ ...fields,+ attempt,+ detail,+ status: response.status,+ });+ } catch (error) {+ if (!UNSENT_ERROR_CODES.has(errorCode(error))) {+ // eve may have started the turn already; a retry could answer twice.+ log.error("Gave up forwarding a Discord dispatch that eve may have received", {+ ...fields,+ error,+ });+ return;+ }+ log.warn("Retrying a forwarded Discord dispatch", { ...fields, attempt, error });+ }+ if (attempt < MAX_ATTEMPTS) await sleep(Math.min(30_000, 1_000 * 2 ** (attempt - 1)));+ }+ log.error("Gave up forwarding a Discord dispatch", { ...fields, attempts: MAX_ATTEMPTS });+ }+}++function errorCode(error: unknown): string {+ const cause = error instanceof Error ? error.cause : undefined;+ const code = (cause as { code?: unknown } | undefined)?.code;+ return typeof code === "string" ? code : "";+}diff --git a/packages/eve/src/public/channels/discord/gateway/index.ts b/packages/eve/src/public/channels/discord/gateway/index.tsnew file mode 100644index 000000000..de8cdabb8--- /dev/null+++ b/packages/eve/src/public/channels/discord/gateway/index.ts@@ -0,0 +1,154 @@+/**+ * A long-running relay that holds a Discord Gateway connection and forwards+ * message dispatches to an eve agent's `discordChannel({ gateway })` route.+ * Run it in a process that stays up, such as a Vercel Daemon; it does not+ * belong in the agent itself.+ */++import { createLogger } from "#internal/logging.js";+import { type OutboundAuthFn, vercelOidc } from "#public/agents/auth.js";+import {+ resolveDiscordBotToken,+ type DiscordApiOptions,+ type DiscordBotToken,+} from "#public/channels/discord/api.js";+import {+ DiscordGatewayFatalError,+ runGatewayConnection,+} from "#public/channels/discord/gateway/connection.js";+import { createForwarder } from "#public/channels/discord/gateway/forwarder.js";++export { DiscordGatewayFatalError };++const log = createLogger("discord.gateway");++const GUILD_MESSAGES_INTENT = 1 << 9;+const DIRECT_MESSAGES_INTENT = 1 << 12;+const MESSAGE_CONTENT_INTENT = 1 << 15;++// Vercel Daemons get 10 seconds between SIGTERM and SIGKILL by default.+const SHUTDOWN_DRAIN_MS = 8_000;++/** Options for {@link experimental_runDiscordGatewayRelay}. */+export interface DiscordGatewayRelayOptions {+ /**+ * Bot credentials. Pass the same object as the agent's `discordChannel`,+ * such as `connectDiscordCredentials(...)`. `botToken` falls back to+ * `DISCORD_BOT_TOKEN`.+ */+ readonly credentials?: { readonly botToken?: DiscordBotToken };+ /** Discord REST API overrides. */+ readonly api?: Omit<DiscordApiOptions, "credentials">;+ /**+ * Base URL of the eve deployment. Defaults to+ * `https://$VERCEL_PROJECT_PRODUCTION_URL`, which a Vercel Daemon has. Set it+ * to `http://localhost:<port>` to relay to `eve dev`.+ */+ readonly url?: string | URL;+ /** Path of the agent's Gateway route. Defaults to `/eve/v1/discord/gateway`. */+ readonly route?: string;+ /**+ * Headers that authenticate each forwarded dispatch. Defaults to this+ * project's Vercel OIDC token, which the route accepts by default. Without a+ * token, as on a laptop, requests go out unauthenticated, which `eve dev`+ * accepts.+ */+ readonly auth?: OutboundAuthFn;+ /**+ * Also request the privileged Message Content intent, so messages that do+ * not mention the bot, such as thread follow-ups, arrive with their text.+ * Enable it under Bot in the Discord Developer Portal first, or Discord+ * refuses the connection.+ */+ readonly messageContent?: boolean;+ /** Stops the relay. Defaults to the process's `SIGTERM` and `SIGINT`. */+ readonly signal?: AbortSignal;+}++/**+ * Connects to the Discord Gateway as the bot and forwards every+ * `MESSAGE_CREATE` dispatch, unchanged and in order, to the agent's+ * `discordChannel({ gateway })` route. Reconnects and resumes on its own.+ * Resolves after `signal` aborts and in-flight deliveries drain; rejects with+ * {@link DiscordGatewayFatalError} when Discord refuses the bot's token or+ * intents.+ *+ * Run exactly one relay per bot: Discord sends every message to each+ * connection, so a second relay makes the agent answer twice.+ */+export async function experimental_runDiscordGatewayRelay(+ options: DiscordGatewayRelayOptions = {},+): Promise<void> {+ const target = new URL(options.route ?? "/eve/v1/discord/gateway", resolveBaseUrl(options.url));+ const shutdown = options.signal === undefined ? listenForShutdown() : undefined;+ const signal = options.signal ?? shutdown!.signal;+ const forwarder = createForwarder({+ headers: outboundHeaders(options.auth),+ url: target,+ });++ log.info("Discord Gateway relay started", { target: target.href });+ try {+ await runGatewayConnection({+ apiBaseUrl: options.api?.apiBaseUrl,+ fetch: options.api?.fetch,+ intents:+ GUILD_MESSAGES_INTENT |+ DIRECT_MESSAGES_INTENT |+ (options.messageContent === true ? MESSAGE_CONTENT_INTENT : 0),+ onDispatch: (dispatch) => {+ if (dispatch.t === "MESSAGE_CREATE") forwarder.enqueue(dispatch);+ },+ resolveToken: () => resolveDiscordBotToken(options.credentials?.botToken),+ signal,+ });+ } finally {+ shutdown?.dispose();+ await forwarder.drain(SHUTDOWN_DRAIN_MS);+ }+}++function resolveBaseUrl(url: string | URL | undefined): URL {+ if (url !== undefined) return new URL(url);+ const production = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim();+ if (production) return new URL(`https://${production}`);+ throw new Error(+ "experimental_runDiscordGatewayRelay needs the eve deployment's URL: pass `url`, such as " ++ "http://localhost:2000 for eve dev, or run it where VERCEL_PROJECT_PRODUCTION_URL is set.",+ );+}++function outboundHeaders(+ auth: OutboundAuthFn | undefined,+): () => Promise<Readonly<Record<string, string>>> {+ if (auth !== undefined) return async () => (await auth()).headers;+ const oidc = vercelOidc();+ let warned = false;+ return async () => {+ try {+ return (await oidc()).headers;+ } catch (error) {+ if (!warned) {+ warned = true;+ log.warn("No Vercel OIDC token; forwarding without credentials", { error });+ }+ return {};+ }+ };+}++function listenForShutdown(): { readonly signal: AbortSignal; dispose(): void } {+ const controller = new AbortController();+ const signals = ["SIGTERM", "SIGINT"] as const;+ const onSignal = (name: NodeJS.Signals) => {+ log.info("Discord Gateway relay shutting down", { signal: name });+ controller.abort();+ };+ for (const name of signals) process.once(name, onSignal);+ return {+ signal: controller.signal,+ dispose: () => {+ for (const name of signals) process.off(name, onSignal);+ },+ };+}diff --git a/packages/eve/src/public/channels/discord/gateway/relay.scenario.test.ts b/packages/eve/src/public/channels/discord/gateway/relay.scenario.test.tsnew file mode 100644index 000000000..b0ea0ef3a--- /dev/null+++ b/packages/eve/src/public/channels/discord/gateway/relay.scenario.test.ts@@ -0,0 +1,301 @@+import { createHash } from "node:crypto";+import { createServer, type IncomingMessage, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import type { Duplex } from "node:stream";++import { afterEach, describe, expect, it } from "vitest";++import {+ DiscordGatewayFatalError,+ experimental_runDiscordGatewayRelay,+} from "#public/channels/discord/gateway/index.js";++const WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";++interface GatewayConnection {+ readonly path: string;+ readonly received: Record<string, any>[];+ send(payload: unknown): void;+ close(code: number): void;+ /** Stops answering, like a peer whose TCP connection silently died. */+ goSilent(): void;+}++/**+ * Fake Discord, plus the eve route the relay forwards to, on one port. The+ * WebSocket side speaks just enough RFC 6455 for the relay's text frames.+ */+async function startFakeDiscord(+ onConnection: (connection: GatewayConnection) => void,+ /** eve's answers to successive forwarded dispatches; 202 once they run out. */+ eveStatuses: number[] = [],+): Promise<{+ readonly url: string;+ readonly forwarded: { readonly body: unknown; readonly authorization?: string }[];+}> {+ const forwarded: { body: unknown; authorization?: string }[] = [];+ const server = createServer((req, res) => {+ if (req.method === "GET" && req.url === "/api/v10/gateway/bot") {+ res.setHeader("content-type", "application/json");+ res.end(JSON.stringify({ url: `ws://127.0.0.1:${port(server)}/gateway` }));+ return;+ }+ if (req.method === "POST" && req.url === "/eve/v1/discord/gateway") {+ let body = "";+ req.on("data", (chunk) => (body += chunk));+ req.on("end", () => {+ forwarded.push({ authorization: req.headers.authorization, body: JSON.parse(body) });+ res.statusCode = eveStatuses.shift() ?? 202;+ res.end("{}");+ });+ return;+ }+ res.statusCode = 404;+ res.end();+ });+ server.on("upgrade", (req, socket) => onConnection(acceptWebSocket(req, socket)));+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ servers.push(server);+ return { forwarded, url: `http://127.0.0.1:${port(server)}` };+}++function acceptWebSocket(req: IncomingMessage, socket: Duplex): GatewayConnection {+ const accept = createHash("sha1")+ .update(`${req.headers["sec-websocket-key"]}${WEBSOCKET_GUID}`)+ .digest("base64");+ socket.write(+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" ++ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`,+ );++ const received: Record<string, any>[] = [];+ let silent = false;+ let buffer = Buffer.alloc(0);+ socket.on("data", (chunk: Buffer) => {+ buffer = Buffer.concat([buffer, chunk]);+ for (let frame = readFrame(buffer); frame; frame = readFrame(buffer)) {+ buffer = buffer.subarray(frame.length);+ if (frame.opcode === 1) {+ const payload = JSON.parse(frame.payload.toString("utf8"));+ received.push(payload);+ if (payload.op === 1 && !silent) socket.write(encodeFrame(1, Buffer.from('{"op":11}')));+ }+ if (frame.opcode === 8 && !silent) {+ socket.end(encodeFrame(8, frame.payload));+ }+ }+ });+ socket.on("error", () => {});+ sockets.push(socket);++ return {+ path: req.url ?? "",+ received,+ send: (payload) => socket.write(encodeFrame(1, Buffer.from(JSON.stringify(payload)))),+ goSilent: () => {+ silent = true;+ },+ close: (code) => {+ const payload = Buffer.alloc(2);+ payload.writeUInt16BE(code);+ socket.write(encodeFrame(8, payload));+ },+ };+}++function readFrame(+ buffer: Buffer,+): { opcode: number; payload: Buffer; length: number } | undefined {+ if (buffer.length < 2) return undefined;+ let length = buffer[1]! & 0x7f;+ let offset = 2;+ if (length === 126) {+ if (buffer.length < 4) return undefined;+ length = buffer.readUInt16BE(2);+ offset = 4;+ }+ const masked = (buffer[1]! & 0x80) !== 0;+ const mask = masked ? buffer.subarray(offset, offset + 4) : undefined;+ offset += masked ? 4 : 0;+ if (buffer.length < offset + length) return undefined;+ const payload = Buffer.from(buffer.subarray(offset, offset + length));+ if (mask) for (let i = 0; i < payload.length; i += 1) payload[i]! ^= mask[i % 4]!;+ return { length: offset + length, opcode: buffer[0]! & 0x0f, payload };+}++function encodeFrame(opcode: number, payload: Buffer): Buffer {+ const header =+ payload.length < 126+ ? Buffer.from([0x80 | opcode, payload.length])+ : Buffer.from([0x80 | opcode, 126, payload.length >> 8, payload.length & 0xff]);+ return Buffer.concat([header, payload]);+}++function port(server: Server): number {+ return (server.address() as AddressInfo).port;+}++async function waitFor(condition: () => boolean): Promise<void> {+ const deadline = Date.now() + 10_000;+ while (!condition()) {+ if (Date.now() > deadline) throw new Error("Timed out waiting for the relay.");+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+}++const servers: Server[] = [];+const sockets: Duplex[] = [];++afterEach(async () => {+ // Upgraded sockets leave the HTTP server's bookkeeping, and a silent one never closes.+ for (const socket of sockets.splice(0)) socket.destroy();+ await Promise.all(+ servers.splice(0).map(+ (server) =>+ new Promise((resolve) => {+ server.closeAllConnections();+ server.close(resolve);+ }),+ ),+ );+});++const HELLO = { d: { heartbeat_interval: 45_000 }, op: 10 };++function messageCreate(s: number, id: string) {+ return { d: { id }, op: 0, s, t: "MESSAGE_CREATE" };+}++describe("experimental_runDiscordGatewayRelay", () => {+ it("forwards message dispatches unchanged and in order, resuming across a reconnect", async () => {+ const connections: GatewayConnection[] = [];+ const discord = await startFakeDiscord((connection) => {+ connections.push(connection);+ connection.send(HELLO);+ });+ const shutdown = new AbortController();++ const relay = experimental_runDiscordGatewayRelay({+ api: { apiBaseUrl: `${discord.url}/api/v10` },+ auth: async () => ({ headers: { authorization: "Bearer relay" } }),+ credentials: { botToken: "bot-token" },+ signal: shutdown.signal,+ url: discord.url,+ });++ await waitFor(() => connections[0]?.received.length === 1);+ const [first] = connections;+ expect(first!.received[0]).toMatchObject({+ d: { intents: (1 << 9) | (1 << 12), token: "bot-token" },+ op: 2,+ });+ first!.send({+ d: { resume_gateway_url: `${discord.url.replace("http", "ws")}/resume`, session_id: "S1" },+ op: 0,+ s: 1,+ t: "READY",+ });+ first!.send(messageCreate(2, "M1"));+ first!.send({ d: {}, op: 0, s: 3, t: "TYPING_START" });+ first!.send(messageCreate(4, "M2"));+ first!.send({ d: null, op: 7 });++ await waitFor(() => connections[1]?.received.length === 1);+ const [, second] = connections;+ expect(second!.path).toMatch(/^\/resume\?/);+ expect(second!.received[0]).toEqual({+ d: { seq: 4, session_id: "S1", token: "bot-token" },+ op: 6,+ });+ second!.send({ d: null, op: 0, s: 5, t: "RESUMED" });+ second!.send(messageCreate(6, "M3"));++ await waitFor(() => discord.forwarded.length === 3);+ shutdown.abort();+ await relay;++ expect(discord.forwarded).toEqual([+ { authorization: "Bearer relay", body: messageCreate(2, "M1") },+ { authorization: "Bearer relay", body: messageCreate(4, "M2") },+ { authorization: "Bearer relay", body: messageCreate(6, "M3") },+ ]);+ });++ it("abandons a connection that stops acknowledging heartbeats and resumes elsewhere", async () => {+ const connections: GatewayConnection[] = [];+ const discord = await startFakeDiscord((connection) => {+ connections.push(connection);+ connection.send({ d: { heartbeat_interval: 50 }, op: 10 });+ });+ const shutdown = new AbortController();+ const relay = experimental_runDiscordGatewayRelay({+ api: { apiBaseUrl: `${discord.url}/api/v10` },+ credentials: { botToken: "bot-token" },+ signal: shutdown.signal,+ url: discord.url,+ });++ await waitFor(() => connections[0]?.received.some((payload) => payload.op === 2) === true);+ connections[0]!.send({+ d: { resume_gateway_url: `${discord.url.replace("http", "ws")}/resume`, session_id: "S1" },+ op: 0,+ s: 1,+ t: "READY",+ });+ connections[0]!.goSilent();++ await waitFor(() => connections[1]?.received.some((payload) => payload.op === 6) === true);+ shutdown.abort();+ await relay;++ expect(connections[1]!.path).toMatch(/^\/resume\?/);+ });++ it("retries a rate limit but never a 5xx, which can come after eve started the turn", async () => {+ let gateway: GatewayConnection | undefined;+ const discord = await startFakeDiscord(+ (connection) => {+ gateway = connection;+ connection.send(HELLO);+ },+ [429, 502],+ );+ const shutdown = new AbortController();+ const relay = experimental_runDiscordGatewayRelay({+ api: { apiBaseUrl: `${discord.url}/api/v10` },+ credentials: { botToken: "bot-token" },+ signal: shutdown.signal,+ url: discord.url,+ });++ await waitFor(() => gateway?.received.length === 1);+ gateway!.send(messageCreate(1, "M1"));+ await waitFor(() => discord.forwarded.length === 2);+ shutdown.abort();+ // Shutdown drains the backlog, so a retry of the 502 would land before this resolves.+ await relay;++ expect(discord.forwarded.map(({ body }) => body)).toEqual([+ messageCreate(1, "M1"),+ messageCreate(1, "M1"),+ ]);+ });++ it("stops with an actionable error when Discord refuses the bot's intents", async () => {+ const discord = await startFakeDiscord((connection) => {+ connection.send(HELLO);+ void waitFor(() => connection.received.length === 1).then(() => connection.close(4014));+ });++ const relay = experimental_runDiscordGatewayRelay({+ api: { apiBaseUrl: `${discord.url}/api/v10` },+ credentials: { botToken: "bot-token" },+ messageContent: true,+ signal: new AbortController().signal,+ url: discord.url,+ });++ await expect(relay).rejects.toThrow(DiscordGatewayFatalError);+ await expect(relay).rejects.toThrow(/4014.*Discord Developer Portal/);+ });+});diff --git a/packages/eve/src/public/channels/discord/inbound.ts b/packages/eve/src/public/channels/discord/inbound.tsindex ce749a169..f1c1c203e 100644--- a/packages/eve/src/public/channels/discord/inbound.ts+++ b/packages/eve/src/public/channels/discord/inbound.ts@@ -126,15 +126,18 @@ const DISCORD_RESPONSE_INSTRUCTIONS =/*** Fields rendered into the model-visible `<discord_context>` block by- * {@link formatDiscordContextBlock}. The optional fields (username, guildId,- * commandName) are omitted from the block when not provided.+ * {@link formatDiscordContextBlock}. Optional fields are omitted from the+ * block when not provided.*/export interface DiscordInboundContext {readonly applicationId?: string;readonly channelId: string;readonly commandName?: string;readonly guildId?: string;- readonly interactionId: string;+ /** Set for interactions such as slash commands. */+ readonly interactionId?: string;+ /** Set for ordinary messages forwarded from the Discord Gateway. */+ readonly messageId?: string;readonly userId: string;readonly username?: string;}@@ -175,7 +178,8 @@ export function formatDiscordContextBlock(context: DiscordInboundContext): strin...(context.username ? [`username: ${context.username}`] : []),`channel_id: ${context.channelId}`,...(context.guildId ? [`guild_id: ${context.guildId}`] : []),- `interaction_id: ${context.interactionId}`,+ ...(context.interactionId ? [`interaction_id: ${context.interactionId}`] : []),+ ...(context.messageId ? [`message_id: ${context.messageId}`] : []),...(context.commandName ? [`command_name: ${context.commandName}`] : []),"</discord_context>",];@@ -260,7 +264,7 @@ function parseInteractionBase(raw: Record<string, unknown>): DiscordInteractionB}function parseInteractionUser(raw: Record<string, unknown>): DiscordUser | null {- const directUser = parseUser(raw.user);+ const directUser = parseDiscordUser(raw.user);if (directUser) return directUser;const member = parseMember(raw.member);return member?.user ?? null;@@ -268,7 +272,7 @@ function parseInteractionUser(raw: Record<string, unknown>): DiscordUser | nullfunction parseMember(value: unknown): DiscordMember | undefined {if (!isObject(value)) return undefined;- const user = parseUser(value.user);+ const user = parseDiscordUser(value.user);if (!user) return undefined;return {nick: isNonEmptyString(value.nick) ? value.nick : undefined,@@ -279,7 +283,8 @@ function parseMember(value: unknown): DiscordMember | undefined {};}-function parseUser(value: unknown): DiscordUser | null {+/** Parses a raw Discord user object, as interactions and Gateway messages carry it. */+export function parseDiscordUser(value: unknown): DiscordUser | null {if (!isObject(value) || !isNonEmptyString(value.id) || !isNonEmptyString(value.username)) {return null;}@@ -318,22 +323,30 @@ function resolveAttachments(isObject(resolved) && isObject(resolved.attachments) ? resolved.attachments : undefined;if (byId === undefined) return [];return attachmentOptionIds(options).flatMap((id) => {- const raw = byId[id];- if (!isObject(raw) || !isNonEmptyString(raw.url) || !isNonEmptyString(raw.filename)) {- return [];- }- return [- {- contentType: isNonEmptyString(raw.content_type) ? raw.content_type : undefined,- filename: raw.filename,- id,- size: typeof raw.size === "number" ? raw.size : undefined,- url: raw.url,- },- ];+ const attachment = parseDiscordAttachment({ ...(isObject(byId[id]) ? byId[id] : {}), id });+ return attachment ? [attachment] : [];});}+/** Parses a raw Discord attachment object, as Gateway messages and resolved command data carry it. */+export function parseDiscordAttachment(raw: unknown): DiscordAttachment | null {+ if (+ !isObject(raw) ||+ !isNonEmptyString(raw.id) ||+ !isNonEmptyString(raw.url) ||+ !isNonEmptyString(raw.filename)+ ) {+ return null;+ }+ return {+ contentType: isNonEmptyString(raw.content_type) ? raw.content_type : undefined,+ filename: raw.filename,+ id: raw.id,+ size: typeof raw.size === "number" ? raw.size : undefined,+ url: raw.url,+ };+}+function attachmentOptionIds(options: readonly DiscordCommandOption[]): string[] {return options.flatMap((option) => [...(option.type === ATTACHMENT_OPTION_TYPE && typeof option.value === "string"diff --git a/packages/eve/src/public/channels/discord/index.ts b/packages/eve/src/public/channels/discord/index.tsindex 7163ab491..de49b2009 100644--- a/packages/eve/src/public/channels/discord/index.ts+++ b/packages/eve/src/public/channels/discord/index.ts@@ -66,6 +66,7 @@ export {commandInteractionMessage,formatDiscordContextBlock,parseDiscordInteraction,+ type DiscordAttachment,type DiscordCommandInteraction,type DiscordCommandOption,type DiscordComponentInteraction,@@ -89,7 +90,19 @@ export {renderInputRequestComponents,} from "#public/channels/discord/hitl.js";-export { defaultDiscordAuth } from "#public/channels/discord/defaults.js";+export {+ defaultDiscordAuth,+ defaultDiscordMessageAuth,+} from "#public/channels/discord/defaults.js";++export type {+ DiscordGatewayConfig,+ DiscordGatewayMessage,+ DiscordMessageResult,+ DiscordMessageResultOrPromise,+ DiscordStartThreadOptions,+ DiscordThreadAutoArchiveMinutes,+} from "#public/channels/discord/messages.js";export {verifyDiscordRequest,diff --git a/packages/eve/src/public/channels/discord/messages.ts b/packages/eve/src/public/channels/discord/messages.tsnew file mode 100644index 000000000..5c69d6ee7--- /dev/null+++ b/packages/eve/src/public/channels/discord/messages.ts@@ -0,0 +1,448 @@+/**+ * Ordinary Discord messages, which Discord delivers only over its Gateway+ * WebSocket. A relay such as `experimental_runDiscordGatewayRelay` from+ * `eve/channels/discord/gateway` holds that connection and forwards each+ * dispatch, unchanged, to the route this module mounts.+ */++import type { SessionAuthContext } from "#channel/types.js";+import { EveAttachmentError } from "#internal/attachments/errors.js";+import { readLimitedBytes } from "#internal/attachments/limited-read.js";+import { createLogger, logError } from "#internal/logging.js";+import { type AuthFn, localDev, routeAuth, vercelOidc } from "#public/channels/auth.js";+import {+ callDiscordApi,+ discordContinuationToken,+ resolveDiscordApplicationId,+ resolveDiscordBotToken,+} from "#public/channels/discord/api.js";+import { discordCommandContent } from "#public/channels/discord/attachments.js";+import { discordAudience } from "#public/channels/discord/audience.js";+import { defaultOnMessage } from "#public/channels/discord/defaults.js";+import type {+ DiscordChannelConfig,+ DiscordChannelState,+ DiscordContext,+} from "#public/channels/discord/discordChannel.js";+import {+ formatDiscordContextBlock,+ parseDiscordAttachment,+ parseDiscordUser,+ type DiscordAttachment,+ type DiscordUser,+} from "#public/channels/discord/inbound.js";+import { POST, type HttpRouteDefinition } from "#channel/routes.js";+import { isNonEmptyString, isObject } from "#shared/guards.js";++const log = createLogger("discord.gateway");++/** Default path of the route that accepts forwarded Gateway dispatches. */+const DEFAULT_GATEWAY_ROUTE = "/eve/v1/discord/gateway";++/** Conversation key of a session that spans a whole channel: a DM or a thread. */+const WHOLE_CHANNEL_CONVERSATION = "channel";++// A MESSAGE_CREATE dispatch is a few kilobytes; the cap only bounds a misbehaving relay.+const MAX_DISPATCH_BYTES = 1024 * 1024;++// DEFAULT and REPLY. Other types are system notices such as joins and pins.+const CONVERSATIONAL_MESSAGE_TYPES = new Set([0, 19]);+const THREAD_CHANNEL_TYPES = new Set([10, 11, 12]);++/** An ordinary Discord message forwarded from the Gateway. */+export interface DiscordGatewayMessage {+ readonly id: string;+ readonly channelId: string;+ /** Absent for direct messages. */+ readonly guildId?: string;+ /**+ * Message text with the bot's own mention removed. Discord sends an empty+ * string for messages that neither mention the bot nor arrive as a DM unless+ * the bot has the Message Content intent.+ */+ readonly content: string;+ readonly author: DiscordUser;+ readonly attachments: readonly DiscordAttachment[];+ /** ID of the message this one replies to, if any. */+ readonly referencedMessageId?: string;+ /**+ * Whether the message is meant for the bot: a direct message, a mention, a+ * reply to one of the bot's messages, or a message in a thread where the bot+ * already has a conversation.+ */+ readonly addressed: boolean;+ /** Discord's raw message object. */+ readonly raw: Record<string, unknown>;+}++/** Minutes of inactivity before Discord archives a thread; the values Discord accepts. */+export type DiscordThreadAutoArchiveMinutes = 60 | 1440 | 4320 | 10080;++/** Options for starting a thread from a message; see {@link DiscordMessageResult.startThread}. */+export interface DiscordStartThreadOptions {+ /** Thread name. Defaults to the message's first line, then its first attachment's filename. */+ readonly name?: string;+ /** Defaults to the channel's own setting. */+ readonly autoArchiveMinutes?: DiscordThreadAutoArchiveMinutes;+}++/**+ * Result of the Gateway message hook. Return `null` to ignore the message.+ * - `auth`: session auth context for the dispatched turn, or `null` for anonymous.+ * - `context`: model-visible context lines appended after the Discord context block.+ * - `title`: workflow run title override that does not change model input.+ * - `conversation`: which session in the channel the message joins; see+ * {@link DiscordMessageResult.conversation}.+ * - `startThread`: answer in a new thread off the message; see+ * {@link DiscordMessageResult.startThread}.+ */+export type DiscordMessageResult = {+ readonly auth: SessionAuthContext | null;+ readonly context?: readonly string[];+ readonly title?: string;+ /**+ * Key of the session the message joins within its Discord channel. Messages+ * with the same key share a session. A message ID is the key of the+ * session that owns that message: the one it started, or the one whose bot+ * reply it is. `"channel"` is one session for the whole channel. Any other+ * string is your own grouping, such as `` `user:${message.author.id}` ``.+ *+ * Defaults to `"channel"` in DMs and threads, which includes the thread a+ * text-channel mention starts; elsewhere, to the replied-to message's session+ * when one owns it, or else a new session keyed by this message.+ */+ readonly conversation?: string;+ /**+ * Starts a thread from the message and moves the conversation into it, as+ * one session for the thread. Applies only when the message would start a+ * new session in a text channel: DMs, messages already in a thread, and+ * replies that continue a session are left as they are. eve adds the author+ * to the thread. When Discord refuses, for example because the bot lacks the+ * Create Public Threads permission, the message is handled as if+ * `startThread` were `false`. Defaults to `gateway.startThread`.+ */+ readonly startThread?: boolean | DiscordStartThreadOptions;+} | null;++/** Sync or async {@link DiscordMessageResult}. */+export type DiscordMessageResultOrPromise = DiscordMessageResult | Promise<DiscordMessageResult>;++/** Configuration for `discordChannel({ gateway })`. */+export interface DiscordGatewayConfig {+ /** Override the route that accepts forwarded dispatches (`/eve/v1/discord/gateway`). */+ readonly route?: string;+ /**+ * Authenticates the relay. The body names the message author, so whoever+ * passes can act as any Discord user. Defaults to `localDev()` plus Vercel+ * OIDC tokens from this project's own runtime in the same environment,+ * which is what `experimental_runDiscordGatewayRelay` sends from a Vercel Daemon.+ */+ readonly auth?: AuthFn<Request> | readonly AuthFn<Request>[];+ /**+ * Decides whether a message dispatches, under what `auth`, and which+ * session it joins. Called for every conversational message from a person;+ * bot authors never reach it. Defaults to dispatching addressed messages+ * with `defaultDiscordMessageAuth` and the default `conversation`.+ */+ onMessage?(ctx: DiscordContext, message: DiscordGatewayMessage): DiscordMessageResultOrPromise;+ /**+ * Default for each accepted message's `startThread`. Defaults to `true`, so+ * the bot answers a mention in a text channel in a new thread; set `false`+ * to answer in the channel, where replies continue the conversation. An+ * `onMessage` result's own `startThread` overrides it.+ */+ readonly startThread?: boolean | DiscordStartThreadOptions;+}++/** Mounts the route that turns forwarded `MESSAGE_CREATE` dispatches into turns. */+export function createDiscordGatewayRoute(input: {+ readonly config: DiscordChannelConfig;+ readonly gateway: DiscordGatewayConfig;+ readonly buildContext: (state: DiscordChannelState) => DiscordContext;+}): HttpRouteDefinition<DiscordChannelState> {+ const { config, gateway } = input;+ const auth = gateway.auth ?? [localDev(), sameEnvironmentRuntime()];+ const onMessage = gateway.onMessage ?? defaultOnMessage;++ return POST<DiscordChannelState>(+ gateway.route ?? DEFAULT_GATEWAY_ROUTE,+ async (req, { from, resolveSession }) => {+ const caller = await routeAuth(req, auth);+ if (caller instanceof Response) return caller;++ let body: Buffer;+ try {+ body = await readLimitedBytes(req, MAX_DISPATCH_BYTES, "discord");+ } catch (error) {+ if (!(error instanceof EveAttachmentError)) throw error;+ return Response.json({ error: "Body exceeds 1 MB." }, { status: 413 });+ }+ let dispatch: unknown;+ try {+ dispatch = JSON.parse(body.toString("utf8"));+ } catch {+ return Response.json({ error: "Body is not JSON." }, { status: 400 });+ }+ if (!isObject(dispatch) || dispatch.t !== "MESSAGE_CREATE")+ return ignored("unsupported_event");+ const raw = isObject(dispatch.d) ? dispatch.d : null;+ const parsed = raw === null ? null : parseGatewayMessage(raw);+ if (parsed === null) return ignored("invalid_message");+ if (parsed.author.isBot) return ignored("bot_author");++ const applicationId = await resolveDiscordApplicationId(config.credentials?.applicationId);+ const content = stripMention(parsed.content, applicationId);+ if (!content && parsed.attachments.length === 0) return ignored("empty_message");++ const isDirectMessage = parsed.guildId === undefined;+ const channelSession = isDirectMessage+ ? undefined+ : await resolveSession(+ discordContinuationToken(parsed.channelId, WHOLE_CHANNEL_CONVERSATION),+ );+ const message: DiscordGatewayMessage = {+ ...parsed,+ addressed:+ isDirectMessage ||+ channelSession !== undefined ||+ mentions(parsed.raw, applicationId) ||+ repliesTo(parsed.raw, applicationId),+ content,+ };++ const state: DiscordChannelState = {+ applicationId,+ channelId: message.channelId,+ conversationId: null,+ guildId: message.guildId ?? null,+ // Replies post as channel messages, which alias the session without re-keying it.+ hasMessageAnchor: true,+ initialResponseSent: true,+ interactionToken: null,+ };+ if (isDirectMessage) state.audience = discordAudience(1);++ let result: DiscordMessageResult;+ try {+ result = await onMessage(input.buildContext(state), message);+ } catch (error) {+ logError(log, "Discord message handler failed", error, { messageId: message.id });+ return Response.json({ error: "The message handler failed." }, { status: 500 });+ }+ if (result === null) return ignored("not_accepted");++ const explicitConversation = isNonEmptyString(result.conversation)+ ? result.conversation+ : undefined;+ const startThread = result.startThread ?? gateway.startThread ?? true;+ state.conversationId = await routeMessage();++ // Picks the session, and moves the message's replies into a new thread when asked.+ async function routeMessage(): Promise<string> {+ if (isDirectMessage || channelSession !== undefined) {+ return explicitConversation ?? WHOLE_CHANNEL_CONVERSATION;+ }+ if (explicitConversation === undefined) {+ const replyTo = message.referencedMessageId;+ if (+ replyTo !== undefined &&+ (await resolveSession(discordContinuationToken(message.channelId, replyTo))) !==+ undefined+ ) {+ return replyTo;+ }+ } else if (startThread === false) {+ return explicitConversation;+ }+ const channelType = await lookUpChannelType(config, message.channelId);+ if (channelType !== undefined) state.audience = discordAudience(channelType);+ if (channelType !== undefined && THREAD_CHANNEL_TYPES.has(channelType)) {+ return explicitConversation ?? WHOLE_CHANNEL_CONVERSATION;+ }+ if (startThread !== false) {+ const threadId = await startThreadFrom(+ config,+ message,+ startThread === true ? {} : startThread,+ );+ if (threadId !== undefined) {+ state.channelId = threadId;+ state.audience = "unknown";+ return explicitConversation ?? WHOLE_CHANNEL_CONVERSATION;+ }+ }+ return explicitConversation ?? message.id;+ }++ const contextBlock = formatDiscordContextBlock({+ applicationId,+ channelId: message.channelId,+ guildId: message.guildId,+ messageId: message.id,+ userId: message.author.id,+ username: message.author.username,+ });+ const session = await from(+ discordContinuationToken(state.channelId ?? message.channelId, state.conversationId),+ ).send(discordCommandContent(content, message.attachments), {+ auth: result.auth,+ context: [contextBlock, ...(result.context ?? [])],+ state,+ title: result.title,+ });+ return Response.json({ accepted: true, sessionId: session.id }, { status: 202 });+ },+ );+}++/**+ * Vercel OIDC from this project's runtime in the current environment only.+ * Other environments, such as a preview deployment, authenticate as+ * `service` and must not reach production as any Discord user.+ */+function sameEnvironmentRuntime(): AuthFn<Request> {+ const oidc = vercelOidc();+ return async (request) => {+ const auth = await oidc(request);+ return auth?.principalType === "runtime" ? auth : null;+ };+}++function ignored(reason: string): Response {+ return Response.json({ accepted: false, reason });+}++function parseGatewayMessage(+ raw: Record<string, unknown>,+): Omit<DiscordGatewayMessage, "addressed"> | null {+ if (!isNonEmptyString(raw.id) || !isNonEmptyString(raw.channel_id)) return null;+ if (typeof raw.type === "number" && !CONVERSATIONAL_MESSAGE_TYPES.has(raw.type)) return null;+ const author = parseDiscordUser(raw.author);+ if (author === null) return null;+ return {+ attachments: Array.isArray(raw.attachments)+ ? raw.attachments.flatMap((entry) => parseDiscordAttachment(entry) ?? [])+ : [],+ author,+ channelId: raw.channel_id,+ content: typeof raw.content === "string" ? raw.content : "",+ guildId: isNonEmptyString(raw.guild_id) ? raw.guild_id : undefined,+ id: raw.id,+ raw,+ referencedMessageId: referencedMessageId(raw),+ };+}++function referencedMessageId(raw: Record<string, unknown>): string | undefined {+ const reference = isObject(raw.message_reference) ? raw.message_reference : null;+ // Type 1 is a forward, which quotes a message rather than replying to it.+ if (reference === null || (reference.type !== undefined && reference.type !== 0))+ return undefined;+ return isNonEmptyString(reference.message_id) ? reference.message_id : undefined;+}++// A bot user's id is its application's id.+function mentions(raw: Record<string, unknown>, applicationId: string): boolean {+ return (+ Array.isArray(raw.mentions) &&+ raw.mentions.some((user) => isObject(user) && user.id === applicationId)+ );+}++function repliesTo(raw: Record<string, unknown>, applicationId: string): boolean {+ const referenced = isObject(raw.referenced_message) ? raw.referenced_message : null;+ return isObject(referenced?.author) && referenced.author.id === applicationId;+}++function stripMention(content: string, applicationId: string): string {+ return content+ .replaceAll(`<@${applicationId}>`, "")+ .replaceAll(`<@!${applicationId}>`, "")+ .trim();+}++const DISCORD_THREAD_NAME_MAX_LENGTH = 100;++/**+ * Starts a public thread from `message` and adds its author, returning the+ * thread's channel id, or `undefined` when Discord refuses.+ */+async function startThreadFrom(+ config: DiscordChannelConfig,+ message: DiscordGatewayMessage,+ options: DiscordStartThreadOptions,+): Promise<string | undefined> {+ const name =+ options.name?.trim() ||+ message.content.split("\n", 1)[0]?.trim() ||+ message.attachments[0]?.filename ||+ "Conversation";+ const body: Record<string, string | number> = {+ name: name.slice(0, DISCORD_THREAD_NAME_MAX_LENGTH),+ };+ if (options.autoArchiveMinutes !== undefined) {+ body.auto_archive_duration = options.autoArchiveMinutes;+ }+ try {+ const botToken = await resolveDiscordBotToken(config.credentials?.botToken);+ const api = { apiBaseUrl: config.api?.apiBaseUrl, botToken, fetch: config.api?.fetch };+ const created = await callDiscordApi({+ ...api,+ body,+ path: `/channels/${encodeURIComponent(message.channelId)}/messages/${encodeURIComponent(message.id)}/threads`,+ });+ const threadId = isObject(created.body) ? created.body.id : undefined;+ if (!created.ok || !isNonEmptyString(threadId)) {+ log.warn("Discord thread creation failed; answering in the channel", {+ channelId: message.channelId,+ status: created.status,+ });+ return undefined;+ }+ // Starting a thread adds only the bot, so its replies would not reach the author.+ const added = await callDiscordApi({+ ...api,+ method: "PUT",+ path: `/channels/${encodeURIComponent(threadId)}/thread-members/${encodeURIComponent(message.author.id)}`,+ });+ if (!added.ok) {+ log.warn("Adding the author to a Discord thread failed", { status: added.status, threadId });+ }+ return threadId;+ } catch (error) {+ log.warn("Discord thread creation failed; answering in the channel", {+ channelId: message.channelId,+ error,+ });+ return undefined;+ }+}++/** Gateway messages omit the channel type, which tells a thread from a channel. */+async function lookUpChannelType(+ config: DiscordChannelConfig,+ channelId: string,+): Promise<number | undefined> {+ try {+ const response = await callDiscordApi({+ apiBaseUrl: config.api?.apiBaseUrl,+ botToken: await resolveDiscordBotToken(config.credentials?.botToken),+ fetch: config.api?.fetch,+ method: "GET",+ path: `/channels/${encodeURIComponent(channelId)}`,+ });+ if (response.ok && isObject(response.body) && typeof response.body.type === "number") {+ return response.body.type;+ }+ log.warn("Discord channel lookup failed; treating the channel as a non-thread", {+ channelId,+ status: response.status,+ });+ } catch (error) {+ log.warn("Discord channel lookup failed; treating the channel as a non-thread", {+ channelId,+ error,+ });+ }+ return undefined;+}diff --git a/research/discord-gateway-relay.md b/research/discord-gateway-relay.mdnew file mode 100644index 000000000..c7a05c6aa--- /dev/null+++ b/research/discord-gateway-relay.md@@ -0,0 +1,101 @@+---+issue: https://github.com/vercel/eve/pull/4934+status: implemented+last_updated: "2026-10-19"+---++# Discord Gateway relay++> **AI status:** Written entirely by AI; human review pending.++The Discord channel answers only HTTP Interactions: slash commands, components, and modals.+Discord delivers ordinary messages, such as DMs, mentions, and thread replies, only over its+Gateway WebSocket, which needs a process that stays connected. Apps that want a conversational+bot today copy roughly 450 lines from a template: a Gateway client, a forwarder, and a second+channel that reimplements a subset of `discordChannel` without HITL, error replies, or+attachments. This plan moves both halves into eve so an app only configures them.++## Authoring API++```ts+// agent/channels/discord.ts+export default discordChannel({+ credentials: connectDiscordCredentials("discord/my-agent"),+ gateway: {}, // mounts POST /eve/v1/discord/gateway+ // gateway: { route?, auth?, onMessage?(ctx, message) => { auth, context?, title? } | null }+});++// daemon/main.ts, run as a Vercel Daemon+await experimental_runDiscordGatewayRelay({+ credentials: connectDiscordCredentials("discord/my-agent"),+ // url?, route?, auth?, messageContent?, signal?, api?+});+```++`gateway.onMessage` mirrors `onCommand`. `defaultDiscordMessageAuth(message)` mirrors+`defaultDiscordAuth(interaction)`.++## Naming++Both halves are named for the Discord Gateway because the wire format is the Gateway's own: the+relay forwards each `MESSAGE_CREATE` dispatch (`{ op, t, s, d }`) unchanged, and the route parses+it. That makes the route usable by any Gateway client, such as discord.js, without an eve-specific+envelope, and leaves room for more dispatch types without a format change. Docs and logs always+say "Discord Gateway" so it does not read as Vercel AI Gateway.++```text+Discord Gateway ──WS──▶ experimental_runDiscordGatewayRelay ──POST {op,t,s,d}──▶ discordChannel gateway route+ (one instance, OIDC) ──REST──▶ Discord+```++## Semantics++- **Addressing.** A message is `addressed` when it is a DM, mentions the bot, replies to the+ bot, or arrives in a thread with a live session. The default `onMessage` dispatches addressed+ messages; a custom one sees every message from a person. Bot authors never reach the hook.+- **Sessions.** DMs and threads map to one session per channel (`<channelId>:channel`). In a+ text channel, a mention starts a thread (see Threads), and a reply continues whichever live+ session owns the replied-to message. With threads off, a mention starts a session keyed by the+ message (`<channelId>:<messageId>`). `onMessage` can+ return `conversation` to choose the key instead, such as `user:<userId>` for one session per+ person. Gateway messages omit the channel type, so the route looks it up only when the+ default needs it.+- **Threads.** By default a message that would open a new session in a text channel starts a+ public thread, adds the author, and keys the session `<threadId>:channel`, as the Slack+ channel answers in threads. `gateway.startThread: false` answers in the channel instead, where+ a mention starts a session keyed by the message and replies continue it; an `onMessage` result's+ `startThread` decides per message. DMs, thread messages, and replies that continue a session are+ untouched, and a refused creation falls back to the channel.+- **Delivery.** Gateway sessions have no interaction token, so `channel.discord.post()` sends+ channel messages. They start with `hasMessageAnchor: true`, so replies never re-key the+ session. Every message the bot posts, in any Discord session, aliases+ `<channelId>:<messageId>`, so both a button press and a Gateway reply find the session that+ posted it.+- **Identity.** Messages and interactions from the same person share a principal, including the+ existing `discord-interaction` authenticator, so requester-only approvals asked by a message+ accept that person's button press. Keeping the old authenticator string avoids orphaning+ existing principals, pending approvals, and per-user tool sessions.+- **Route auth.** The body asserts the author's identity, so the default is narrower than+ ordinary route auth: `localDev()` plus Vercel OIDC from this project's runtime in the same+ environment (`principalType: "runtime"`). A preview deployment cannot post to production. The relay signs with the project's OIDC token by default and forwards without+ credentials when none exists, which `eve dev` accepts.+- **Route contract.** The body is a raw Gateway dispatch, capped at 1 MB. Responses: `202`+ dispatched, `200 { accepted: false, reason }` ignored, `400` not JSON, `401` auth, `413` too+ large, `429` rate limited (retryable), `5xx` unknown, since a platform timeout can follow a+ dispatch. eve does not deduplicate.+- **Relay.** Discovers the Gateway URL from `GET /gateway/bot`, identifies with the+ `GUILD_MESSAGES` and `DIRECT_MESSAGES` intents (plus `MESSAGE_CONTENT` on request), resumes+ across reconnects, and forwards dispatches serially with a bounded backlog. It retries only a+ `429` or a connection that failed before the request reached eve, never a `5xx` or a timeout. It stops+ with `DiscordGatewayFatalError` on close codes that reconnecting cannot fix.++## Boundaries++- The relay is a library, not generated code. Deployment wiring (Dockerfile, `vercel.json`+ `daemons`) stays in the app; `eve add channel/discord` could scaffold it later.+- No deduplication. A Gateway sequence number identifies a dispatch only within one session, and+ eve has no idempotent `send`, so two relays connected at once, or a retry after eve started a turn,+ can answer twice.+- No cross-process resume. A deploy or restart starts a new Gateway session, so messages sent while+ no relay is connected are lost. Handing the session cursor to the next process is a follow-up.+- One relay per bot. Sharding is out of scope.