Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

[2/3] feat(slack): deliver sign-ins to the event principal (#4004)

Ben Pankow8d6cd3e497c8
diff --git a/.changeset/slack-authorization-principal-recipient.md b/.changeset/slack-authorization-principal-recipient.md
new file mode 100644
index 000000000..68203db9d
--- /dev/null
+++ b/.changeset/slack-authorization-principal-recipient.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Slack now sends sign-in challenges and approval feedback privately to the Slack user behind the event's principal, not to whoever spoke last in the thread. Channel state replaces `approvalResponderUsers` and `pendingApprovalCandidateUsers` with a single `slackUsersByPrincipal` map.
diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdx
index 4f978a890..f85e50d74 100644
--- a/docs/channels/slack.mdx
+++ b/docs/channels/slack.mdx
@@ -524,12 +524,15 @@ export default slackChannel({
});
```
-Authorization prompts split public status from private credentials. A sign-in challenge (OAuth URL, device code) is a credential. Anyone who completes it binds their identity to the session's connection. The default `authorization.required` handler posts a public, link-free status in the thread, delivers the actual challenge ephemerally to the triggering user, device code included, and then updates that public status when `authorization.completed` fires. The handler receives a private-delivery context with `postEphemeral`, `postDirectMessage` (needs the `im:write` scope), and `state`. There is, intentionally, no public `post` and no raw API access.
+Authorization prompts split public status from private credentials. A sign-in challenge (OAuth URL, device code) is a credential. Anyone who completes it binds their identity to the session's connection. The default `authorization.required` handler posts a public, link-free status in the thread, delivers the actual challenge ephemerally to the Slack user behind the event's `principalId`, device code included, and then updates that public status when `authorization.completed` fires. The handler receives a private-delivery context with `postEphemeral`, `postDirectMessage` (needs the `im:write` scope), and `state`. There is, intentionally, no public `post` and no raw API access. `state.slackUsersByPrincipal` maps each principal eve has seen in the thread, through a message or an input response, to its Slack user ID. If the principal has no entry, the challenge is not sent privately.
```ts
events: {
"authorization.required"(eventData, channel) {
- const userId = channel.state.triggeringUserId;
+ const userId =
+ eventData.principalId === undefined
+ ? undefined
+ : channel.state.slackUsersByPrincipal?.[eventData.principalId];
if (!userId || !eventData.authorization?.url) return;
return channel.postDirectMessage(userId, `Sign in to continue: ${eventData.authorization.url}`);
},
diff --git a/packages/eve/src/channel/channel-address.ts b/packages/eve/src/channel/channel-address.ts
index 4d5a065c9..99af78893 100644
--- a/packages/eve/src/channel/channel-address.ts
+++ b/packages/eve/src/channel/channel-address.ts
@@ -146,6 +146,7 @@ export function createChannelAddress<TState = undefined>(input: {
context: payload.context,
message: serializeUrlFilePartsInMessage(payload.message) ?? "",
outputSchema: payload.outputSchema,
+ state: payload.state,
},
requestId: metadata.requestId,
title: options.title,
diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.ts
index c73c98734..6f59075eb 100644
--- a/packages/eve/src/channel/types.ts
+++ b/packages/eve/src/channel/types.ts
@@ -494,6 +494,8 @@ export interface RunInput {
readonly message?: string | UserContent;
readonly context?: readonly string[];
readonly outputSchema?: JsonObject;
+ /** Channel payload state for the first delivery, as later deliveries carry it. */
+ readonly state?: unknown;
};
/** Observability correlation only; never grants delegated-session privileges. */
readonly conversationId?: string;
diff --git a/packages/eve/src/execution/session/entry-authorization.integration.test.ts b/packages/eve/src/execution/session/entry-authorization.integration.test.ts
index bd9ec3861..5c540d85e 100644
--- a/packages/eve/src/execution/session/entry-authorization.integration.test.ts
+++ b/packages/eve/src/execution/session/entry-authorization.integration.test.ts
@@ -1,4 +1,12 @@
-import { describe, expect, it } from "vitest";
+import { createHmac } from "node:crypto";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createChannelOperations } from "#channel/channel-operations.js";
+import { isCompiledChannel } from "#channel/compiled-channel.js";
+import { isHttpRouteDefinition } from "#channel/routes.js";
+import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
+import { slackChannel } from "#public/channels/slack/slackChannel.js";
+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import { resumeHook, start } from "#internal/workflow/runtime.js";
import { filterEventsByType } from "#internal/testing/events.js";
import { createTestRuntime } from "#internal/testing/app-harness.js";
@@ -28,7 +36,101 @@ import {
expectSingleTurn,
} from "#internal/testing/entry-test-helpers.js";
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
describe("workflowEntry integration", () => {
+ it("sends a first-turn sign-in privately to a custom-auth Slack author", async () => {
+ const signingSecret = "first-turn-signing-secret";
+ const ephemeral: Record<string, unknown>[] = [];
+ const realFetch = globalThis.fetch;
+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(input instanceof Request ? input.url : String(input));
+ if (url.hostname !== "slack.com") return realFetch(input, init);
+ if (url.pathname.endsWith("/chat.postEphemeral")) {
+ ephemeral.push(Object.fromEntries(new URLSearchParams(String(init?.body))));
+ }
+ return Response.json({ ok: true, ts: "1700000000.000900", messages: [] });
+ });
+ const slack = slackChannel({
+ credentials: { botToken: "xoxb-test", signingSecret },
+ onDirectMessage: () => ({
+ auth: {
+ attributes: {},
+ authenticator: "employee-directory",
+ principalId: "employee:alice",
+ principalType: "user",
+ },
+ }),
+ });
+ if (!isCompiledChannel(slack)) throw new Error("Expected a compiled Slack channel.");
+ const route = slack.routes.find((candidate) => candidate.method === "POST");
+ if (route === undefined || !isHttpRouteDefinition(route)) {
+ throw new Error("Expected the Slack events route.");
+ }
+ const { runtime } = await createWeatherAuthRuntime("workflow-entry-slack-first-turn-auth", [
+ { logicalPath: "channels/slack.ts", loadNamespace: async () => ({ default: slack }) },
+ ]);
+
+ await runtime.run(async () => {
+ const bundle = await getCompiledRuntimeAgentBundle({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ });
+ const resolved = bundle.graph.root.channels.find((channel) => channel.name === "slack");
+ if (resolved?.adapter === undefined) throw new Error("Expected the resolved Slack channel.");
+ const operations = createChannelOperations<unknown>({
+ adapter: resolved.adapter,
+ channelName: "slack",
+ runtime: createWorkflowRuntime({
+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),
+ }),
+ });
+ const body = JSON.stringify({
+ event: {
+ channel: "D_ALICE",
+ channel_type: "im",
+ event_ts: "1700000000.000100",
+ text: "Use the get_weather tool to check the weather in Lisbon.",
+ ts: "1700000000.000100",
+ type: "message",
+ user: "U_ALICE",
+ },
+ event_id: "Ev_first_turn_auth",
+ team_id: "T01",
+ type: "event_callback",
+ });
+ const timestamp = Math.floor(Date.now() / 1000);
+ const signature = `v0=${createHmac("sha256", signingSecret)
+ .update(`v0:${timestamp}:${body}`)
+ .digest("hex")}`;
+ const pending: Promise<unknown>[] = [];
+ await route.handler(
+ new Request("https://agent.example.com/eve/v1/slack", {
+ body,
+ headers: {
+ "content-type": "application/json",
+ "x-slack-request-timestamp": String(timestamp),
+ "x-slack-signature": signature,
+ },
+ method: "POST",
+ }),
+ {
+ ...operations,
+ attachSession: vi.fn() as never,
+ params: {},
+ requestIp: null,
+ to: vi.fn() as never,
+ waitUntil: (task) => void pending.push(task),
+ },
+ );
+ await Promise.all(pending);
+
+ await vi.waitFor(() => expect(ephemeral).toHaveLength(1), { timeout: 20_000 });
+ expect(ephemeral[0]).toMatchObject({ channel: "D_ALICE", user: "U_ALICE" });
+ });
+ });
+
it("resumes normal follow-ups after an interactive authorization callback", async () => {
const { completeCalls, runtime } = await createWeatherAuthRuntime(
"workflow-entry-auth-followup",
@@ -495,7 +597,10 @@ interface WeatherAuthRuntime {
* `oauth-code` callback. Shared by the callback-resume and
* challenge-stays-open owner tests.
*/
-async function createWeatherAuthRuntime(agentName: string): Promise<WeatherAuthRuntime> {
+async function createWeatherAuthRuntime(
+ agentName: string,
+ modules: NonNullable<Parameters<typeof createTestRuntime>[0]>["modules"] = [],
+): Promise<WeatherAuthRuntime> {
let completeCalls = 0;
const completedPrincipals: ConnectionPrincipal[] = [];
const weatherAuth: AuthorizationDefinition<{ nonce: string }> = {
@@ -561,6 +666,7 @@ async function createWeatherAuthRuntime(agentName: string): Promise<WeatherAuthR
};
const runtime = await createTestRuntime({
agent: { name: agentName },
+ modules,
tools: [getWeatherTool],
});
const manifestTool = runtime.manifest.tools.find((tool) => tool.name === getWeatherTool.name);
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index 8c1303d91..1fbae3088 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -223,6 +223,7 @@ function createInitialDelivery(
message: input.input.message,
context: input.input.context,
outputSchema: input.input.outputSchema,
+ state: input.input.state,
},
readClientContext(input.input),
),
diff --git a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
index ab821c5a3..20a869e35 100644
--- a/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-channel-operations.ts
@@ -54,9 +54,15 @@ export function mockChannelContext<TState = undefined>(
...payload,
inputResponses: inputResponseSchema.array().parse(payload.inputResponses),
};
+ const optionsState = (options as { readonly state?: Partial<TState> }).state;
+ const state =
+ payload.state === undefined
+ ? optionsState
+ : { ...optionsState, ...(payload.state as Partial<TState>) };
return (await observeDelivery(continuationToken, {
...options,
...validatedPayload,
+ state,
} as ObservedChannelDelivery<TState>)) as never;
},
};
diff --git a/packages/eve/src/public/channels/slack/auth.ts b/packages/eve/src/public/channels/slack/auth.ts
index 7674978c0..ec5ad30c0 100644
--- a/packages/eve/src/public/channels/slack/auth.ts
+++ b/packages/eve/src/public/channels/slack/auth.ts
@@ -1,4 +1,5 @@
import type { SessionAuthContext } from "#channel/types.js";
+import type { SlackChannelState } from "#public/channels/slack/slackChannel.js";
interface SlackAuthContextInput {
readonly channelId: string;
@@ -17,6 +18,14 @@ export function slackUserIdFromAuthContext(auth: SessionAuthContext | null): str
return typeof userId === "string" && userId.length > 0 ? userId : undefined;
}
+/** Returns the Slack user recorded for a principal, if one has been seen in this thread. */
+export function slackUserIdForPrincipal(
+ state: Pick<SlackChannelState, "slackUsersByPrincipal">,
+ principalId: string | undefined,
+): string | undefined {
+ return principalId === undefined ? undefined : state.slackUsersByPrincipal?.[principalId];
+}
+
/**
* Builds the Slack-derived session auth context used by inbound
* messages and signed interactivity callbacks.
diff --git a/packages/eve/src/public/channels/slack/connections.test.ts b/packages/eve/src/public/channels/slack/connections.test.ts
index 031d43061..ea9ff74b4 100644
--- a/packages/eve/src/public/channels/slack/connections.test.ts
+++ b/packages/eve/src/public/channels/slack/connections.test.ts
@@ -22,15 +22,15 @@ describe("formatConnectionDisplayName", () => {
});
describe("buildAuthRequiredPublicText", () => {
- it("invites the triggering user to connect when one is known", () => {
- expect(buildAuthRequiredPublicText({ displayName: "Linear", hasUser: true })).toBe(
+ it("invites the recipient to connect when the link was sent privately", () => {
+ expect(buildAuthRequiredPublicText({ displayName: "Linear", hasRecipient: true })).toBe(
"Connect with Linear to continue",
);
});
- it("notes the missing actor when no user is known", () => {
- expect(buildAuthRequiredPublicText({ displayName: "Linear", hasUser: false })).toBe(
- "Authorization required for Linear (no triggering user)",
+ it("notes when the link could not be sent privately", () => {
+ expect(buildAuthRequiredPublicText({ displayName: "Linear", hasRecipient: false })).toBe(
+ "Authorization required for Linear (couldn't send the sign-in link privately)",
);
});
});
diff --git a/packages/eve/src/public/channels/slack/connections.ts b/packages/eve/src/public/channels/slack/connections.ts
index cf18a921e..2de9d912d 100644
--- a/packages/eve/src/public/channels/slack/connections.ts
+++ b/packages/eve/src/public/channels/slack/connections.ts
@@ -7,9 +7,9 @@
* posted sign-in link and bind their own identity to the session. The
* default handler therefore posts a link-free public status while
* delivering the actual challenge as an ephemeral "Sign in"
- * message visible only to the triggering user.
+ * message visible only to the Slack user behind the event's `principalId`.
*
- * When no user can be targeted (no triggering user id, no challenge
+ * When no user can be targeted (no Slack user for the principal, no challenge
* URL, or the ephemeral delivery fails), the public status still leaves
* the shared thread with safe progress feedback. The matching
* `authorization.completed` handler edits that status post in place to
@@ -34,16 +34,16 @@ export function formatConnectionDisplayName(connectionName: string): string {
/**
* Public status text for an authorization challenge. Deliberately
* link-free: it must stay safe to post in a shared thread. When the
- * channel cannot identify a triggering user (rare — schedule-initiated
- * sessions or events that lack actor metadata) the text drops the
- * "Connect with" call-to-action since there's no one to act on it.
+ * principal has no Slack user in this thread (schedule-initiated sessions,
+ * or principals never seen here) the text drops the "Connect with"
+ * call-to-action since no one received the link.
*/
export function buildAuthRequiredPublicText(input: {
readonly displayName: string;
- readonly hasUser: boolean;
+ readonly hasRecipient: boolean;
}): string {
- if (!input.hasUser) {
- return `Authorization required for ${input.displayName} (no triggering user)`;
+ if (!input.hasRecipient) {
+ return `Authorization required for ${input.displayName} (couldn't send the sign-in link privately)`;
}
return `Connect with ${input.displayName} to continue`;
}
diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.ts
index 93ad6d27a..0307aaf1e 100644
--- a/packages/eve/src/public/channels/slack/defaults.test.ts
+++ b/packages/eve/src/public/channels/slack/defaults.test.ts
@@ -99,6 +99,8 @@ function buildChannelStub(state: Partial<SlackChannelState> = {}) {
return { channel, post, postDirectMessage, postEphemeral, request, startTyping };
}
+const RECIPIENT = { slackUsersByPrincipal: { "slack:T01:U777": "U777" } };
+
function authRequiredEvent(
overrides: { url?: string; userCode?: string; displayName?: string } = {},
) {
@@ -106,6 +108,7 @@ function authRequiredEvent(
authorization: { url: overrides.url ?? "https://connect.example.com/a/sca_1", ...overrides },
description: "Authorization required for notion",
name: "notion",
+ principalId: "slack:T01:U777",
sequence: 0,
stepIndex: 0,
turnId: "turn_0",
@@ -299,7 +302,7 @@ describe("defaultInputRequestedHandler private input requests", () => {
describe("defaultEvents approval lifecycle", () => {
it("sends candidate progress privately", async () => {
const { channel, postEphemeral } = buildChannelStub({
- pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ slackUsersByPrincipal: { "slack:T1:U777": "U777" },
});
const ctx = sessionContext({
attributes: { user_id: "U777" },
@@ -330,7 +333,7 @@ describe("defaultEvents approval lifecycle", () => {
it("routes candidate progress from event identity instead of ambient auth", async () => {
const { channel, postEphemeral } = buildChannelStub({
- pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ slackUsersByPrincipal: { "slack:T1:U777": "U777" },
teamId: "T1",
});
const wrongAmbientUser = sessionContext({
@@ -358,12 +361,11 @@ describe("defaultEvents approval lifecycle", () => {
"U777",
"Checking whether you can respond to this approval…",
);
- expect(channel.state.pendingApprovalCandidateUsers).toEqual({ "candidate-1": "U777" });
});
it("delivers an immediate rejection through the responder mapping", async () => {
const { channel, postEphemeral } = buildChannelStub({
- pendingApprovalCandidateUsers: { "candidate-1": "U777" },
+ slackUsersByPrincipal: { "slack:T1:U777": "U777" },
});
const ctx = sessionContext({
attributes: { user_id: "U777" },
@@ -392,7 +394,7 @@ describe("defaultEvents approval lifecycle", () => {
it("updates the shared card only after settlement", async () => {
const { channel, request } = buildChannelStub({
- approvalResponderUsers: { "slack:T1:U777": "U777" },
+ slackUsersByPrincipal: { "slack:T1:U777": "U777" },
pendingApprovalCards: {
"approval-1": {
messageBlocks: [
@@ -433,7 +435,7 @@ describe("defaultEvents approval lifecycle", () => {
it("settles the request when its buttons carry tool-approval metadata", async () => {
const { channel, request } = buildChannelStub({
- approvalResponderUsers: { "slack:T1:U777": "U777" },
+ slackUsersByPrincipal: { "slack:T1:U777": "U777" },
pendingApprovalCards: {
"approval-1": {
messageBlocks: [
@@ -481,7 +483,7 @@ describe("defaultEvents approval lifecycle", () => {
type: "card",
}));
const { channel, request } = buildChannelStub({
- approvalResponderUsers: { "slack:T1:U777": "U777" },
+ slackUsersByPrincipal: { "slack:T1:U777": "U777" },
pendingApprovalCards: Object.fromEntries(
requestIds.map((requestId) => [requestId, { messageBlocks, messageTs: "123.456" }]),
),
@@ -517,8 +519,8 @@ describe("defaultEvents approval lifecycle", () => {
});
describe("defaultEvents authorization.required", () => {
- it("posts a public status and delivers the challenge ephemerally to the triggering user", async () => {
- const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
+ it("posts a public status and delivers the challenge ephemerally to the event principal", async () => {
+ const { channel, post, postEphemeral } = buildChannelStub(RECIPIENT);
await defaultEvents["authorization.required"]!(authRequiredEvent(), channel, sessionCtx);
@@ -534,10 +536,7 @@ describe("defaultEvents authorization.required", () => {
});
it("does not post a public status for candidate-scoped authorization", async () => {
- const { channel, post, postEphemeral } = buildChannelStub({
- pendingApprovalCandidateUsers: { "candidate-1": "U777" },
- triggeringUserId: "U_OTHER",
- });
+ const { channel, post, postEphemeral } = buildChannelStub(RECIPIENT);
await defaultEvents["authorization.required"]!(
{ ...authRequiredEvent(), candidateId: "candidate-1" },
@@ -549,31 +548,44 @@ describe("defaultEvents authorization.required", () => {
expect(postEphemeral).toHaveBeenCalledTimes(1);
});
- it("uses only the candidate mapping for candidate-scoped challenges", async () => {
+ it("targets the event principal instead of the current caller or stale channel state", async () => {
const { channel, postEphemeral } = buildChannelStub({
- pendingApprovalCandidateUsers: { "candidate-1": "U_CANDIDATE" },
+ slackUsersByPrincipal: {
+ "slack:T01:U777": "U777",
+ "slack:T01:U_CURRENT": "U_CURRENT",
+ },
triggeringUserId: "U_STALE",
});
- const wrongAmbientUser = sessionContext({
- attributes: { user_id: "U_WRONG" },
+ const laterCaller = sessionContext({
+ attributes: { user_id: "U_CURRENT" },
authenticator: "slack-webhook",
- principalId: "slack:T01:U_WRONG",
+ principalId: "slack:T01:U_CURRENT",
principalType: "user",
});
+ await defaultEvents["authorization.required"]!(authRequiredEvent(), channel, laterCaller);
+
+ expect(postEphemeral.mock.calls[0]?.[0]).toBe("U777");
+ });
+
+ it("resolves a custom-auth principal through its recorded Slack user", async () => {
+ const { channel, postEphemeral } = buildChannelStub({
+ slackUsersByPrincipal: { "okta|alice": "U_ALICE" },
+ });
+
await defaultEvents["authorization.required"]!(
- { ...authRequiredEvent(), candidateId: "candidate-1" },
+ { ...authRequiredEvent(), candidateId: "candidate-1", principalId: "okta|alice" },
channel,
- wrongAmbientUser,
+ sessionCtx,
);
- expect(postEphemeral.mock.calls[0]?.[0]).toBe("U_CANDIDATE");
+ expect(postEphemeral.mock.calls[0]?.[0]).toBe("U_ALICE");
});
- it("does not leak a candidate challenge when its mapping is missing", async () => {
+ it("does not leak a challenge whose principal has no Slack user", async () => {
const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U_STALE" });
await defaultEvents["authorization.required"]!(
- { ...authRequiredEvent(), candidateId: "candidate-missing" },
+ { ...authRequiredEvent(), candidateId: "candidate-1" },
channel,
sessionContext({
attributes: { user_id: "U_WRONG" },
@@ -585,22 +597,8 @@ describe("defaultEvents authorization.required", () => {
expect(postEphemeral).not.toHaveBeenCalled();
});
- it("targets the current Slack caller instead of stale channel state", async () => {
- const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U_FIRST" });
- const currentCaller = sessionContext({
- attributes: { user_id: "U_CURRENT" },
- authenticator: "slack-webhook",
- principalId: "slack:T01:U_CURRENT",
- principalType: "user",
- });
-
- await defaultEvents["authorization.required"]!(authRequiredEvent(), channel, currentCaller);
-
- expect(postEphemeral.mock.calls[0]?.[0]).toBe("U_CURRENT");
- });
-
it("renders the device user code in the ephemeral blocks and fallback text", async () => {
- const { channel, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
+ const { channel, postEphemeral } = buildChannelStub(RECIPIENT);
await defaultEvents["authorization.required"]!(
authRequiredEvent({ userCode: "OTB-DGO" }),
@@ -614,7 +612,7 @@ describe("defaultEvents authorization.required", () => {
});
it("renders the challenge displayName instead of the title-cased connection name", async () => {
- const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
+ const { channel, post, postEphemeral } = buildChannelStub(RECIPIENT);
await defaultEvents["authorization.required"]!(
authRequiredEvent({ displayName: "Notion Workspace" }),
@@ -627,22 +625,24 @@ describe("defaultEvents authorization.required", () => {
expect(message.text).toContain("Sign in with Notion Workspace");
});
- it("posts a link-free public status when there is no triggering user", async () => {
- const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: null });
+ it("posts a link-free public status when the principal has no Slack user", async () => {
+ const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: "U_STALE" });
await defaultEvents["authorization.required"]!(authRequiredEvent(), channel, sessionCtx);
expect(postEphemeral).not.toHaveBeenCalled();
expect(post).toHaveBeenCalledTimes(1);
const publicText = post.mock.calls[0]?.[0] as string;
- expect(publicText).toBe("Authorization required for Notion (no triggering user)");
+ expect(publicText).toBe(
+ "Authorization required for Notion (couldn't send the sign-in link privately)",
+ );
expect(publicText).not.toContain("https://");
expect(channel.state.pendingAuthMessageTs).toEqual({ notion: "ts1" });
});
it("keeps the link-free public status when the ephemeral delivery fails", async () => {
const logs = captureLogRecords();
- const { channel, post, postEphemeral } = buildChannelStub({ triggeringUserId: "U777" });
+ const { channel, post, postEphemeral } = buildChannelStub(RECIPIENT);
postEphemeral.mockRejectedValueOnce(new Error("ephemeral rejected"));
await defaultEvents["authorization.required"]!(authRequiredEvent(), channel, sessionCtx);
@@ -659,7 +659,7 @@ describe("defaultEvents authorization.required", () => {
it("reuses an existing public status when authorization is already pending", async () => {
const { channel, post, postEphemeral } = buildChannelStub({
- triggeringUserId: "U777",
+ ...RECIPIENT,
pendingAuthMessageTs: { notion: "ts0" },
});
diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.ts
index fc1cd45a0..d31744859 100644
--- a/packages/eve/src/public/channels/slack/defaults.ts
+++ b/packages/eve/src/public/channels/slack/defaults.ts
@@ -3,7 +3,11 @@ import type { SessionAuthContext } from "#channel/types.js";
import { createLogger, extractErrorId, formatErrorHint, logError } from "#internal/logging.js";
import { describeActionRequests } from "#public/channels/slack/action-status.js";
import { isTaskControlTool } from "#protocol/task-tools.js";
-import { buildSlackAuthContext, slackUserIdFromAuthContext } from "#public/channels/slack/auth.js";
+import {
+ buildSlackAuthContext,
+ slackUserIdForPrincipal,
+ slackUserIdFromAuthContext,
+} from "#public/channels/slack/auth.js";
import {
buildAuthCompletedText,
buildAuthEphemeralBlocks,
@@ -363,7 +367,7 @@ export async function postCompletedSlackReply(
*/
export const defaultEvents: SlackChannelInternalEvents = {
async "approval.candidate"(event, channel, _ctx) {
- const userId = channel.state.pendingApprovalCandidateUsers?.[event.candidateId];
+ const userId = slackUserIdForPrincipal(channel.state, event.responderPrincipalId);
if (event.outcome === "pending" && userId !== undefined) {
await channel.thread.postEphemeral(
userId,
@@ -387,7 +391,7 @@ export const defaultEvents: SlackChannelInternalEvents = {
const messageChannelId = card.messageChannelId ?? channel.state.channelId;
if (messageChannelId === null) return;
const answerLabel = event.outcome === "approved" ? "Approve" : "Cancel";
- const userId = channel.state.approvalResponderUsers?.[event.responderPrincipalId];
+ const userId = slackUserIdForPrincipal(channel.state, event.responderPrincipalId);
const blocks = card.messageBlocks.flatMap((block) => {
if (!blockContainsRequestAction(block, event.requestId)) return [block];
if (typeof block !== "object" || block === null) return [];
@@ -552,14 +556,9 @@ export const defaultEvents: SlackChannelInternalEvents = {
);
},
- async "authorization.required"(event, channel, ctx) {
+ async "authorization.required"(event, channel, _ctx) {
const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);
- const triggeringUserId =
- event.candidateId === undefined
- ? (slackUserIdFromAuthContext(ctx.session.auth.current) ??
- channel.state.triggeringUserId ??
- null)
- : (channel.state.pendingApprovalCandidateUsers?.[event.candidateId] ?? null);
+ const recipientUserId = slackUserIdForPrincipal(channel.state, event.principalId) ?? null;
const challengeUrl = event.authorization?.url;
// Post a public, link-free status so everyone in the thread can see
@@ -569,7 +568,7 @@ export const defaultEvents: SlackChannelInternalEvents = {
if (event.candidateId === undefined && pending[event.name] === undefined) {
const publicText = buildAuthRequiredPublicText({
displayName,
- hasUser: triggeringUserId !== null,
+ hasRecipient: recipientUserId !== null,
});
try {
const sent = await channel.thread.post(publicText);
@@ -588,12 +587,12 @@ export const defaultEvents: SlackChannelInternalEvents = {
}
// The challenge is user-specific: the sign-in link (and device code)
- // must only ever be visible to the triggering user, never posted into
+ // must only ever be visible to the person who started the sign-in, never posted into
// the shared thread.
- if (triggeringUserId && challengeUrl) {
+ if (recipientUserId && challengeUrl) {
const userCode = event.authorization?.userCode;
try {
- await channel.thread.postEphemeral(triggeringUserId, {
+ await channel.thread.postEphemeral(recipientUserId, {
blocks: buildAuthEphemeralBlocks({
displayName,
url: challengeUrl,
diff --git a/packages/eve/src/public/channels/slack/input-response.ts b/packages/eve/src/public/channels/slack/input-response.ts
index ab1d56605..5c0476506 100644
--- a/packages/eve/src/public/channels/slack/input-response.ts
+++ b/packages/eve/src/public/channels/slack/input-response.ts
@@ -1,32 +1,16 @@
-import type { SessionAuthContext } from "#channel/types.js";
import { createLogger } from "#internal/logging.js";
import { buildSlackBinding } from "#public/channels/slack/api.js";
import { buildSlackAuthContext } from "#public/channels/slack/auth.js";
-import { deriveHitlResponse } from "#public/channels/slack/hitl.js";
import type {
SlackChannelConfig,
SlackInputResponseContext,
SlackInputResponseResult,
SlackInputResponseSubmission,
- SlackChannelState,
} from "#public/channels/slack/slackChannel.js";
import type { SlackTransportOptions } from "#public/channels/slack/transport.js";
const log = createLogger("slack.interactions");
-export function approvalResponderStatePatch(
- submission: Extract<SlackInputResponseSubmission, { type: "block_actions" }>,
- auth: SessionAuthContext | null,
-): Partial<SlackChannelState> | undefined {
- if (
- auth?.principalId === undefined ||
- !submission.actions.some((action) => deriveHitlResponse(action)?.kind === "tool-approval")
- ) {
- return undefined;
- }
- return { approvalResponderUsers: { [auth.principalId]: submission.user.id } };
-}
-
export async function authorizeInputResponse(input: {
readonly channelId: string;
readonly deps: {
diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.ts
index 9a9ab51d8..6b9c6f2e3 100644
--- a/packages/eve/src/public/channels/slack/interactions.ts
+++ b/packages/eve/src/public/channels/slack/interactions.ts
@@ -39,10 +39,7 @@ import {
updateAnsweredFreeformCard,
updateAnsweredHitlCard,
} from "#public/channels/slack/interaction-cards.js";
-import {
- approvalResponderStatePatch,
- authorizeInputResponse,
-} from "#public/channels/slack/input-response.js";
+import { authorizeInputResponse } from "#public/channels/slack/input-response.js";
import type {
SlackChannelConfig,
SlackChannelState,
@@ -54,7 +51,10 @@ import type {
SlackShortcutContext,
} from "#public/channels/slack/slackChannel.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
-import { bindSlackSessionOperations } from "#public/channels/slack/session-operations.js";
+import {
+ bindSlackSessionOperations,
+ withSlackResponder,
+} from "#public/channels/slack/session-operations.js";
import { dispatchSlashCommand } from "#public/channels/slack/slash-command.js";
import { parseInputResponse } from "#shared/input.js";
@@ -495,7 +495,7 @@ async function dispatchBlockInputResponses(input: {
.from(slackContinuationToken(channelId, threadTs))
.respond(input.submission.inputResponses, {
auth: result.auth,
- state: approvalResponderStatePatch(input.submission, result.auth),
+ state: withSlackResponder(undefined, input.submission.user.id),
});
} catch (error) {
log.error("HITL interaction delivery failed", { error });
@@ -672,6 +672,7 @@ async function dispatchViewInputResponse(input: {
.from(input.metadata.continuationToken)
.respond(input.submission.inputResponses, {
auth: result.auth,
+ state: withSlackResponder(undefined, input.submission.user.id),
});
} catch (error) {
log.error("freeform answer delivery failed", { error });
diff --git a/packages/eve/src/public/channels/slack/session-operations.ts b/packages/eve/src/public/channels/slack/session-operations.ts
index fc7d0e602..15488b579 100644
--- a/packages/eve/src/public/channels/slack/session-operations.ts
+++ b/packages/eve/src/public/channels/slack/session-operations.ts
@@ -1,9 +1,11 @@
-import type {
- ChannelFrom,
- ChannelResolveSession,
- ChannelRespondOptions,
- ChannelSendOptions,
- ChannelSource,
+import {
+ INTERNAL_CHANNEL_DELIVER,
+ type ChannelFrom,
+ type ChannelResolveSession,
+ type ChannelRespondOptions,
+ type ChannelSendOptions,
+ type ChannelSource,
+ type InternalChannelSource,
} from "#channel/channel-operations.js";
import type { SessionAuthContext } from "#channel/types.js";
import type { InputResponse, StrictInputResponses } from "#shared/input.js";
@@ -44,13 +46,13 @@ export function bindSlackSessionOperations(input: {
readonly resolveSession: ChannelResolveSession;
readonly state: SlackChannelState;
}): SlackSessionOperations {
- const source = input.from(input.address);
+ const source = input.from(input.address) as InternalChannelSource<SlackChannelState>;
const auth = (value: SessionAuthContext | null | undefined) =>
value === undefined ? input.defaultAuth : value;
return {
async send(message, options = {}) {
- return await source.send(message, {
+ return await sendAsSlackUser(source, message, {
...options,
auth: auth(options.auth),
state: input.state,
@@ -60,6 +62,7 @@ export function bindSlackSessionOperations(input: {
return await source.respond(inputResponses, {
...options,
auth: auth(options.auth),
+ state: withSlackResponder(options.state, input.state.triggeringUserId),
});
},
async cancel(options) {
@@ -79,3 +82,35 @@ export function bindSlackSessionOperations(input: {
},
};
}
+
+/**
+ * Sends a message and stamps its Slack author on the payload, so `deliver` can
+ * map a custom-auth principal to the Slack user who wrote the message.
+ */
+export async function sendAsSlackUser(
+ source: InternalChannelSource<SlackChannelState>,
+ message: string | UserContent,
+ options: ChannelSendOptions<SlackChannelState>,
+): ReturnType<SlackSource["send"]> {
+ return await source[INTERNAL_CHANNEL_DELIVER](
+ {
+ context: options.context,
+ message,
+ state: { triggeringUserId: options.state?.triggeringUserId ?? null },
+ },
+ options,
+ );
+}
+
+/**
+ * Stamps the verified Slack user behind an input response, so `deliver` can map
+ * a custom-auth responder's principal to them. The verified user wins over any
+ * caller-supplied value.
+ */
+export function withSlackResponder(
+ state: Partial<SlackChannelState> | undefined,
+ slackUserId: string | null | undefined,
+): Partial<SlackChannelState> | undefined {
+ if (!slackUserId) return state;
+ return { ...state, triggeringUserId: slackUserId };
+}
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index 62a97b37d..a4f6c5ad9 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -10,9 +10,10 @@ import {
type CompiledChannel,
} from "#channel/compiled-channel.js";
import type { ChannelFrom, ChannelSource } from "#channel/channel-operations.js";
+import type { SessionAuthContext } from "#channel/types.js";
import { isHttpRouteDefinition } from "#channel/routes.js";
import { ContextContainer, contextStorage } from "#context/container.js";
-import { SessionKey } from "#context/keys.js";
+import { AuthKey, SessionKey } from "#context/keys.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
import {
mockChannelContext,
@@ -192,6 +193,10 @@ function stubAccessor() {
return { get: () => undefined, set: () => {} } as any;
}
+function callerAccessor(auth: unknown) {
+ return { get: (key: unknown) => (key === AuthKey ? auth : undefined), set: () => {} } as any;
+}
+
const stubAlsContext = (() => {
const ctx = new ContextContainer();
ctx.setVirtualContext(SessionKey, {
@@ -1240,6 +1245,23 @@ describe("slackChannel() default event handlers", () => {
});
});
+ it("records the Slack user behind each delivered message's principal", async () => {
+ const adapter = withState(getAdapter(slackChannel()), THREAD_STATE);
+ const ctx = buildAdapterContext(
+ adapter,
+ callerAccessor({
+ attributes: { user_id: "U_ALICE" },
+ authenticator: "slack-webhook",
+ principalId: "slack:T01:U_ALICE",
+ principalType: "user",
+ }),
+ );
+
+ await adapter.deliver!({ message: "hello" }, ctx);
+
+ expect(ctx.state.slackUsersByPrincipal).toEqual({ "slack:T01:U_ALICE": "U_ALICE" });
+ });
+
it("refreshes triggeringUserId from the current Slack caller on every turn", async () => {
const onTurnStarted = vi.fn();
const adapter = withState(
@@ -3128,6 +3150,31 @@ describe("slackChannel() inbound direct message pipeline", () => {
expect(options.title).toBe("Private message");
});
+ it("maps a custom-auth message sender to their Slack user when delivered", async () => {
+ const customAuth = {
+ attributes: {},
+ authenticator: "okta",
+ principalId: "okta|alice",
+ principalType: "user",
+ };
+ const channel = slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ onDirectMessage: () => ({ auth: customAuth }),
+ });
+
+ const { body } = buildDirectMessageBody();
+ const { send } = await firePost(channel, buildSignedRequest({ body }));
+ const delivery = send.mock.calls[0]?.[1] as ObservedChannelDelivery<SlackChannelState>;
+ const author = delivery.state?.triggeringUserId;
+ expect(author).toEqual(expect.any(String));
+
+ const adapter = withState(getAdapter(channel), THREAD_STATE);
+ const ctx = buildAdapterContext(adapter, callerAccessor(customAuth));
+ await adapter.deliver!({ message: "hello", state: { triggeringUserId: author } }, ctx);
+
+ expect(ctx.state.slackUsersByPrincipal).toEqual({ "okta|alice": author });
+ });
+
it("uses an opaque run title for direct messages", async () => {
const channel = slackChannel({
credentials: { botToken: "xoxb-test" },
@@ -3637,9 +3684,7 @@ describe("slackChannel() HITL interaction pipeline", () => {
principalType: "user",
},
inputResponses: [{ optionId: "approve", requestId: "approval_abc123" }],
- state: {
- approvalResponderUsers: { "slack:T_ACTOR:U_APPROVER": "U_APPROVER" },
- },
+ state: { triggeringUserId: "U_APPROVER" },
});
});
@@ -3802,13 +3847,115 @@ describe("slackChannel() HITL interaction pipeline", () => {
expect(onInputResponse).toHaveBeenCalledTimes(1);
expect(send).toHaveBeenCalledTimes(1);
- expect(send.mock.calls[0]?.[1]).toMatchObject({
- auth: customAuth,
- state: { approvalResponderUsers: { "employee:ada": "U_APPROVER" } },
- });
+ const delivery = send.mock.calls[0]?.[1] as Extract<
+ ObservedChannelDelivery<SlackChannelState>,
+ { readonly inputResponses: readonly unknown[] }
+ >;
+ expect(delivery).toMatchObject({ auth: customAuth, state: { triggeringUserId: "U_APPROVER" } });
+
+ const adapter = withState(getAdapter(channel), THREAD_STATE);
+ const ctx = buildAdapterContext(adapter, callerAccessor(customAuth));
+ await adapter.deliver!({ inputResponses: delivery.inputResponses, state: delivery.state }, ctx);
+ expect(ctx.state.slackUsersByPrincipal).toEqual({ "employee:ada": "U_APPROVER" });
});
- it("persists the responder mapping for later approval candidate feedback", async () => {
+ it.each([
+ {
+ name: "onInteraction ctx.respond",
+ channel: (auth: SessionAuthContext) =>
+ slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ async onInteraction(_action, ctx) {
+ await ctx.respond([{ optionId: "approve", requestId: "approval_abc123" }], { auth });
+ },
+ }),
+ request: () =>
+ buildSignedInteractionRequest({
+ type: "block_actions",
+ team: { id: "T01" },
+ user: { id: "U_APPROVER", username: "ada" },
+ channel: { id: "C01" },
+ message: { ts: "1700000000.000010", thread_ts: "1700000000.000001", blocks: [] },
+ actions: [{ action_id: "custom-approve", text: { type: "plain_text", text: "OK" } }],
+ }),
+ },
+ {
+ name: "onEvent ctx.respond",
+ channel: (auth: SessionAuthContext) =>
+ slackChannel({
+ credentials: { botToken: "xoxb-test" },
+ async onEvent(ctx) {
+ await ctx.respond([{ optionId: "approve", requestId: "approval_abc123" }], {
+ auth,
+ target: { channelId: "C01", threadTs: "1700000000.000001" },
+ });
+ },
+ }),
+ request: () =>
+ buildSignedRequest({
+ body: buildEventBody(
+ {
+ item: { channel: "C01", ts: "1700000000.000001", type: "message" },
+ reaction: "white_check_mark",
+ type: "reaction_added",
+ user: "U_APPROVER",
+ },
+ { eventId: "Ev_custom_approve", teamId: "T01" },
+ ),
+ }),
+ },
+ ])(
+ "sends a custom-auth responder's sign-in privately after $name",
+ async ({ channel: buildChannel, request }) => {
+ fetchMock.mockImplementation(
+ () =>
+ new Response(JSON.stringify({ ok: true, ts: "1700000001.000001" }), {
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const customAuth: SessionAuthContext = {
+ attributes: {},
+ authenticator: "employee-directory",
+ principalId: "employee:ada",
+ principalType: "user",
+ };
+ const channel = buildChannel(customAuth);
+ const { send } = await firePost(channel, request());
+ const delivery = send.mock.calls[0]?.[1] as Extract<
+ ObservedChannelDelivery<SlackChannelState>,
+ { readonly inputResponses: readonly unknown[] }
+ >;
+ const adapter = withState(getAdapter(channel), THREAD_STATE);
+ const ctx = buildAdapterContext(adapter, callerAccessor(delivery.auth));
+ await adapter.deliver!(
+ { inputResponses: delivery.inputResponses, state: delivery.state },
+ ctx,
+ );
+
+ await callEvent(
+ adapter,
+ makeEvent("authorization.required", {
+ attemptId: "attempt-1",
+ authorization: { url: "https://idp.example/sign-in" },
+ candidateId: "candidate-1",
+ description: "Sign in to approve.",
+ name: "approver-sign-in",
+ principalId: "employee:ada",
+ sequence: 1,
+ stepIndex: 0,
+ turnId: "turn-1",
+ }),
+ ctx,
+ );
+
+ const ephemeral = slackCalls(fetchMock, "chat.postEphemeral").map(([, init]) =>
+ parseSlackRequestBody(init),
+ );
+ expect(ephemeral).toEqual([expect.objectContaining({ channel: "C01", user: "U_APPROVER" })]);
+ },
+ );
+
+ it("persists the responder principal mapping for later approval candidate feedback", async () => {
fetchMock.mockImplementation(
() =>
new Response(JSON.stringify({ ok: true, ts: "1700000001.000001" }), {
@@ -3822,7 +3969,7 @@ describe("slackChannel() HITL interaction pipeline", () => {
{ readonly inputResponses: readonly unknown[] }
>;
const adapter = withState(getAdapter(channel), THREAD_STATE);
- const ctx = buildAdapterContext(adapter, stubAccessor());
+ const ctx = buildAdapterContext(adapter, callerAccessor(delivery.auth));
await adapter.deliver!(
{
@@ -3832,7 +3979,7 @@ describe("slackChannel() HITL interaction pipeline", () => {
ctx,
);
- expect(ctx.state.approvalResponderUsers).toEqual({ "slack:T01:U_APPROVER": "U_APPROVER" });
+ expect(ctx.state.slackUsersByPrincipal).toEqual({ "slack:T01:U_APPROVER": "U_APPROVER" });
await callEvent(
adapter,
diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.ts
index 79c7f80a5..df32ae050 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.ts
@@ -5,11 +5,12 @@ import type {
ChannelFrom,
ChannelResolveSession,
ChannelSource,
+ InternalChannelSource,
} from "#channel/channel-operations.js";
import { defaultDeliverResult } from "#channel/adapter.js";
import type { Session, SessionHandle } from "#channel/session.js";
import { setChannelActivityRenderers, setChannelBuildMetadata } from "#channel/compiled-channel.js";
-import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";
+import type { DeliverPayload, SessionAuthContext, TurnPolicy } from "#channel/types.js";
import type { VercelConnectMetadata } from "#shared/vercel-connect-metadata.js";
import type { CardElement } from "#compiled/chat/index.js";
import type { SessionContext } from "#public/definitions/callback-context.js";
@@ -75,6 +76,8 @@ import { defineSlackAppManifest } from "#public/channels/slack/app-manifest.js";
import { handleInteractionPost } from "#public/channels/slack/interactions.js";
import {
bindSlackSessionOperations,
+ sendAsSlackUser,
+ withSlackResponder,
type SlackSendOptions,
type SlackSessionOperations,
} from "#public/channels/slack/session-operations.js";
@@ -184,8 +187,8 @@ export interface SlackAuthorizationEventContext {
*/
readonly postDirectMessage: SlackThread["postDirectMessage"];
/**
- * Hydrated per-session channel state — read `triggeringUserId` to
- * target the delivery.
+ * Hydrated per-session channel state. Resolve the recipient with
+ * `slackUsersByPrincipal[eventData.principalId]`.
*/
readonly state: SlackChannelState;
}
@@ -234,9 +237,8 @@ export interface SlackChannelState {
installationTeamId?: string | null;
/**
* Slack user id of the actor that triggered the current session/turn.
- * Captured on every inbound mention so default handlers (e.g.
- * `authorization.required`) can target ephemeral feedback at the right
- * user without re-parsing the mention payload.
+ * A later message can change it, so sign-in and approval handlers address
+ * recipients through `slackUsersByPrincipal` instead.
*/
triggeringUserId?: string | null;
/**
@@ -263,8 +265,12 @@ export interface SlackChannelState {
*/
pendingAuthMessageTs?: Record<string, string>;
pendingApprovalCards?: Record<string, SlackPendingApprovalCard>;
- pendingApprovalCandidateUsers?: Record<string, string>;
- approvalResponderUsers?: Record<string, string>;
+ /**
+ * Principal id to Slack user id, recorded as each message or input response
+ * is delivered. Default handlers use it to address the principal named on
+ * `authorization.required` and approval events.
+ */
+ slackUsersByPrincipal?: Record<string, string>;
}
/**
@@ -892,8 +898,6 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
});
const onInputResponse = config.onInputResponse ?? defaultOnInputResponse;
const authorizationRequiredOverride = config.events?.["authorization.required"];
- const candidateHandler =
- config.events?.["approval.candidate"] ?? defaultEvents["approval.candidate"]!;
const activityOwnsTypingStatus = hasSlackActivityStatus(config.activity?.renderers);
const turnStartedHandler =
config.events?.["turn.started"] ??
@@ -921,21 +925,6 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
const mergedEvents: SlackChannelInternalEvents = {
...defaultEvents,
...config.events,
- async "approval.candidate"(data, channel, ctx) {
- const responderUserId = channel.state.approvalResponderUsers?.[data.responderPrincipalId];
- if (data.outcome === "pending" && responderUserId !== undefined) {
- channel.state.pendingApprovalCandidateUsers = {
- ...channel.state.pendingApprovalCandidateUsers,
- [data.candidateId]: responderUserId,
- };
- }
- await candidateHandler(data, channel, ctx);
- if (data.outcome !== "pending") {
- const users = { ...channel.state.pendingApprovalCandidateUsers };
- delete users[data.candidateId];
- channel.state.pendingApprovalCandidateUsers = users;
- }
- },
async "turn.started"(data, channel, ctx) {
const triggeringUserId = slackUserIdFromAuthContext(ctx.session.auth.current);
if (triggeringUserId !== undefined) {
@@ -977,8 +966,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
lastReasoningTypingStatus: null,
pendingAuthMessageTs: {},
pendingApprovalCards: {},
- pendingApprovalCandidateUsers: {},
- approvalResponderUsers: {},
+ slackUsersByPrincipal: {},
},
fetchFile: slackFetchFile,
metadata(state): SlackInstrumentationMetadata {
@@ -995,19 +983,14 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {
return rebuildSlackContext(state, session, api, config.credentials);
},
- deliver(payload, channel) {
+ // The runtime hands `deliver` the full adapter context; `session.auth.current`
+ // is the caller of this delivery.
+ deliver(payload, channel: SlackChannelContext & { readonly session: SessionHandle }) {
const cards = payload.pendingApprovalCards;
if (typeof cards === "object" && cards !== null) {
channel.state.pendingApprovalCards = { ...channel.state.pendingApprovalCards, ...cards };
}
- const responders = (payload.state as Partial<SlackChannelState> | undefined)
- ?.approvalResponderUsers;
- if (typeof responders === "object" && responders !== null) {
- channel.state.approvalResponderUsers = {
- ...channel.state.approvalResponderUsers,
- ...responders,
- };
- }
+ recordSlackPrincipal(channel.state, channel.session.auth.current, payload);
return defaultDeliverResult(payload);
},
@@ -1162,11 +1145,10 @@ async function receiveOnSlack(
state.audience = audience;
}
- return deps.from(slackContinuationToken(channelId, continuationThreadTs)).send(input.message, {
- auth: input.auth,
- state,
- title: input.title,
- });
+ const source = deps.from(
+ slackContinuationToken(channelId, continuationThreadTs),
+ ) as InternalChannelSource<SlackChannelState>;
+ return sendAsSlackUser(source, input.message, { auth: input.auth, state, title: input.title });
}
/**
@@ -1498,7 +1480,13 @@ async function dispatchSlackEvent(input: {
resolveSession: ({ target }) =>
input.resolveSession(slackContinuationToken(target.channelId, target.threadTs)),
respond: (inputResponses, { auth, target }) =>
- sourceFor(target).respond(inputResponses, { auth }),
+ sourceFor(target).respond(inputResponses, {
+ auth,
+ state: withSlackResponder(
+ undefined,
+ typeof input.envelope.event.user === "string" ? input.envelope.event.user : undefined,
+ ),
+ }),
send: (message, { auth, target, title }) =>
receiveOnSlack(
{ auth, message, target, title },
@@ -1615,3 +1603,24 @@ async function deliverSlackMessage(input: {
logError(log, `${input.kind} delivery failed`, error, { channelId: message.channelId });
}
}
+
+/**
+ * Records the Slack user behind a delivery's principal. Slack-authenticated
+ * callers carry their user id; custom auth relies on the message author or
+ * clicking user stamped on the payload.
+ */
+function recordSlackPrincipal(
+ state: SlackChannelState,
+ caller: SessionAuthContext | null,
+ payload: DeliverPayload,
+): void {
+ if (caller === null) return;
+ const stamped = (payload.state as Partial<SlackChannelState> | undefined)?.triggeringUserId;
+ const slackUserId =
+ slackUserIdFromAuthContext(caller) ?? (typeof stamped === "string" ? stamped : undefined);
+ if (slackUserId === undefined) return;
+ state.slackUsersByPrincipal = {
+ ...state.slackUsersByPrincipal,
+ [caller.principalId]: slackUserId,
+ };
+}