Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(discord): answer HITL presses as the presser (#4430)

Ben Pankow7c60065ebd11
diff --git a/.changeset/discord-press-auth.md b/.changeset/discord-press-auth.md
new file mode 100644
index 000000000..c8f68bb97
--- /dev/null
+++ b/.changeset/discord-press-auth.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Discord button presses, selects, and modal submissions now answer as the Discord user who made them instead of anonymously, so requester-only and other approval response policies work on Discord. The new `onInputResponse` option on `discordChannel` chooses an answer's auth or drops it, and its context carries the presser's `defaultAuth`. Apps with a custom `onCommand` must also set `onInputResponse`; until they do, eve drops presses and logs a warning.
diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdx
index 5bf26e6d0..8b7df2e62 100644
--- a/docs/channels/discord.mdx
+++ b/docs/channels/discord.mdx
@@ -94,6 +94,28 @@ Typing fires on `turn.started` and `actions.requested`, but only when a bot toke
HITL renders as Discord components. Confirmations and options become buttons, `display: "select"` becomes a string select, and freeform input becomes a button that opens a modal. When the user responds, the parked session (paused awaiting input) resumes.
+A press, select, or modal submission answers as the Discord user who made it, with the same `defaultDiscordAuth` principal a command from them gets by default. Approval response policies compare against that principal. Approvals are requester-only by default, so only the person whose command asked can approve. `onInputResponse(ctx, interaction)` decides the answer's `auth`: return `{ auth }` to accept it, or `null` (or throw) to drop it and keep the request pending. `ctx.defaultAuth` is the presser's `defaultDiscordAuth`; it identifies them but doesn't authorize them by itself.
+
+If you customize `onCommand`, eve drops every press and submission until you also set `onInputResponse`, and logs a warning saying so. The default Discord principal wouldn't match the principals your `onCommand` returns, so a requester-only approval would refuse the requester. It would also let someone your `onCommand` turns away answer open approvals. Give both hooks the same mapping and gating:
+
+```ts
+import { discordChannel } from "eve/channels/discord";
+
+const auth = (interaction: { user: { id: string } }) => ({
+ auth: {
+ principalId: `user:${interaction.user.id}`,
+ principalType: "user" as const,
+ authenticator: "discord",
+ attributes: {},
+ },
+});
+
+export default discordChannel({
+ onCommand: (_ctx, interaction) => auth(interaction),
+ onInputResponse: (_ctx, interaction) => auth(interaction),
+});
+```
+
### Proactive sessions
Start a session without an inbound interaction through `to(discord, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(discord, target).send(message, { auth })` from another channel. The proactive target shape is `{ channelId, conversationId?, initialMessage? }`. Either path needs a bot token, supplied by Connect or `DISCORD_BOT_TOKEN`.
diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
index a31ea3bb2..00f2d2581 100644
--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
@@ -75,20 +75,20 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform
| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[11](#note-11)</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>[11](#note-11)</sup> | ✅ | ✅ | ✅ |
-| the requester pressing Approve on a requester-only approval runs the tool | ✅ | ✅ | ✅ | | —<sup>[1](#note-1)</sup> | ❌<sup>[17](#note-17)</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> |
-| another person pressing Approve on a requester-only approval leaves it pending | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ❌<sup>[17](#note-17)</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> |
-| another person pressing Cancel on a requester-only approval leaves it pending | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ❌<sup>[17](#note-17)</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> |
-| another person's rejected press leaves the approval's buttons in place | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</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> |
-| another person pressing Approve on an open approval runs the tool | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[19](#note-19)</sup> | ❌<sup>[17](#note-17)</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> |
+| the requester pressing Approve on a requester-only approval runs the 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> |
+| another person pressing Approve on a requester-only approval leaves it pending | —<sup>[17](#note-17)</sup> | —<sup>[17](#note-17)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> |
+| another person pressing Cancel on a requester-only approval leaves it pending | —<sup>[17](#note-17)</sup> | —<sup>[17](#note-17)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> |
+| another person's rejected press leaves the approval's buttons in place | —<sup>[17](#note-17)</sup> | —<sup>[17](#note-17)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> |
+| another person pressing Approve on an open approval runs the tool | —<sup>[17](#note-17)</sup> | —<sup>[17](#note-17)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | ✅ | | —<sup>[18](#note-18)</sup> | | ✅ | | ✅ | | ✅ | | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</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>[20](#note-20)</sup> | —<sup>[20](#note-20)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[20](#note-20)</sup> | ✅ | ✅ | ✅ |
-| a PDF a person sends reaches the agent with its bytes and type | —<sup>[20](#note-20)</sup> | —<sup>[20](#note-20)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[20](#note-20)</sup> | ✅ | ✅ | ✅ |
-| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[20](#note-20)</sup> | —<sup>[20](#note-20)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[20](#note-20)</sup> | ✅ | ✅ | ✅ |
-| a file sent earlier in the conversation is still there on a later message | —<sup>[20](#note-20)</sup> | —<sup>[20](#note-20)</sup> | ✅ | | ✅ | —<sup>[21](#note-21)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[20](#note-20)</sup> | ✅ | ✅ | ✅ |
+| an image a person sends reaches the agent with its bytes and type | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[19](#note-19)</sup> | ✅ | ✅ | ✅ |
+| a PDF a person sends reaches the agent with its bytes and type | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | ✅ | ✅ | ✅ |
+| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | ✅ | ✅ | ✅ |
+| a file sent earlier in the conversation is still there on a later message | —<sup>[19](#note-19)</sup> | —<sup>[19](#note-19)</sup> | ✅ | | ✅ | —<sup>[20](#note-20)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | —<sup>[19](#note-19)</sup> | ✅ | ✅ | ✅ |
## Notes
@@ -108,8 +108,7 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform
14. <a id="note-14"></a>the rule applies only where the conversation is public or shared, and this one is private
15. <a id="note-15"></a>the sign-in prompt, link included, is posted to the whole thread
16. <a id="note-16"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified
-17. <a id="note-17"></a>a button press responds with `auth: null`, so no one can satisfy a response policy
-18. <a id="note-18"></a>the platform has no second person who can act
-19. <a id="note-19"></a>the platform has no second person who can act or buttons a person can press
-20. <a id="note-20"></a>the platform has no files a person can send
-21. <a id="note-21"></a>each slash command starts its own session, so no later message shares one with the file
+17. <a id="note-17"></a>the platform has no second person who can act
+18. <a id="note-18"></a>the platform has no second person who can act or buttons a person can press
+19. <a id="note-19"></a>the platform has no files a person can send
+20. <a id="note-20"></a>each slash command starts its own session, so no later message shares one with the file
diff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
index 10a894dac..3c09b9819 100644
--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
@@ -90,19 +90,6 @@ function unnamedAnsweredPrompts(
);
}
-/** Presses reach a response policy without the presser's identity, so eve refuses them all. */
-function anonymousPresses(
- reason: string,
- rules: readonly ContractRuleName[],
-): Partial<Record<ContractRuleName, BrokenCell>> {
- return Object.fromEntries(
- rules.map((rule) => [
- rule,
- { reason, symptom: /Authentication is required to respond to this approval/ },
- ]),
- );
-}
-
interface ConformanceChannel {
readonly driver: () => ChannelDriver | ClientDriver;
/**
@@ -162,15 +149,6 @@ const CHAT_SDK_BROKEN = {
const DISCORD_BROKEN = {
...unnamedAnsweredPrompts(UNNAMED_RESPONDER, ["approvalPress", "questionPress"]),
- ...anonymousPresses(
- "a button press responds with `auth: null`, so no one can satisfy a response policy",
- [
- "the requester pressing Approve on a requester-only approval runs the tool",
- "another person pressing Approve on a requester-only approval leaves it pending",
- "another person pressing Cancel on a requester-only approval leaves it pending",
- "another person pressing Approve on an open approval runs the tool",
- ],
- ),
...noSignInRenderer(
"a sign-in names the service and shows its sign-in link",
"a sign-in shows its confirmation code",
diff --git a/packages/eve/src/public/channels/discord/defaults.ts b/packages/eve/src/public/channels/discord/defaults.ts
index 19c4d8a4f..10fbb2a14 100644
--- a/packages/eve/src/public/channels/discord/defaults.ts
+++ b/packages/eve/src/public/channels/discord/defaults.ts
@@ -6,7 +6,10 @@ import {
DISCORD_MESSAGE_CONTENT_MAX_LENGTH,
splitDiscordMessageContent,
} from "#public/channels/discord/api.js";
-import type { DiscordCommandInteraction } from "#public/channels/discord/inbound.js";
+import type {
+ DiscordCommandInteraction,
+ DiscordInteractionBase,
+} from "#public/channels/discord/inbound.js";
import { renderInputRequestComponents } from "#public/channels/discord/hitl.js";
import type {
DiscordChannelEvents,
@@ -17,13 +20,14 @@ import type {
const log = createLogger("discord.defaults");
/**
- * Builds the default {@link SessionAuthContext} for a Discord command
- * interaction: 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.
+ * 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.
*/
-export function defaultDiscordAuth(interaction: DiscordCommandInteraction): SessionAuthContext {
+export function defaultDiscordAuth(interaction: DiscordInteractionBase): SessionAuthContext {
const attributes: Record<string, string> = {
channel_id: interaction.channelId,
interaction_id: interaction.id,
diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.ts
index 3fe21b780..0366657af 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts
@@ -291,34 +291,87 @@ describe("discordChannel() inbound route", () => {
);
});
- it("acknowledges HITL button clicks with a deferred update", async () => {
+ describe("answering a HITL press", () => {
const { privateKey, publicKeyHex } = testKeys();
- const components = renderInputRequestComponents({
- action: { callId: "call_1", input: {}, kind: "tool-call", toolName: "ask_question" },
- kind: "question",
- options: [{ id: "approve", label: "Approve" }],
- prompt: "Approve?",
- requestId: "call_1",
+ const customId = (
+ renderInputRequestComponents({
+ action: { callId: "call_1", input: {}, kind: "tool-call", toolName: "ask_question" },
+ kind: "question",
+ options: [{ id: "approve", label: "Approve" }],
+ prompt: "Approve?",
+ requestId: "call_1",
+ })[0] as { components: Array<{ custom_id: string }> }
+ ).components[0]!.custom_id;
+ /** A press of Approve in guild G01, as Discord sends it: the presser on `member`. */
+ const press = (userId: string) =>
+ signedRequest({
+ body: JSON.stringify({
+ application_id: "APP1",
+ channel_id: "C01",
+ data: { component_type: 2, custom_id: customId },
+ guild_id: "G01",
+ id: `I-${userId}`,
+ member: { user: { id: userId, username: userId } },
+ message: { id: "M01" },
+ token: "tok2",
+ type: 3,
+ version: 1,
+ }),
+ privateKey,
+ });
+ const answered = (principalId: string) =>
+ expect.objectContaining({
+ auth: expect.objectContaining({ principalId }),
+ inputResponses: [{ optionId: "approve", requestId: "call_1" }],
+ });
+
+ it("answers as the guild member who pressed", async () => {
+ const channel = discordChannel({ credentials: { publicKey: publicKeyHex } });
+
+ const { response, send } = await firePost(channel, press("U01"));
+
+ await expect(response.json()).resolves.toEqual({ type: 6 });
+ expect(send).toHaveBeenCalledWith("C01:M01", answered("discord:G01:U01"));
});
- const customId = (components[0] as { components: Array<{ custom_id: string }> }).components[0]!
- .custom_id;
- const body = JSON.stringify({
- application_id: "APP1",
- channel_id: "C01",
- data: { component_type: 2, custom_id: customId },
- id: "I02",
- message: { id: "M01" },
- token: "tok2",
- type: 3,
- user: { id: "U01", username: "ada" },
- version: 1,
+
+ it("lets onInputResponse accept a press with ctx.defaultAuth or drop it", async () => {
+ const channel = discordChannel({
+ credentials: { publicKey: publicKeyHex },
+ onInputResponse: (ctx, interaction) =>
+ interaction.user.id === "U01" ? { auth: ctx.defaultAuth } : null,
+ });
+
+ const accepted = await firePost(channel, press("U01"));
+ const dropped = await firePost(channel, press("U02"));
+
+ expect(accepted.send).toHaveBeenCalledWith("C01:M01", answered("discord:G01:U01"));
+ expect(dropped.send).not.toHaveBeenCalled();
});
- const channel = discordChannel({ credentials: { publicKey: publicKeyHex } });
- const { response } = await firePost(channel, signedRequest({ body, privateKey }));
+ it.each([
+ {
+ name: "onInputResponse throws",
+ config: {
+ onInputResponse: () => {
+ throw new Error("policy lookup failed");
+ },
+ },
+ log: { level: "error", message: "input response handler failed" },
+ },
+ {
+ name: "onCommand is custom and onInputResponse isn't",
+ config: { onCommand: () => ({ auth: null }) },
+ log: { level: "warn", message: expect.stringContaining("set onInputResponse") },
+ },
+ ])("drops a press when $name", async ({ config, log }) => {
+ const logs = captureLogRecords();
+ const channel = discordChannel({ credentials: { publicKey: publicKeyHex }, ...config });
- expect(response.status).toBe(200);
- await expect(response.json()).resolves.toEqual({ type: 6 });
+ const { send } = await firePost(channel, press("U01"));
+
+ expect(send).not.toHaveBeenCalled();
+ expect(logs.records).toContainEqual(expect.objectContaining(log));
+ });
});
it("opens and resolves freeform HITL modals", async () => {
@@ -388,6 +441,7 @@ describe("discordChannel() inbound route", () => {
expect(submit.send).toHaveBeenCalledWith(
"C01:M01",
expect.objectContaining({
+ auth: expect.objectContaining({ principalId: "discord:U01" }),
inputResponses: [{ requestId: "call_1", text: "freeform answer" }],
}),
);
@@ -583,15 +637,11 @@ describe("defaultDiscordAuth", () => {
it("derives guild-scoped user auth", () => {
const auth = defaultDiscordAuth({
applicationId: "APP1",
- attachments: [],
channelId: "C01",
- commandName: "ask",
guildId: "G01",
id: "I01",
- options: [],
raw: {},
token: "tok",
- type: 2,
user: { id: "U01", isBot: false, username: "ada" },
});
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index ba0c421d4..1a7e6626a 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -21,7 +21,11 @@ import {
type DiscordMessageBody,
type DiscordPostedMessage,
} from "#public/channels/discord/api.js";
-import { defaultEvents, defaultOnCommand } from "#public/channels/discord/defaults.js";
+import {
+ defaultDiscordAuth,
+ defaultEvents,
+ defaultOnCommand,
+} from "#public/channels/discord/defaults.js";
import {
deriveComponentInputResponses,
deriveModalInputResponses,
@@ -68,6 +72,12 @@ export interface DiscordContext {
readonly discord: DiscordHandle;
}
+/** Context passed to `discordChannel({ onInputResponse })` before eve answers the pending request. */
+export interface DiscordInputResponseContext extends DiscordContext {
+ /** Auth derived from the Discord user who pressed or submitted, as `defaultDiscordAuth` builds it. */
+ readonly defaultAuth: SessionAuthContext;
+}
+
/** Channel-owned Discord context returned by `context()`. */
type DiscordChannelContext = DiscordContext & { state: DiscordChannelState };
@@ -133,6 +143,14 @@ export type DiscordCommandResult = {
/** Sync or async {@link DiscordCommandResult}. */
export type DiscordCommandResultOrPromise = DiscordCommandResult | Promise<DiscordCommandResult>;
+/** Result of {@link DiscordChannelConfig.onInputResponse}: `{ auth }` to accept the answer, or `null` to drop it. */
+export type DiscordInputResponseResult = { readonly auth: SessionAuthContext | null } | null;
+
+/** A Discord interaction that answers a pending request: a button press, a select, or a modal submission. */
+export type DiscordInputResponseInteraction =
+ | DiscordComponentInteraction
+ | DiscordModalSubmitInteraction;
+
type DiscordEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (
data: EventData<T>,
channel: DiscordEventContext,
@@ -179,6 +197,19 @@ export interface DiscordChannelConfig {
interaction: DiscordCommandInteraction,
): DiscordCommandResultOrPromise;
+ /**
+ * Authorizes a button press, select, or modal submission before it answers a
+ * pending request. Return `{ auth }` to accept the answer, or `null` to drop
+ * it and keep the request pending. Thrown errors are logged and drop the
+ * answer. Defaults to the interacting user's Discord auth. With a custom
+ * `onCommand` and no `onInputResponse`, every answer is dropped: set it to
+ * give a person's answers the same principal, and gating, as their commands.
+ */
+ onInputResponse?(
+ ctx: DiscordInputResponseContext,
+ interaction: DiscordInputResponseInteraction,
+ ): DiscordInputResponseResult | Promise<DiscordInputResponseResult>;
+
readonly events?: DiscordChannelEvents;
}
@@ -230,6 +261,9 @@ export interface DiscordChannel extends Channel<
/** Discord channel factory for HTTP Interactions and proactive channel messages. */
export function discordChannel(config: DiscordChannelConfig = {}): DiscordChannel {
const onCommand = config.onCommand ?? defaultOnCommand;
+ const onInputResponse =
+ config.onInputResponse ??
+ (config.onCommand === undefined ? acceptAsPresser : dropUnmappedInputResponse);
const mergedEvents: DiscordChannelEvents = { ...defaultEvents, ...config.events };
return defineChannel<
@@ -277,6 +311,7 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanne
config,
interaction,
onCommand,
+ onInputResponse,
from,
waitUntil,
});
@@ -499,6 +534,7 @@ async function handleInteraction(input: {
readonly config: DiscordChannelConfig;
readonly interaction: DiscordInteraction;
readonly onCommand: NonNullable<DiscordChannelConfig["onCommand"]>;
+ readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
readonly from: ChannelFrom<DiscordChannelState>;
readonly waitUntil: (task: Promise<unknown>) => void;
}): Promise<Response> {
@@ -513,13 +549,17 @@ async function handleInteraction(input: {
}
if (input.interaction.type === DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT) {
return handleComponentInteraction({
+ config: input.config,
interaction: input.interaction,
+ onInputResponse: input.onInputResponse,
from: input.from,
waitUntil: input.waitUntil,
});
}
return handleModalSubmitInteraction({
+ config: input.config,
interaction: input.interaction,
+ onInputResponse: input.onInputResponse,
from: input.from,
waitUntil: input.waitUntil,
});
@@ -564,7 +604,9 @@ async function handleCommandInteraction(input: {
}
function handleComponentInteraction(input: {
+ readonly config: DiscordChannelConfig;
readonly interaction: DiscordComponentInteraction;
+ readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
readonly from: ChannelFrom<DiscordChannelState>;
readonly waitUntil: (task: Promise<unknown>) => void;
}): Response {
@@ -582,6 +624,8 @@ function handleComponentInteraction(input: {
if (inputResponses.length > 0) {
input.waitUntil(
dispatchInputResponses({
+ config: input.config,
+ onInputResponse: input.onInputResponse,
conversationId: input.interaction.messageId,
inputResponses,
interaction: input.interaction,
@@ -593,7 +637,9 @@ function handleComponentInteraction(input: {
}
function handleModalSubmitInteraction(input: {
+ readonly config: DiscordChannelConfig;
readonly interaction: DiscordModalSubmitInteraction;
+ readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
readonly from: ChannelFrom<DiscordChannelState>;
readonly waitUntil: (task: Promise<unknown>) => void;
}): Response {
@@ -601,6 +647,8 @@ function handleModalSubmitInteraction(input: {
if (inputResponses.length > 0) {
input.waitUntil(
dispatchInputResponses({
+ config: input.config,
+ onInputResponse: input.onInputResponse,
conversationId: input.interaction.messageId ?? input.interaction.id,
inputResponses,
interaction: input.interaction,
@@ -647,22 +695,59 @@ async function dispatchCommand(input: {
}
async function dispatchInputResponses(input: {
+ readonly config: DiscordChannelConfig;
+ readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
readonly conversationId: string;
readonly inputResponses: readonly ValidatedInputResponse[];
- readonly interaction: DiscordComponentInteraction | DiscordModalSubmitInteraction;
+ readonly interaction: DiscordInputResponseInteraction;
readonly from: ChannelFrom<DiscordChannelState>;
}): Promise<void> {
+ const state = stateFromInteraction(input.interaction, {
+ conversationId: input.conversationId,
+ // A modal opened outside a message falls back to the interaction id, which is no message.
+ hasMessageAnchor: input.conversationId !== input.interaction.id,
+ initialResponseSent: true,
+ });
+ let result: DiscordInputResponseResult;
+ try {
+ result = await input.onInputResponse(
+ {
+ defaultAuth: defaultDiscordAuth(input.interaction),
+ discord: buildDiscordHandle({ config: input.config, state }),
+ },
+ input.interaction,
+ );
+ } catch (error) {
+ log.error("input response handler failed", { error });
+ return;
+ }
+ if (result === null) return;
try {
await input
.from(discordContinuationToken(input.interaction.channelId, input.conversationId))
.respond(input.inputResponses, {
- auth: null,
+ auth: result.auth,
});
} catch (error) {
log.error("interaction response delivery failed", { error });
}
}
+function acceptAsPresser(ctx: DiscordInputResponseContext): DiscordInputResponseResult {
+ return { auth: ctx.defaultAuth };
+}
+
+/**
+ * A custom `onCommand` may map users to its own principals or keep some out.
+ * The default Discord auth would match neither, so answers fail closed.
+ */
+function dropUnmappedInputResponse(): null {
+ log.warn(
+ "dropped a Discord input response: onCommand is customized but onInputResponse is not; set onInputResponse to accept button presses and modal submissions",
+ );
+ return null;
+}
+
function stateFromInteraction(
interaction: DiscordInteraction,
options: {
diff --git a/packages/eve/src/public/channels/discord/index.ts b/packages/eve/src/public/channels/discord/index.ts
index e2e629ea5..7163ab491 100644
--- a/packages/eve/src/public/channels/discord/index.ts
+++ b/packages/eve/src/public/channels/discord/index.ts
@@ -29,6 +29,9 @@ export {
type DiscordContext,
type DiscordEventContext,
type DiscordHandle,
+ type DiscordInputResponseContext,
+ type DiscordInputResponseInteraction,
+ type DiscordInputResponseResult,
type DiscordReceiveTarget,
type DiscordRequestOptions,
} from "#public/channels/discord/discordChannel.js";