Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): deliver Chat SDK shared-thread sign-ins privately (#4429)

Ben Pankow83b97e616c11
diff --git a/.changeset/chat-sdk-private-sign-in.md b/.changeset/chat-sdk-private-sign-in.md
new file mode 100644
index 000000000..816be0125
--- /dev/null
+++ b/.changeset/chat-sdk-private-sign-in.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Chat SDK channels now send a sign-in started in a shared thread to the person signing in, as an ephemeral message or a direct message, and show a link-free status in the thread. Adapters that support neither still post the existing "continue in a direct message" notice.
diff --git a/docs/channels/chat-sdk.mdx b/docs/channels/chat-sdk.mdx
index a7f714fa8..3a0b64c9e 100644
--- a/docs/channels/chat-sdk.mdx
+++ b/docs/channels/chat-sdk.mdx
@@ -195,6 +195,33 @@ chatSdkChannel({
});
```
+### Sign-ins
+
+When a tool needs a connection the person hasn't authorized, eve shows a sign-in prompt with the connection's link, code, or instructions. In a direct message it posts the prompt in the thread and edits it once the sign-in completes.
+
+Outside a direct message, the prompt is a credential, so eve sends it only to the person signing in. It uses the adapter's native ephemeral message where there is one and otherwise opens a direct message with them. The thread gets a status without the link, which eve edits once the sign-in completes.
+
+To find that person, eve matches the turn's `auth` principal to the author of the message you passed to `send`. Private delivery therefore needs both:
+
+- per-person `auth` on each `send`, so a principal names one person; and
+- the handler's `Thread` object as `thread`, rather than a thread id string, so eve sees who wrote the message.
+
+```ts
+bot.onSubscribedMessage(async (thread, message) => {
+ await send(message.text, {
+ thread,
+ auth: {
+ authenticator: "slack",
+ principalType: "user",
+ principalId: message.author.userId,
+ attributes: {},
+ },
+ });
+});
+```
+
+Without both, including with the default `auth: null`, the thread only gets a notice to continue in a direct message, and the prompt isn't shown anywhere. The same happens when several people send as one principal (such as tenant auth), or when the adapter has neither ephemerals nor `openDM`.
+
### Proactive sessions
Start a session without an inbound webhook through `to(channel, target).send(message, { auth })` from a schedule `run` handler, or `ctx.to(channel, target).send(message, { auth })` from another channel. The target is a serialized Chat SDK thread, or `{ threadId, adapterName }` when you only have a provider-native thread id:
diff --git a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
index 2a911240c..a31ea3bb2 100644
--- a/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
+++ b/packages/eve/src/internal/testing/channel-conformance/MATRIX.md
@@ -67,14 +67,14 @@ 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` | `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>[11](#note-11)</sup> | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ❌<sup>[12](#note-12)</sup> | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[13](#note-13)</sup> | ✅ | ✅ | ✅ |
-| a sign-in shows its confirmation code | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ❌<sup>[12](#note-12)</sup> | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[13](#note-13)</sup> | ✅ | ✅ | ✅ |
+| a sign-in names the service and shows its sign-in link | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[13](#note-13)</sup> | ✅ | ✅ | ✅ |
+| a sign-in shows its confirmation code | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | —<sup>[13](#note-13)</sup> | ✅ | ✅ | ✅ |
| only the person signing in sees the sign-in link and code | —<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>[14](#note-14)</sup> | ✅ | —<sup>[14](#note-14)</sup> | ❌<sup>[15](#note-15)</sup> | —<sup>[14](#note-14)</sup> | ✅ | —<sup>[14](#note-14)</sup> | ✅ | ❌<sup>[16](#note-16)</sup> | —<sup>[14](#note-14)</sup> | —<sup>[14](#note-14)</sup> |
-| a sign-in without a link shows its instructions | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ❌<sup>[12](#note-12)</sup> | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ |
+| a sign-in without a link shows its instructions | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ❌<sup>[11](#note-11)</sup> | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[11](#note-11)</sup> | ✅ | ✅ | ✅ |
| after signing in, the agent carries on with the request | ✅ | ✅ | ✅ | | ✅ | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | | ✅ | ✅ | ✅ | ✅ |
-| completing a sign-in tells the person it succeeded | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌<sup>[12](#note-12)</sup> | ✅ | ✅ | ✅ |
+| 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>[12](#note-12)</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> |
@@ -102,8 +102,8 @@ pnpm --filter eve exec vitest run --config vitest.unit.config.ts channel-conform
8. <a id="note-8"></a>one person answers in their own browser tab; there's nobody else to tell
9. <a id="note-9"></a>a resolved prompt doesn't say who answered; input.resolved carries no responder
10. <a id="note-10"></a>the card loses its buttons after a typed approval but doesn't say who approved
-11. <a id="note-11"></a>outside a DM the bot says to continue in a direct message but never sends one
-12. <a id="note-12"></a>the channel has no default sign-in renderer
+11. <a id="note-11"></a>the channel has no default sign-in renderer
+12. <a id="note-12"></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
13. <a id="note-13"></a>the rule applies only where the conversation is shared or private, and this one is public
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
diff --git a/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts
index 8d591e8cf..59e787371 100644
--- a/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/chat-sdk-driver.ts
@@ -115,6 +115,7 @@ export function chatSdkDriver(surface: Exclude<Surface, "public"> = "shared"): C
return {
id: messageIdOf(call),
links: linkTargets(card),
+ onlyPerson: isPersonDirectMessage(call),
options: buttonsOf(call),
text: card === undefined ? (driver.postedText(call) ?? "") : texts(card),
};
@@ -268,6 +269,14 @@ function isPost(call: PlatformCall): boolean {
return call.method === "postMessage" || call.method === "editMessage";
}
+/** The DM thread the bot opens with the person, beside the conversation's own thread. */
+const PERSON_DM_THREAD = `${ADAPTER}:direct-message:${PERSON.userId}`;
+
+function isPersonDirectMessage(call: PlatformCall): boolean {
+ const { threadId } = call.response as { readonly threadId?: string };
+ return threadId === PERSON_DM_THREAD;
+}
+
function fakeAdapter({
dm,
nextId,
@@ -348,13 +357,27 @@ function fakeAdapter({
isDM: dm,
metadata: {},
}),
+ // No native ephemerals, as on Discord or Linq: `postEphemeral` falls back to a DM.
+ // Only the person signing in can be reached, so a sign-in sent to anyone else fails its cells.
+ async openDM(userId: string) {
+ if (userId !== PERSON.userId) throw new Error(`no direct message with ${userId}`);
+ return PERSON_DM_THREAD;
+ },
async postMessage(id: string, posted: AdapterPostableMessage) {
const messageId = `posted-${nextId()}`;
- record({ body: render(posted), method: "postMessage", response: { id: messageId } });
+ record({
+ body: render(posted),
+ method: "postMessage",
+ response: { id: messageId, threadId: id },
+ });
return { id: messageId, raw: posted, threadId: id };
},
async editMessage(id: string, messageId: string, posted: AdapterPostableMessage) {
- record({ body: render(posted), method: "editMessage", response: { id: messageId } });
+ record({
+ body: render(posted),
+ method: "editMessage",
+ response: { id: messageId, threadId: id },
+ });
return { id: messageId, raw: posted, threadId: id };
},
async addReaction() {},
diff --git a/packages/eve/src/internal/testing/channel-conformance/conformance.ts b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
index 4808cf5c7..10a894dac 100644
--- a/packages/eve/src/internal/testing/channel-conformance/conformance.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/conformance.ts
@@ -129,8 +129,11 @@ function noSignInRenderer(
);
}
-/** Chat SDK's default sign-in, outside a DM, points the person at a DM it never sends. */
-const SIGN_IN_ONLY_IN_DMS = Object.fromEntries(
+/**
+ * Linq's group sign-in can't reach the person privately: its `openDM` needs a phone
+ * handle, and a message names its sender only by the handle's opaque id.
+ */
+const LINQ_SIGN_IN_NOT_PRIVATE = Object.fromEntries(
[
"a sign-in names the service and shows its sign-in link",
"a sign-in shows its confirmation code",
@@ -138,7 +141,8 @@ const SIGN_IN_ONLY_IN_DMS = Object.fromEntries(
].map((rule) => [
rule,
{
- reason: "outside a DM the bot says to continue in a direct message but never sends one",
+ reason:
+ "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",
symptom: SIGN_IN_NOT_SHOWN,
},
]),
@@ -231,10 +235,7 @@ const WEB_CHAT_SINGLE_PERSON =
* failure (such as harness breakage) both turn it red.
*/
const channelConformance = {
- "chat-sdk": [
- { driver: chatSdkDriver, broken: { ...CHAT_SDK_BROKEN, ...SIGN_IN_ONLY_IN_DMS } },
- { driver: chatSdkTextDriver },
- ],
+ "chat-sdk": [{ driver: chatSdkDriver, broken: CHAT_SDK_BROKEN }, { driver: chatSdkTextDriver }],
"chat-sdk-dm": [{ dm: true, driver: () => chatSdkDriver("private"), broken: CHAT_SDK_BROKEN }],
discord: [{ driver: discordDriver, broken: DISCORD_BROKEN, unsupported: DISCORD_UNSUPPORTED }],
"discord-dm": [
@@ -269,7 +270,7 @@ const channelConformance = {
},
},
],
- linq: [{ driver: linqDriver, broken: SIGN_IN_ONLY_IN_DMS }],
+ linq: [{ driver: linqDriver, broken: LINQ_SIGN_IN_NOT_PRIVATE }],
"linq-dm": [{ dm: true, driver: () => linqDriver("private") }],
photon: [{ driver: photonDriver }],
slack: [{ driver: slackDriver, broken: SLACK_BROKEN }],
diff --git a/packages/eve/src/internal/testing/channel-conformance/linq-driver.ts b/packages/eve/src/internal/testing/channel-conformance/linq-driver.ts
index 398d3394e..8c25cc782 100644
--- a/packages/eve/src/internal/testing/channel-conformance/linq-driver.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/linq-driver.ts
@@ -17,7 +17,8 @@ const SIGNING_SECRET = `whsec_${SIGNING_KEY.toString("base64")}`;
const BASE_URL = "https://linq-conformance.invalid/api/partner";
// Stands in for cdn.linqapp.com; `.invalid` never resolves, so nothing that bypasses the fake reaches the network.
const CDN_HOST = "cdn.linq-conformance.invalid";
-const PERSON = "alice";
+// As on Linq, a handle's `id` is opaque; only `handle`, a phone number or email, can be messaged.
+const PERSON = { handle: "+15550100", id: "handle-alice" };
let nextChat = 0;
interface LinqPart {
@@ -64,7 +65,7 @@ export function linqDriver(surface: Exclude<Surface, "public"> = "shared"): Chan
direction: "inbound",
id: `linq-inbound-${messageId}`,
parts: [{ type: "text", value: text }, ...media],
- sender_handle: { handle: PERSON, id: PERSON, is_me: false },
+ sender_handle: { ...PERSON, is_me: false },
},
event_type: "message.received",
});
@@ -101,10 +102,20 @@ export function linqDriver(surface: Exclude<Surface, "public"> = "shared"): Chan
};
}
const bodyText = await request.text();
+ const body = bodyText === "" ? {} : (JSON.parse(bodyText) as { readonly to?: unknown });
+ // Starting a chat (`messages.create`) needs a handle Linq can reach.
+ if (Array.isArray(body.to) && body.to.some((to) => to !== PERSON.handle)) {
+ return {
+ body,
+ // Never delivered, so no reader takes it for a sent message.
+ method: `${request.method} ${url.pathname} (rejected)`,
+ response: Response.json({ error: "invalid recipient" }, { status: 400 }),
+ };
+ }
outbound += 1;
const id = `linq-outbound-${outbound}`;
return {
- body: bodyText === "" ? {} : JSON.parse(bodyText),
+ body,
method: `${request.method} ${url.pathname}`,
// The adapter reads the sent or edited message's id back to edit it later.
response: { chat_id: chatId, id, message: { id } },
diff --git a/packages/eve/src/public/channels/chat-sdk/authorization.ts b/packages/eve/src/public/channels/chat-sdk/authorization.ts
index 04957085f..d3c1a45cc 100644
--- a/packages/eve/src/public/channels/chat-sdk/authorization.ts
+++ b/packages/eve/src/public/channels/chat-sdk/authorization.ts
@@ -1,7 +1,10 @@
import type { Thread } from "#compiled/chat/index.js";
+import { createLogger, logError } from "#internal/logging.js";
import { isNotImplemented } from "#public/channels/chat-sdk/notImplemented.js";
import type { ChatSdkChannelEvents } from "#public/channels/chat-sdk/chatSdkChannel.js";
+const log = createLogger("chat-sdk.authorization");
+
/** Built-in connection authorization handlers for Chat SDK threads. */
export function defaultAuthorizationEvents(): Pick<
ChatSdkChannelEvents,
@@ -14,14 +17,25 @@ export function defaultAuthorizationEvents(): Pick<
if (pending[event.name] !== undefined) return;
const displayName = authorizationDisplayName(event.name, event.authorization?.displayName);
- const message = channel.thread.isDM
- ? authorizationPrompt({
- displayName,
- instructions: event.authorization?.instructions,
- url: event.authorization?.url,
- userCode: event.authorization?.userCode,
- })
- : `Authorization required for ${displayName}. Continue in a direct message with this agent.`;
+ const prompt = authorizationPrompt({
+ displayName,
+ instructions: event.authorization?.instructions,
+ url: event.authorization?.url,
+ userCode: event.authorization?.userCode,
+ });
+ // Outside a DM the challenge is a credential: it goes only to the person signing in,
+ // and the thread sees a link-free status the completion handler can edit.
+ let message = prompt;
+ if (!channel.thread.isDM) {
+ const userId =
+ event.principalId === undefined
+ ? undefined
+ : channel.state.usersByPrincipal?.[event.principalId];
+ message =
+ typeof userId === "string" && (await postPrivately(channel.thread, userId, prompt))
+ ? `Authorization required for ${displayName}. I sent you the sign-in details privately.`
+ : `Authorization required for ${displayName}. Continue in a direct message with this agent.`;
+ }
const posted = await channel.thread.post({ markdown: message });
if (posted.id) {
channel.state.pendingAuthMessageIds = { ...pending, [event.name]: posted.id };
@@ -55,6 +69,21 @@ export function defaultAuthorizationEvents(): Pick<
};
}
+/**
+ * Shows `markdown` to `userId` alone: natively where the adapter can, else in a
+ * DM. False when the adapter can do neither or the send fails.
+ */
+async function postPrivately(thread: Thread, userId: string, markdown: string): Promise<boolean> {
+ try {
+ return (await thread.postEphemeral(userId, { markdown }, { fallbackToDM: true })) !== null;
+ } catch (error) {
+ if (!isNotImplemented(error)) {
+ logError(log, "failed to deliver sign-in privately", error, { threadId: thread.id });
+ }
+ return false;
+ }
+}
+
async function safeStartTyping(thread: Thread, status: string): Promise<void> {
try {
await thread.startTyping(status);
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
index 855ea8609..7b60cbb24 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts
@@ -21,6 +21,7 @@ import type {
AdapterPostableMessage,
Attachment,
ChatInstance,
+ EphemeralMessage,
FetchResult,
FormattedContent,
MessageMetadata,
@@ -515,6 +516,117 @@ describe("chatSdkChannel", () => {
]);
});
+ describe("a sign-in outside a direct message", () => {
+ const signIn = makeEvent("authorization.required", {
+ authorization: { url: "https://connect.example.com/a/sca_1", userCode: "ABC-123" },
+ name: "notion",
+ principalId: AUTH.principalId,
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn-1",
+ });
+ const PRIVATE_STATUS =
+ "Authorization required for Notion. I sent you the sign-in details privately.";
+ const DM_NOTICE =
+ "Authorization required for Notion. Continue in a direct message with this agent.";
+ const alice = author();
+ const bob = { ...author(), fullName: "Bob", userId: "user-2", userName: "bob" };
+
+ /** Delivers a message from `from`, sent as `caller`, then raises the sign-in. */
+ async function signInAfter(
+ adapter: TestAdapter & Adapter,
+ messages: ReadonlyArray<{
+ readonly caller: typeof AUTH | null;
+ readonly from?: Message["author"];
+ }>,
+ ) {
+ const bridge = chatSdkChannel({
+ adapters: { test: adapter },
+ state: memoryState(),
+ userName: "bot",
+ });
+ const state: ChatSdkChannelState = { thread: serializedThread() };
+ const channelAdapter = withState(getAdapter(bridge.channel), state);
+ const ctx = buildAdapterContext(channelAdapter, stubAccessor());
+ for (const { caller, from } of messages) {
+ const currentMessage = from === undefined ? undefined : message("hi", from).toJSON();
+ await channelAdapter.deliver!(
+ { message: "hi", state: { thread: { ...serializedThread(), currentMessage } } },
+ { ...ctx, session: { auth: { current: caller, initiator: caller } } } as never,
+ );
+ }
+ await callEvent(channelAdapter, signIn, ctx);
+ return adapter.posted.map(({ message: posted }) => posted);
+ }
+
+ it.each([
+ {
+ name: "shows the challenge only to the person signing in",
+ postEphemeral: async () => ({
+ id: "e1",
+ threadId: THREAD_ID,
+ usedFallback: false,
+ raw: {},
+ }),
+ status: PRIVATE_STATUS,
+ },
+ {
+ name: "points at a DM when the adapter can't deliver privately",
+ postEphemeral: async () => null,
+ status: DM_NOTICE,
+ },
+ {
+ name: "points at a DM when the private delivery fails",
+ postEphemeral: async () => {
+ throw new Error("ephemeral failed");
+ },
+ status: DM_NOTICE,
+ },
+ ])("$name", async ({ postEphemeral, status }) => {
+ const adapter = testAdapter();
+ const ephemerals: Array<{ message: AdapterPostableMessage; userId: string }> = [];
+ adapter.postEphemeral = async (_threadId, userId, posted) => {
+ ephemerals.push({ message: posted, userId });
+ return postEphemeral();
+ };
+
+ const posted = await signInAfter(adapter, [{ caller: AUTH, from: alice }]);
+
+ expect(posted).toEqual([{ markdown: status }]);
+ expect(ephemerals).toEqual([
+ {
+ message: {
+ markdown:
+ "Authorization required for Notion.\n\nCode: ABC-123\n\nhttps://connect.example.com/a/sca_1",
+ },
+ userId: alice.userId,
+ },
+ ]);
+ });
+
+ it.each([
+ { name: "an anonymous sender", messages: [{ caller: null, from: alice }] },
+ { name: "a bot author", messages: [{ caller: AUTH, from: { ...alice, isBot: true } }] },
+ { name: "a send without its message", messages: [{ caller: AUTH }] },
+ {
+ name: "a principal two people send as",
+ messages: [
+ { caller: AUTH, from: alice },
+ { caller: AUTH, from: bob },
+ ],
+ },
+ ])("sends the challenge to no one after $name", async ({ messages }) => {
+ const adapter = testAdapter();
+ const ephemeral = vi.fn();
+ adapter.postEphemeral = ephemeral;
+
+ const posted = await signInAfter(adapter, messages);
+
+ expect(posted).toEqual([{ markdown: DM_NOTICE }]);
+ expect(ephemeral).not.toHaveBeenCalled();
+ });
+ });
+
it("does not throw when the adapter's startTyping is not implemented", async () => {
const adapter = testAdapter();
adapter.startTypingError = new NotImplementedError("startTyping");
@@ -1046,6 +1158,12 @@ class TestAdapter {
startTypingError: Error | null = null;
editError: Error | null = null;
rehydrateAttachment?: (attachment: Attachment) => Attachment;
+ /** Native ephemerals, when a test gives the adapter them. */
+ postEphemeral?: (
+ threadId: string,
+ userId: string,
+ message: AdapterPostableMessage,
+ ) => Promise<EphemeralMessage | null>;
async initialize(chat: ChatInstance): Promise<void> {
this.chat = chat;
@@ -1163,10 +1281,10 @@ class TestAdapter {
}
}
-function message(text: string): Message {
+function message(text: string, from: Message["author"] = author()): Message {
return new Message({
attachments: [],
- author: author(),
+ author: from,
formatted: parseMarkdown(text),
id: "message-1",
isMention: true,
diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
index 81c07aadd..02f8d7ddb 100644
--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.ts
@@ -5,7 +5,9 @@ import type {
ChannelRespondOptions,
ChannelSendOptions,
} from "#channel/channel-operations.js";
-import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import { defaultDeliverResult } from "#channel/adapter.js";
+import type { SessionHandle } from "#channel/session.js";
+import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";
import { ContextContainer, contextStorage } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { EveAttachmentError } from "#internal/attachments/errors.js";
@@ -79,6 +81,11 @@ export interface ChatSdkChannelState extends Record<string, unknown> {
pendingToolCallMessage?: string | null;
/** Authorization status messages, keyed by connection name. */
pendingAuthMessageIds?: Record<string, string>;
+ /**
+ * The Chat SDK user behind each principal that sent a message, so a sign-in
+ * reaches them privately. `null` once more than one person sent as it.
+ */
+ usersByPrincipal?: Record<string, string | null>;
/** Posted input request cards, keyed by message id, until eve resolves every request on them. */
pendingInputCards?: Record<string, ChatSdkPendingInputCard>;
streamStepIndex?: number | null;
@@ -345,6 +352,14 @@ export function chatSdkChannel<TAdapters extends ChatSdkAdapters>(
state: { thread },
});
},
+ // `session.auth.current` is the caller of this delivery.
+ deliver(
+ payload,
+ channel: ChatSdkChannelContext<TAdapters> & { readonly session: SessionHandle },
+ ) {
+ recordPrincipalUser(channel.state, channel.session.auth.current, payload);
+ return defaultDeliverResult(payload);
+ },
events: mergedEvents,
});
@@ -620,6 +635,28 @@ async function bridgeRespond<TAdapters extends ChatSdkAdapters>(
});
}
+/**
+ * Records the author of the delivery's message as the Chat SDK user behind its
+ * caller. A principal several people send as, such as tenant auth, names no one
+ * person, so it records `null` rather than whoever spoke last.
+ */
+function recordPrincipalUser(
+ state: ChatSdkChannelState,
+ caller: SessionAuthContext | null,
+ payload: DeliverPayload,
+): void {
+ if (caller === null) return;
+ const thread = (payload.state as Partial<ChatSdkChannelState> | undefined)?.thread;
+ const author = thread?.currentMessage?.author;
+ if (author === undefined || author.isBot === true || author.isMe) return;
+ const recorded = state.usersByPrincipal?.[caller.principalId];
+ if (recorded === author.userId || recorded === null) return;
+ state.usersByPrincipal = {
+ ...state.usersByPrincipal,
+ [caller.principalId]: recorded === undefined ? author.userId : null,
+ };
+}
+
function activeFrom(operation: "respond" | "send"): ChannelFrom<ChatSdkChannelState> {
const active = contextStorage.getStore()?.get(ActiveWebhookKey);
if (!active) {