Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[2/4] feat(discord): show connection sign-ins (#5030)

Ben Pankowacc76d59f904
diff --git a/.changeset/discord-sign-ins.md b/.changeset/discord-sign-ins.md
new file mode 100644
index 000000000..f0a777292
--- /dev/null
+++ b/.changeset/discord-sign-ins.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The Discord channel now shows connection sign-ins. In a DM it posts the sign-in link and any confirmation code; in a server it posts a **Sign in** button that shows the link only to the person who has to sign in, in an ephemeral message. The message updates once the sign-in completes or is cancelled.
diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdx
index 0ef312a39..971e8e934 100644
--- a/docs/channels/discord.mdx
+++ b/docs/channels/discord.mdx
@@ -377,6 +377,12 @@ export default discordChannel({
});
```
+### Connection sign-ins
+
+When a connection needs the person to sign in, the default `authorization.required` handler posts it to the conversation. In a DM, the message includes a link button to the sign-in page and any confirmation code. In a server, the shared message only says who has to sign in and has a **Sign in** button. When someone presses it, eve identifies them the same way it does for HITL presses (`onInputResponse`). If that's the person who has to sign in, eve answers with an ephemeral message holding the link and code, which only they can see. Anyone else gets an ephemeral note that they can't open it. That way another member can't finish the sign-in with their own account and have it saved under the requester's identity. Once the sign-in completes or is cancelled, eve edits the message to say so and removes its button.
+
+If `onCommand` or `gateway.onMessage` gives people principals other than the default, set `onInputResponse` to the same mapping. Otherwise eve can't match a press to the person who has to sign in, and nobody can open the sign-in in a server.
+
### 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/channel/pending-authorization.ts b/packages/eve/src/channel/pending-authorization.ts
index d79e51d25..44be7b5a1 100644
--- a/packages/eve/src/channel/pending-authorization.ts
+++ b/packages/eve/src/channel/pending-authorization.ts
@@ -42,6 +42,7 @@ export async function findPendingAuthorization(
return [...pending.values()].at(-1);
}
-function attemptKey(event: { readonly attemptId?: string; readonly name: string }): string {
+/** Identifies one sign-in attempt: a connection name and its `attemptId`. */
+export function attemptKey(event: { readonly attemptId?: string; readonly name: string }): string {
return JSON.stringify([event.name, event.attemptId ?? null]);
}
diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
index 407d6eefd..f53231e03 100644
--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
@@ -91,15 +91,15 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform
| 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> | ✅ | ✅ | ✅ |
+| a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ |
+| a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[16](#note-16)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[17](#note-17)</sup> | ✅ | ✅ | ✅ |
+| only the person signing in sees the sign-in link and code | —<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> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | —<sup>[18](#note-18)</sup> | ✅ | ✅ | ❌<sup>[19](#note-19)</sup> | —<sup>[18](#note-18)</sup> | —<sup>[18](#note-18)</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>[20](#note-20)</sup> | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | ✅ | —<sup>[9](#note-9)</sup> | ✅ | —<sup>[9](#note-9)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[10](#note-10)</sup> | —<sup>[20](#note-20)</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>[21](#note-21)</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> | ✅ | ✅ | ✅ |
+| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[21](#note-21)</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>[21](#note-21)</sup> | ✅ | ✅ | ✅ |
## Tool callers
@@ -112,10 +112,10 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform
| 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> | ✅ | ✅ | ✅ |
+| an image a person sends reaches the agent with its bytes and type | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |
+| a PDF a person sends reaches the agent with its bytes and type | —<sup>[22](#note-22)</sup> | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |
+| a file that can't be downloaded reaches the agent as a note, not a link, and the next message still works | —<sup>[22](#note-22)</sup> | —<sup>[23](#note-23)</sup> | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |
+| a file sent earlier in the conversation is still there on a later message | —<sup>[22](#note-22)</sup> | ✅ | ✅ | | ✅ | —<sup>[24](#note-24)</sup> | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | —<sup>[22](#note-22)</sup> | ✅ | ✅ | ✅ |
## Notes
@@ -134,14 +134,12 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform
13. <a id="note-13"></a>one person answers in their own browser tab; there's nobody else to tell
14. <a id="note-14"></a>a resolved prompt doesn't say who answered; input.resolved carries no responder
15. <a id="note-15"></a>a press carries only the card's message id, and the session that knew its prompt is gone, so the retired card shows only how it ended
-16. <a id="note-16"></a>the channel has no default sign-in renderer
-17. <a id="note-17"></a>Linq's openDM needs the person's phone handle, but a message names its sender by an opaque handle id, so the bot can only say to continue in a direct message
-18. <a id="note-18"></a>the rule applies only where the conversation is shared or private, and this one is public
-19. <a id="note-19"></a>the rule applies only where the conversation is public or shared, and this one is private
-20. <a id="note-20"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified
-21. <a id="note-21"></a>the sign-in goes privately to the person signing in, so the thread shows nothing to press
-22. <a id="note-22"></a>the channel shows no sign-in, so there's nothing to press
-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 file
+16. <a id="note-16"></a>Linq's openDM needs the person's phone handle, but a message names its sender by an opaque handle id, so the bot can only say to continue in a direct message
+17. <a id="note-17"></a>the rule applies only where the conversation is shared or private, and this one is public
+18. <a id="note-18"></a>the rule applies only where the conversation is public or shared, and this one is private
+19. <a id="note-19"></a>the code is in the elicitation body the whole issue sees; who sees the auth signal's link is unverified
+20. <a id="note-20"></a>the sign-in goes privately to the person signing in, so the thread shows nothing to press
+21. <a id="note-21"></a>the channel has no default sign-in renderer
+22. <a id="note-22"></a>the platform has no files a person can send
+23. <a id="note-23"></a>the browser sends a file's bytes with the message, so there is no download to fail
+24. <a id="note-24"></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 520f71365..7c6b4f568 100644
--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
@@ -155,29 +155,12 @@ const CHAT_SDK_BROKEN = {
const DISCORD_BROKEN = {
...unnamedAnsweredPrompts(UNNAMED_RESPONDER, ["approvalPress", "questionPress"]),
- ...noSignInRenderer(
- "a sign-in names the service and shows its sign-in link",
- "a sign-in shows its confirmation code",
- "a sign-in without a link shows its instructions",
- "completing a sign-in tells the person it succeeded",
- ),
};
/** 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";
@@ -188,12 +171,7 @@ 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_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>>;
@@ -253,13 +231,11 @@ const channelConformance = {
{ driver: () => discordDriver(), broken: DISCORD_BROKEN, unsupported: DISCORD_UNSUPPORTED },
{
driver: () => discordDriver("shared", "gateway"),
- broken: DISCORD_GATEWAY_SHARED_BROKEN,
- unsupported: DISCORD_GATEWAY_UNSUPPORTED,
+ broken: DISCORD_GATEWAY_BROKEN,
},
{
driver: () => discordDriver("shared", "gateway-threads"),
broken: DISCORD_GATEWAY_BROKEN,
- unsupported: DISCORD_GATEWAY_UNSUPPORTED,
},
],
"discord-dm": [
@@ -273,7 +249,6 @@ const channelConformance = {
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.ts
index f33dacef8..18aea0c3c 100644
--- a/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/discord-driver.ts
@@ -86,6 +86,8 @@ export function discordDriver(
const uploads = new Map<string, SentFile>();
/** The message each interaction token's `@original` response is, once known. */
const originals = new Map<string, string>();
+ /** Interaction tokens answered with an ephemeral deferred response, which only the presser sees. */
+ const ephemeralTokens = new Set<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. */
@@ -299,21 +301,47 @@ export function discordDriver(
},
shownMessage(call) {
if (!isMessageWrite(call)) return undefined;
+ const token = /\/webhooks\/[^/]+\/([^/]+)\/messages\/@original$/u.exec(call.method)?.[1];
return {
id: (call.response as { readonly id: string }).id,
links: linkTargets((call.body as { readonly components?: unknown }).components),
onlyPerson:
+ (token !== undefined && ephemeralTokens.has(token)) ||
(((call.body as { readonly flags?: number }).flags ?? 0) & EPHEMERAL_FLAG) !== 0,
options: choicesOf(call),
text: (call.body as { readonly content?: string }).content ?? "",
};
},
+ shownReply(body) {
+ // A message answering an interaction; with the ephemeral flag, only the presser sees it.
+ const reply = body as {
+ readonly data?: {
+ readonly components?: unknown;
+ readonly content?: string;
+ readonly flags?: number;
+ };
+ readonly type?: number;
+ };
+ if (reply.type !== 4 || reply.data === undefined) return undefined;
+ return {
+ id: "",
+ links: linkTargets(reply.data.components),
+ onlyPerson: ((reply.data.flags ?? 0) & 64) !== 0,
+ options: [],
+ text: reply.data.content ?? "",
+ };
+ },
personShownAs: [`<@${PERSON.id}>`, PERSON.username],
press(option, person: Person) {
const handle = option.handle as PressHandle;
const id = nextInteraction();
- // A component interaction's `@original` response is the message holding the component.
- originals.set(`tok-${id}`, handle.messageId);
+ if (handle.customId.startsWith("eve_auth:")) {
+ // eve answers a sign-in press with an ephemeral deferred response, a new message.
+ ephemeralTokens.add(`tok-${id}`);
+ } else {
+ // A component interaction's `@original` response is the message holding the component.
+ originals.set(`tok-${id}`, handle.messageId);
+ }
return signed(
JSON.stringify({
application_id: "APP1",
diff --git a/packages/eve/src/public/channels/discord/authorization.ts b/packages/eve/src/public/channels/discord/authorization.ts
new file mode 100644
index 000000000..e9f9aadf5
--- /dev/null
+++ b/packages/eve/src/public/channels/discord/authorization.ts
@@ -0,0 +1,172 @@
+/**
+ * Discord connection sign-ins. A sign-in link is a credential: whoever
+ * completes it binds their account to the person who asked. In a DM the bot
+ * posts the link directly. In a server the shared message carries no link or
+ * code, only a button, and eve answers its press with an ephemeral message
+ * that shows the challenge to the presser alone, and only when the presser is
+ * the person who must sign in.
+ */
+
+import { createHash } from "node:crypto";
+
+import { attemptKey, findPendingAuthorization } from "#channel/pending-authorization.js";
+import type { Session } from "#channel/session.js";
+import type { SessionAuthContext } from "#channel/types.js";
+import { createLogger } from "#internal/logging.js";
+import type {
+ AuthorizationCompletedStreamEvent,
+ AuthorizationRequiredStreamEvent,
+} from "#protocol/message.js";
+import type { DiscordMessageBody } from "#public/channels/discord/api.js";
+import { DISCORD_COMPONENT_TYPE } from "#public/channels/discord/hitl.js";
+import { displayProperName } from "#shared/display-name.js";
+
+const log = createLogger("discord.authorization");
+
+type AuthorizationRequired = AuthorizationRequiredStreamEvent["data"];
+type AuthorizationCompleted = AuthorizationCompletedStreamEvent["data"];
+
+/** Custom id prefix of the shared sign-in message's button. */
+export const DISCORD_AUTHORIZATION_CUSTOM_ID_PREFIX = "eve_auth:";
+
+const LINK_BUTTON_STYLE = 5;
+const PRIMARY_BUTTON_STYLE = 1;
+const NOT_YOURS = "Only the person who needs to sign in can open this sign-in.";
+
+/** The sign-in attempt a shared message's button names, as an opaque digest. */
+export interface DiscordAuthorizationReveal {
+ readonly attempt: string;
+}
+
+function displayNameOf(event: {
+ readonly authorization?: { readonly displayName?: string };
+ readonly name: string;
+}): string {
+ return event.authorization?.displayName ?? displayProperName(event.name);
+}
+
+/** The full sign-in, link and code included, for the person signing in alone. */
+export function renderDiscordAuthorizationPrompt(event: AuthorizationRequired): DiscordMessageBody {
+ const displayName = displayNameOf(event);
+ const url = event.authorization?.url;
+ const userCode = event.authorization?.userCode;
+ const content = [
+ `Sign in to ${displayName} to continue.`,
+ event.authorization?.instructions,
+ userCode ? `If ${displayName} asks for a confirmation code, enter ${userCode}.` : undefined,
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+ if (!url) return { content };
+ return {
+ components: [
+ {
+ components: [
+ {
+ label: `Sign in to ${displayName}`,
+ style: LINK_BUTTON_STYLE,
+ type: DISCORD_COMPONENT_TYPE.BUTTON,
+ url,
+ },
+ ],
+ type: DISCORD_COMPONENT_TYPE.ACTION_ROW,
+ },
+ ],
+ content,
+ };
+}
+
+/** The shared sign-in message: who must sign in, and a button that shows them the challenge. */
+export function renderDiscordAuthorizationStatus(event: AuthorizationRequired): DiscordMessageBody {
+ const userId = discordUserIdOf(event.principalId);
+ const who = userId ? `<@${userId}> needs` : "Someone needs";
+ return {
+ components: [
+ {
+ components: [
+ {
+ custom_id: authorizationCustomId(event),
+ label: "Sign in",
+ style: PRIMARY_BUTTON_STYLE,
+ type: DISCORD_COMPONENT_TYPE.BUTTON,
+ },
+ ],
+ type: DISCORD_COMPONENT_TYPE.ACTION_ROW,
+ },
+ ],
+ content: `${who} to sign in to ${displayNameOf(event)} to continue. Only they can open the sign-in.`,
+ };
+}
+
+/** What a sign-in's message says once it settles. */
+export function renderDiscordAuthorizationCompleted(event: AuthorizationCompleted): string {
+ const displayName = displayNameOf(event);
+ if (event.outcome === "authorized") return `${displayName} connected.`;
+ const reason = event.reason === undefined ? "" : ` (${event.reason})`;
+ return `${displayName} sign-in ${event.outcome}${reason}.`;
+}
+
+/** Reads the sign-in attempt a button names, or `null` for any other component. */
+export function readDiscordAuthorizationReveal(
+ customId: string,
+): DiscordAuthorizationReveal | null {
+ if (!customId.startsWith(DISCORD_AUTHORIZATION_CUSTOM_ID_PREFIX)) return null;
+ const attempt = customId.slice(DISCORD_AUTHORIZATION_CUSTOM_ID_PREFIX.length);
+ return attempt ? { attempt } : null;
+}
+
+/**
+ * Answers a press of the shared message's button with an ephemeral message.
+ * The challenge comes from the session's own stream and goes back only when
+ * the presser's principal is the one that must sign in; nothing the button
+ * carries is trusted for identity.
+ */
+export async function answerDiscordAuthorizationReveal(input: {
+ readonly auth: SessionAuthContext | null;
+ readonly resolveSession: () => Promise<Session | undefined>;
+ readonly reveal: DiscordAuthorizationReveal;
+}): Promise<DiscordMessageBody> {
+ if (input.auth === null) return { content: NOT_YOURS };
+ let event: AuthorizationRequired | undefined;
+ try {
+ const session = await input.resolveSession();
+ event =
+ session &&
+ (await findPendingAuthorization(
+ session,
+ (candidate) => attemptDigest(candidate) === input.reveal.attempt,
+ ));
+ } catch (error) {
+ log.error("Discord sign-in lookup failed", { error });
+ }
+ if (event === undefined) return { content: "This sign-in is no longer active." };
+ if (input.auth.principalId !== event.principalId) return { content: NOT_YOURS };
+ return renderDiscordAuthorizationPrompt(event);
+}
+
+function authorizationCustomId(event: AuthorizationRequired): string {
+ return `${DISCORD_AUTHORIZATION_CUSTOM_ID_PREFIX}${attemptDigest(event)}`;
+}
+
+/**
+ * A fixed-length digest of one sign-in attempt. Connection names can be long
+ * enough to overflow Discord's 100-character `custom_id`, and a digest never
+ * needs truncating, so the button always names its exact attempt.
+ */
+function attemptDigest(event: { readonly attemptId?: string; readonly name: string }): string {
+ return createHash("sha256").update(attemptKey(event)).digest("base64url").slice(0, 32);
+}
+
+/** The key a channel's state tracks one sign-in attempt's message under. */
+export function discordAuthorizationMessageKey(event: {
+ readonly attemptId?: string;
+ readonly name: string;
+}): string {
+ return attemptDigest(event);
+}
+
+/** The Discord user behind a default principal (`discord:<userId>`), when it is one. */
+function discordUserIdOf(principalId: string | undefined): string | undefined {
+ const match = /^discord:(\d+)$/u.exec(principalId ?? "");
+ return match?.[1];
+}
diff --git a/packages/eve/src/public/channels/discord/defaults.ts b/packages/eve/src/public/channels/discord/defaults.ts
index 81194b7a5..15e800679 100644
--- a/packages/eve/src/public/channels/discord/defaults.ts
+++ b/packages/eve/src/public/channels/discord/defaults.ts
@@ -4,6 +4,7 @@ import { resolvedPromptLabel } from "#channel/resolved-prompt.js";
import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";
import {
DISCORD_MESSAGE_CONTENT_MAX_LENGTH,
+ DISCORD_NO_MENTIONS,
splitDiscordMessageContent,
} from "#public/channels/discord/api.js";
import type {
@@ -16,6 +17,12 @@ import type {
DiscordMessageResult,
} from "#public/channels/discord/messages.js";
import { renderInputRequestComponents } from "#public/channels/discord/hitl.js";
+import {
+ discordAuthorizationMessageKey,
+ renderDiscordAuthorizationCompleted,
+ renderDiscordAuthorizationPrompt,
+ renderDiscordAuthorizationStatus,
+} from "#public/channels/discord/authorization.js";
import type {
DiscordChannelEvents,
DiscordCommandResult,
@@ -96,13 +103,26 @@ export async function editDiscordResolvedPrompt(
label: string,
): Promise<void> {
const content = `${prompt.content}\n\n${label}`.slice(0, DISCORD_MESSAGE_CONTENT_MAX_LENGTH);
+ await editDiscordMessage(discord, prompt.messageId, content);
+}
+
+/**
+ * Rewrites one of the bot's messages in the current channel to `content` and
+ * removes its components. Throws when Discord refuses the edit.
+ */
+async function editDiscordMessage(
+ discord: Pick<DiscordHandle, "channelId" | "request">,
+ messageId: string,
+ content: string,
+): Promise<void> {
+ // A raw request skips the API helpers' default, so suppress pings here.
const response = await discord.request(
- `/channels/${encodeURIComponent(discord.channelId)}/messages/${encodeURIComponent(prompt.messageId)}`,
- { components: [], content },
+ `/channels/${encodeURIComponent(discord.channelId)}/messages/${encodeURIComponent(messageId)}`,
+ { allowed_mentions: DISCORD_NO_MENTIONS, components: [], content },
{ botAuth: true, method: "PATCH" },
);
if (!response.ok) {
- throw new Error(`Discord prompt edit failed with HTTP ${response.status}.`);
+ throw new Error(`Discord message edit failed with HTTP ${response.status}.`);
}
}
@@ -120,10 +140,44 @@ export const defaultEvents: DiscordChannelEvents = {
await channel.discord.startTyping();
},
+ // In a 1:1 DM the person signing in is the only one there, so the link goes in the open.
+ // Anywhere else, including group DMs and proactive sessions, the button keeps it private.
+ async "authorization.required"(event, channel, _ctx) {
+ const message =
+ channel.state.directMessage === true
+ ? renderDiscordAuthorizationPrompt(event)
+ : renderDiscordAuthorizationStatus(event);
+ try {
+ const posted = await channel.discord.post(message);
+ if (posted.id) {
+ channel.state.pendingAuthMessageIds = {
+ ...channel.state.pendingAuthMessageIds,
+ [discordAuthorizationMessageKey(event)]: posted.id,
+ };
+ }
+ } catch (error) {
+ log.error("Discord sign-in delivery failed", { error, name: event.name });
+ }
+ },
+
async "authorization.completed"(event, channel, _ctx) {
if (event.outcome === "authorized") {
await channel.discord.startTyping();
}
+ const key = discordAuthorizationMessageKey(event);
+ const messageId = channel.state.pendingAuthMessageIds?.[key];
+ if (messageId === undefined) return;
+ const { [key]: _, ...rest } = channel.state.pendingAuthMessageIds ?? {};
+ channel.state.pendingAuthMessageIds = rest;
+ try {
+ await editDiscordMessage(
+ channel.discord,
+ messageId,
+ renderDiscordAuthorizationCompleted(event),
+ );
+ } catch (error) {
+ log.warn("Discord sign-in edit failed", { error, name: event.name });
+ }
},
async "actions.requested"(_event, channel, _ctx) {
diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.ts
index 6eba84b5f..f8eb9a4c3 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts
@@ -402,7 +402,11 @@ describe("discordChannel() inbound route", () => {
};
};
const prompt = {
- body: { components: [], content: "Approve?\n\nNo longer active" },
+ body: {
+ allowed_mentions: { parse: [] },
+ components: [],
+ content: "Approve?\n\nNo longer active",
+ },
method: "PATCH",
url: "https://discord.com/api/v10/channels/C01/messages/M01",
};
@@ -678,6 +682,61 @@ describe("discordChannel() default event handlers", () => {
]);
});
+ it.each([
+ {
+ name: "a 1:1 DM shows the link in the open",
+ where: { audience: "private", directMessage: true },
+ link: true,
+ },
+ {
+ name: "a group DM keeps the link behind a button",
+ where: { audience: "private" },
+ link: false,
+ },
+ {
+ name: "a session with no known audience keeps the link behind a button",
+ where: {},
+ link: false,
+ },
+ ])("posting a sign-in: $name", async ({ where, link }) => {
+ const fetchMock = vi.fn<typeof fetch>(async () =>
+ Response.json({ channel_id: "C01", id: "M01" }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const adapter = withState(
+ getAdapter(discordChannel({ credentials: { applicationId: "APP1", botToken: "bot-token" } })),
+ {
+ ...where,
+ applicationId: "APP1",
+ channelId: "C01",
+ conversationId: "M00",
+ guildId: null,
+ hasMessageAnchor: true,
+ initialResponseSent: true,
+ interactionToken: null,
+ },
+ );
+
+ await callEvent(
+ adapter,
+ makeEvent("authorization.required", {
+ authorization: { url: "https://calendar.example/sign-in", userCode: "ABCD-1234" },
+ description: "Sign in to Calendar",
+ name: "calendar",
+ principalId: "discord:123",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ buildAdapterContext(adapter, captureAccessor("discord:C01:M00").accessor),
+ );
+
+ const posted = String(fetchMock.mock.calls[0]![1]!.body);
+ expect(posted.includes("https://calendar.example/sign-in")).toBe(link);
+ expect(posted.includes("ABCD-1234")).toBe(link);
+ expect(posted.includes('"label":"Sign in"')).toBe(!link);
+ });
+
it("receive starts a proactive channel session", async () => {
const channel = discordChannel({ credentials: { botToken: "bot-token" } });
const send = vi.fn().mockResolvedValue({ id: "s1" });
diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.ts
index 063641e86..5c112a5ee 100644
--- a/packages/eve/src/public/channels/discord/discordChannel.ts
+++ b/packages/eve/src/public/channels/discord/discordChannel.ts
@@ -1,6 +1,6 @@
import type { DiscordInstrumentationMetadata } from "#public/channels/discord/index.js";
import type { SessionHistoryMessage } from "#shared/session-history.js";
-import type { ChannelFrom } from "#channel/channel-operations.js";
+import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
import {
INACTIVE_REQUEST_NOTICE,
respondOrRetireInactivePrompt,
@@ -38,6 +38,11 @@ import {
buildFreeformModalResponse,
isDiscordFreeformComponent,
} from "#public/channels/discord/hitl.js";
+import {
+ answerDiscordAuthorizationReveal,
+ readDiscordAuthorizationReveal,
+ type DiscordAuthorizationReveal,
+} from "#public/channels/discord/authorization.js";
import {
commandInteractionMessage,
DISCORD_EPHEMERAL_MESSAGE_FLAG,
@@ -114,6 +119,10 @@ export interface DiscordChannelState {
hasMessageAnchor: boolean;
/** Posted prompts with components, keyed by requestId, until eve resolves them. */
hitlPrompts?: Record<string, DiscordHitlPrompt>;
+ /** Each pending sign-in's message, keyed by sign-in attempt, until the sign-in settles. */
+ pendingAuthMessageIds?: Record<string, string>;
+ /** Whether the conversation is a 1:1 DM with the bot, where nobody else can see a sign-in. */
+ directMessage?: boolean;
}
/** What a posted prompt needs so its message can be edited once eve resolves it. */
@@ -309,7 +318,7 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanne
routes: [
POST<DiscordChannelState>(
config.route ?? "/eve/v1/discord",
- async (req, { from, waitUntil }) => {
+ async (req, { from, resolveSession, waitUntil }) => {
const body = await verifyDiscordInbound(req, config.credentials);
if (body === null) return new Response("unauthorized", { status: 401 });
@@ -336,6 +345,7 @@ export function discordChannel(config: DiscordChannelConfig = {}): DiscordChanne
onCommand,
onInputResponse,
from,
+ resolveSession,
waitUntil,
});
},
@@ -567,8 +577,15 @@ async function handleInteraction(input: {
readonly onCommand: NonNullable<DiscordChannelConfig["onCommand"]>;
readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
readonly from: ChannelFrom<DiscordChannelState>;
+ readonly resolveSession: ChannelResolveSession;
readonly waitUntil: (task: Promise<unknown>) => void;
}): Promise<Response> {
+ if (input.interaction.type === DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT) {
+ const reveal = readDiscordAuthorizationReveal(input.interaction.customId);
+ if (reveal !== null) {
+ return revealAuthorization({ ...input, interaction: input.interaction, reveal });
+ }
+ }
if (input.interaction.type === DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND) {
return handleCommandInteraction({
config: input.config,
@@ -634,6 +651,63 @@ async function handleCommandInteraction(input: {
return discordDeferredJson(result.ephemeral === true);
}
+/**
+ * Answers a sign-in button press with an ephemeral message, identifying the
+ * presser the same way a HITL press does. Finding the sign-in reads the
+ * session's stream, so the press is acknowledged first, as an ephemeral
+ * deferred response, to stay inside Discord's 3-second deadline.
+ */
+function revealAuthorization(input: {
+ readonly config: DiscordChannelConfig;
+ readonly interaction: DiscordComponentInteraction;
+ readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
+ readonly resolveSession: ChannelResolveSession;
+ readonly reveal: DiscordAuthorizationReveal;
+ readonly waitUntil: (task: Promise<unknown>) => void;
+}): Response {
+ input.waitUntil(answerRevealedAuthorization(input));
+ return discordDeferredJson(true);
+}
+
+async function answerRevealedAuthorization(input: {
+ readonly config: DiscordChannelConfig;
+ readonly interaction: DiscordComponentInteraction;
+ readonly onInputResponse: NonNullable<DiscordChannelConfig["onInputResponse"]>;
+ readonly resolveSession: ChannelResolveSession;
+ readonly reveal: DiscordAuthorizationReveal;
+}): Promise<void> {
+ const { interaction } = input;
+ const state = stateFromInteraction(interaction, {
+ conversationId: interaction.messageId,
+ hasMessageAnchor: true,
+ initialResponseSent: false,
+ });
+ const discord = buildDiscordHandle({ config: input.config, state });
+ let auth: SessionAuthContext | null = null;
+ try {
+ const result = await input.onInputResponse(
+ { defaultAuth: defaultDiscordAuth(interaction), discord },
+ interaction,
+ );
+ auth = result?.auth ?? null;
+ } catch (error) {
+ log.error("Discord sign-in press authorization failed", { error });
+ }
+ const body = await answerDiscordAuthorizationReveal({
+ auth,
+ // The sign-in message is one of the session's addresses, as every bot post is.
+ resolveSession: () =>
+ input.resolveSession(discordContinuationToken(interaction.channelId, interaction.messageId)),
+ reveal: input.reveal,
+ });
+ try {
+ // Fills in the ephemeral deferred response, so only the presser sees it.
+ await discord.editOriginalResponse(body);
+ } catch (error) {
+ log.error("Discord sign-in reply failed", { error });
+ }
+}
+
function handleComponentInteraction(input: {
readonly config: DiscordChannelConfig;
readonly interaction: DiscordComponentInteraction;
@@ -815,6 +889,7 @@ function stateFromInteraction(
): DiscordChannelState {
return {
audience: discordAudience(interaction.channelType),
+ directMessage: interaction.channelType === 1,
applicationId: interaction.applicationId,
channelId: interaction.channelId,
conversationId: options.conversationId,
diff --git a/packages/eve/src/public/channels/discord/messages.ts b/packages/eve/src/public/channels/discord/messages.ts
index 5c69d6ee7..fa5791adb 100644
--- a/packages/eve/src/public/channels/discord/messages.ts
+++ b/packages/eve/src/public/channels/discord/messages.ts
@@ -220,7 +220,11 @@ export function createDiscordGatewayRoute(input: {
initialResponseSent: true,
interactionToken: null,
};
- if (isDirectMessage) state.audience = discordAudience(1);
+ // Bots receive only 1:1 DMs over the Gateway, never group DMs.
+ if (isDirectMessage) {
+ state.audience = discordAudience(1);
+ state.directMessage = true;
+ }
let result: DiscordMessageResult;
try {