The Open Framework for Building Agents
fix(slack): scope bot tokens to app installations (#2150)
vercel-gh-bot-2[bot]2bbb77570eea
diff --git a/.changeset/bright-slack-workspaces.md b/.changeset/bright-slack-workspaces.mdnew file mode 100644index 000000000..1e687ee0a--- /dev/null+++ b/.changeset/bright-slack-workspaces.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Pass the app installation workspace id to function-form Slack bot token providers across events, interactions, proactive sends, and private file downloads.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex aa509dcd8..3810d1a0d 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -33,6 +33,20 @@ export default slackChannel({`connectSlackCredentials` returns `{ botToken, webhookVerifier }`, keeping token rotation, multi-workspace tenancy, and request verification inside Connect rather than your code.+Function-form bot tokens receive `{ teamId }` when Slack supplies the app installation workspace. Use it to select an installation in a self-managed multi-workspace app. The id can differ from the actor or content workspace for Slack Connect events:++```ts title="agent/channels/slack.ts"+import { slackChannel } from "eve/channels/slack";++export default slackChannel({+ credentials: {+ botToken: ({ teamId }) => loadInstallationToken(teamId),+ },+});+```++Literal tokens and zero-argument token functions remain supported. A multi-workspace provider should reject a missing `teamId` instead of selecting a default installation.+### Manage Slack credentials yourselfUse this fallback when the agent does not run on Vercel or Vercel Connect is unavailable. In the setup command, **Use portable credentials** is the environment-variable option; eve adds `SLACK_BOT_TOKEN` and `SLACK_SIGNING_SECRET` to `.env.example`.@@ -357,6 +371,7 @@ import { connectSlackCredentials } from "@vercel/connect/eve";const { botToken } = connectSlackCredentials("slack/my-agent");const response = await callSlackApi({botToken,+ context: { teamId: "T0123456789" },operation: "reactions.get",body: { channel: "C0123456789", timestamp: "1712345678.000100", full: true },});@@ -364,7 +379,7 @@ if (!response.ok) throw new Error(String(response.error));````callSlackApi` resolves function-form tokens (secret managers, Connect-rotation) at call time and form-encodes the body — the only safe default,+rotation) with the supplied `context` at call time and form-encodes the body — the only safe default,since Slack's JSON support is partial (`conversations.replies` rejectsJSON). `resolveSlackBotToken` materializes a `SlackBotToken` to a stringwhen you need the bearer token itself.@@ -414,7 +429,7 @@ events: {### Proactive sessions-Start a session without an inbound message through `ctx.to(slack, target).send(message, { auth })` from another channel, or `to(slack, target).send(message, { auth })` from a schedule `run` handler. The proactive target shape is `{ channelId, threadTs?, initialMessage? }`. This sends turn input to the agent; it is not a direct Slack post.+Start a session without an inbound message through `ctx.to(slack, target).send(message, { auth })` from another channel, or `to(slack, target).send(message, { auth })` from a schedule `run` handler. The proactive target shape is `{ channelId, installationTeamId?, threadTs?, initialMessage? }`. Set `installationTeamId` to the app installation workspace when a function-form bot token must select an installation. This sends turn input to the agent; it is not a direct Slack post.To post without invoking the model, use `ctx.thread.post(...)` in an inbound Slack handler or `channel.thread.post(...)` in an `events` handler. Use `callSlackApi(...)` where no Slack channel context exists. For application-managed retries and deduplication, see [Durable cross-channel notifications](../patterns/durable-cross-channel-notifications).@@ -422,7 +437,7 @@ To post without invoking the model, use `ctx.thread.post(...)` in an inbound SlaInbound files behind authenticated Slack URLs are staged with `fetchFile`. See [File uploads](./custom#file-uploads) for the `fetchFile` contract.-Private file downloads require the Slack bot token's `files:read` scope. Add the scope and reinstall the Slack app before sending attachments.+Private file downloads resolve credentials from the session's app installation workspace and require the Slack bot token's `files:read` scope. Add the scope and reinstall the Slack app before sending attachments.Staged files live in the session sandbox under `/workspace/attachments`. Session history keeps a reference to that path, not a second copy of the Slack file. If the backend can no longer reattach the original sandbox, eve cannot restore the attachment bytes from history; later turns receive a missing-file result. Store files outside the sandbox when the agent must retain them independently of sandbox availability.diff --git a/packages/eve/extension-contracts/compatibility/channel/v7.ts b/packages/eve/extension-contracts/compatibility/channel/v7.tsnew file mode 100644index 000000000..5aed0be83--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v7.ts@@ -0,0 +1,8 @@+import { defineChannel, POST } from "#public/channels/index.js";++export default defineChannel({+ routes: [POST("/files", async () => new Response("ok"))],+ async fetchFile(url) {+ return url.startsWith("https://files.example.com/") ? Buffer.from("example") : null;+ },+});diff --git a/packages/eve/extension-contracts/reports/channel/v8.json b/packages/eve/extension-contracts/reports/channel/v8.jsonnew file mode 100644index 000000000..d00cd3e85--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v8.json@@ -0,0 +1,17 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 8,+ "sha256": "0a97cef446a84f6ea475af78c567f9ac303bdb8dc2de5d6f4fe946e282d003e3",+ "exports": [+ "DELETE",+ "GET",+ "PATCH",+ "POST",+ "PUT",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "isChannel"+ ]+}diff --git a/packages/eve/src/channel/adapter.ts b/packages/eve/src/channel/adapter.tsindex 096b9409f..47b2c6487 100644--- a/packages/eve/src/channel/adapter.ts+++ b/packages/eve/src/channel/adapter.ts@@ -4,7 +4,11 @@ import { createLogger } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import type { SessionHandle } from "#channel/session.js";import type { DeliverPayload } from "#channel/types.js";-import type { FetchFileResult, FetchFileFunction } from "#shared/channel-definition.js";+import type {+ FetchFileContext,+ FetchFileResult,+ FetchFileFunction,+} from "#shared/channel-definition.js";import type { ChannelAudienceMetadata } from "#shared/channel-audience.js";const log = createLogger("channel.adapter");@@ -96,7 +100,7 @@ export type ChannelEventHandlers<TCtx extends ChannelAdapterContext<any> = Chann* When fields are provided, staging prefers them over the values the* channel populated at ingestion time.*/-export type { FetchFileResult };+export type { FetchFileContext, FetchFileResult };export type ChannelInstrumentationMetadata = Readonly<Record<string, unknown> & ChannelAudienceMetadatadiff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 29c5e0554..c99ab22d6 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -31,7 +31,7 @@ const EXTENSION_CAPABILITY_CONTRACTS = {supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],dropped: {},},- channel: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },+ channel: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], dropped: {} },schedule: { current: 3, supported: [1, 2, 3], dropped: {} },subagent: { current: 2, supported: [1, 2], dropped: {} },connection: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },diff --git a/packages/eve/src/harness/attachment-staging.integration.test.ts b/packages/eve/src/harness/attachment-staging.integration.test.tsindex a4899f892..4c7759564 100644--- a/packages/eve/src/harness/attachment-staging.integration.test.ts+++ b/packages/eve/src/harness/attachment-staging.integration.test.ts@@ -169,14 +169,15 @@ describe("stageAttachmentsToSandbox (integration)", () => {const resolvedBytes = Buffer.from("resolved-ref-bytes", "utf8");let fetchFileCalls = 0;const adapter: ChannelAdapter<any> = {- async fetchFile(url) {+ async fetchFile(url, context) {fetchFileCalls += 1;// fetchFile receives the URL string from the FilePart.expect(url).toBe("https://example.com/file");+ expect(context?.state).toEqual({ installationTeamId: "T_INSTALLATION" });return resolvedBytes;},kind: "custom-channel",- state: { opener: "alice" },+ state: { installationTeamId: "T_INSTALLATION" },};const sandbox = mockSandbox({ id: "sbx_ref" });diff --git a/packages/eve/src/harness/attachment-staging.ts b/packages/eve/src/harness/attachment-staging.tsindex 3780fd7f2..20c378d7b 100644--- a/packages/eve/src/harness/attachment-staging.ts+++ b/packages/eve/src/harness/attachment-staging.ts@@ -345,7 +345,7 @@ async function tryFetchFile(const adapterKind = getAdapterKind(adapter);try {- const result = await adapter.fetchFile(url);+ const result = await adapter.fetchFile(url, adapterCtx);if (result === null) {return null;}diff --git a/packages/eve/src/public/channels/slack/api.test.ts b/packages/eve/src/public/channels/slack/api.test.tsindex 6e357cbfb..237fb1e6d 100644--- a/packages/eve/src/public/channels/slack/api.test.ts+++ b/packages/eve/src/public/channels/slack/api.test.ts@@ -2,7 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Card, CardText } from "#compiled/chat/index.js";import { decodeSlackApiBody } from "#public/channels/slack/api-encoding.js";-import { buildSlackBinding, callSlackApi } from "#public/channels/slack/api.js";+import {+ buildSlackBinding,+ callSlackApi,+ resolveSlackBotToken,+ type SlackBotTokenContext,+} from "#public/channels/slack/api.js";interface FetchCall {url: string;@@ -956,3 +961,41 @@ describe("auto-anchor on first post", () => {expect(anchors).toHaveLength(1);});});++describe("Slack bot token context", () => {+ let mock: ReturnType<typeof buildFetchMock>;++ beforeEach(() => {+ mock = buildFetchMock();+ vi.stubGlobal("fetch", mock.fetch);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("passes explicit identity to a context-aware token provider", async () => {+ const botToken = vi.fn((context: SlackBotTokenContext) => {+ expect(context).toEqual({ teamId: "T01" });+ return "xoxb-team-one";+ });++ await callSlackApi({+ botToken,+ context: { teamId: "T01" },+ operation: "auth.test",+ body: {},+ });++ expect(botToken).toHaveBeenCalledTimes(1);+ });++ it("keeps zero-argument token providers supported", async () => {+ const botToken = vi.fn(() => "xoxb-legacy");++ const token = await resolveSlackBotToken(botToken, { teamId: "T01" });++ expect(token).toBe("xoxb-legacy");+ expect(botToken).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/eve/src/public/channels/slack/api.ts b/packages/eve/src/public/channels/slack/api.tsindex e794a99aa..9a6b39e30 100644--- a/packages/eve/src/public/channels/slack/api.ts+++ b/packages/eve/src/public/channels/slack/api.ts@@ -24,7 +24,6 @@ import {uploadSlackFiles,type SlackApiOptions,type SlackApiResponse as SlackPrimitiveApiResponse,- type SlackBotToken as SlackPrimitiveBotToken,type SlackFileUpload,type SlackMessageOptions,} from "#compiled/@chat-adapter/slack/api.js";@@ -38,12 +37,16 @@ import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";const log = createLogger("slack.api");+/** Slack app installation workspace available when eve resolves a bot token. */+export interface SlackBotTokenContext {+ readonly teamId?: string;+}+/*** Slack bot token, materialized either as a literal `xoxb-...` string or- * as a (possibly async) function that returns one. The function form- * supports secret-manager lookups and credential rotation.+ * as a (possibly async) function that receives the app installation workspace.*/-export type SlackBotToken = SlackPrimitiveBotToken;+export type SlackBotToken = string | ((context: SlackBotTokenContext) => string | Promise<string>);/*** Builds the channel-local continuation token (`<channelId>:<threadTs>`).@@ -60,9 +63,13 @@ export function slackContinuationToken(channelId: string, threadTs: string): str* Materializes a {@link SlackBotToken} to a string, falling back to* `process.env.SLACK_BOT_TOKEN`. Throws when neither is set.*/-export async function resolveSlackBotToken(token?: SlackBotToken): Promise<string> {+export async function resolveSlackBotToken(+ token?: SlackBotToken,+ context: SlackBotTokenContext = {},+): Promise<string> {const source = token ?? process.env.SLACK_BOT_TOKEN;if (!source) throw new Error("SLACK_BOT_TOKEN is required.");+ if (typeof source === "function") return source(context);return resolveSlackBotTokenPrimitive(source);}@@ -81,13 +88,14 @@ export type SlackApiResponse = SlackPrimitiveApiResponse;*/export async function callSlackApi(input: {readonly botToken: SlackBotToken | undefined;+ readonly context?: SlackBotTokenContext;readonly operation: string;readonly body: unknown;}): Promise<SlackApiResponse> {return callSlackApiPrimitive(input.operation,normalizeSlackApiBody(input.body),- createSlackApiOptions(input.botToken),+ createSlackApiOptions(input.botToken, input.context),);}@@ -98,8 +106,9 @@ export async function callSlackApi(input: {*/function createSlackRequester(botToken: SlackBotToken | undefined,+ context: SlackBotTokenContext,): (operation: string, body: unknown) => Promise<SlackApiResponse> {- return (operation, body) => callSlackApi({ botToken, operation, body });+ return (operation, body) => callSlackApi({ botToken, context, operation, body });}/**@@ -349,11 +358,14 @@ export interface SlackWorkspaceHandle {/** Builds the workspace-scoped API handle used by generic event callbacks. */export function buildSlackWorkspaceHandle(input: {readonly botToken: SlackBotToken | undefined;+ /** Workspace whose app installation supplies the bot token. */+ readonly installationTeamId?: string;+ /** Actor/content workspace exposed on the public handle. */readonly teamId: string | undefined;}): SlackWorkspaceHandle {return {teamId: input.teamId,- request: createSlackRequester(input.botToken),+ request: createSlackRequester(input.botToken, { teamId: input.installationTeamId }),};}@@ -384,10 +396,14 @@ export function buildSlackBinding(input: {readonly botUserId?: string;readonly channelId: string;readonly threadTs: string;+ /** Workspace whose app installation supplies the bot token. */+ readonly installationTeamId?: string;+ /** Actor/content workspace exposed on the public handle. */readonly teamId: string | undefined;readonly onThreadTsChanged?: (ts: string) => void;}): SlackBinding {- const request = createSlackRequester(input.botToken);+ const context = { teamId: input.installationTeamId };+ const request = createSlackRequester(input.botToken, context);let messages: readonly SlackThreadMessage[] = [];let currentThreadTs = input.threadTs;let refreshInFlight: Promise<void> | undefined;@@ -405,7 +421,7 @@ export function buildSlackBinding(input: {const channelId = options?.channelId ?? input.channelId;const threadTs = options?.threadTs ?? currentThreadTs;return uploadSlackFiles(files.map(toSlackFileUpload), {- ...createSlackApiOptions(input.botToken),+ ...createSlackApiOptions(input.botToken, context),channelId: channelId || undefined,initialComment: options?.initialComment,threadTs: threadTs || undefined,@@ -424,7 +440,7 @@ export function buildSlackBinding(input: {}try {const response = await fetchSlackThreadReplies({- ...createSlackApiOptions(input.botToken),+ ...createSlackApiOptions(input.botToken, context),channel: input.channelId,limit: 50,ts: currentThreadTs,@@ -482,7 +498,7 @@ export function buildSlackBinding(input: {}const response = await postSlackMessage(- buildPostMessageOptions(message, input.channelId, currentThreadTs, input.botToken),+ buildPostMessageOptions(message, input.channelId, currentThreadTs, input.botToken, context),);const id = response.id;handleMessageTs(id);@@ -501,7 +517,13 @@ export function buildSlackBinding(input: {async postEphemeral(userId, rawMessage) {const message = normalizePostInput(rawMessage);const response = await postSlackEphemeral({- ...buildPostMessageOptions(message, input.channelId, currentThreadTs, input.botToken),+ ...buildPostMessageOptions(+ message,+ input.channelId,+ currentThreadTs,+ input.botToken,+ context,+ ),user: userId,});return { id: response.id, raw: response.raw };@@ -515,7 +537,7 @@ export function buildSlackBinding(input: {}const message = normalizePostInput(rawMessage);const response = await postSlackMessage(- buildPostMessageOptions(message, imChannelId, "", input.botToken),+ buildPostMessageOptions(message, imChannelId, "", input.botToken, context),);return { id: response.id, raw: response.raw };},@@ -584,9 +606,10 @@ function buildPostMessageOptions(channelId: string,threadTs: string,botToken: SlackBotToken | undefined,+ context: SlackBotTokenContext,): SlackMessageOptions {const base: SlackMessageOptions = {- ...createSlackApiOptions(botToken),+ ...createSlackApiOptions(botToken, context),channel: channelId,threadTs: threadTs || undefined,unfurlLinks: false,@@ -611,8 +634,11 @@ function buildPostMessageOptions(return base;}-function createSlackApiOptions(botToken: SlackBotToken | undefined): SlackApiOptions {- return { token: () => resolveSlackBotToken(botToken) };+function createSlackApiOptions(+ botToken: SlackBotToken | undefined,+ context: SlackBotTokenContext = {},+): SlackApiOptions {+ return { token: () => resolveSlackBotToken(botToken, context) };}function normalizeSlackApiBody(body: unknown): Record<string, unknown> {diff --git a/packages/eve/src/public/channels/slack/attachments.test.ts b/packages/eve/src/public/channels/slack/attachments.test.tsindex 763222824..b48713238 100644--- a/packages/eve/src/public/channels/slack/attachments.test.ts+++ b/packages/eve/src/public/channels/slack/attachments.test.ts@@ -191,17 +191,20 @@ describe("createSlackFetchFile", () => {});});- it("invokes a function-shaped bot token to support rotation", async () => {+ it("resolves function-shaped bot tokens for the session's installation workspace", async () => {const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(new Uint8Array([0]), { status: 200 }));- const tokenFn = vi.fn(async () => "xoxb-rotated-token");+ const tokenFn = vi.fn(async (_context: { readonly teamId?: string }) => "xoxb-rotated-token");const fetchFile = createSlackFetchFile({ botToken: tokenFn });- await fetchFile("https://files.slack.com/x");+ await fetchFile("https://files.slack.com/x", {+ state: { installationTeamId: "T_INSTALLATION", teamId: "T_ACTOR" },+ });expect(tokenFn).toHaveBeenCalledTimes(1);+ expect(tokenFn).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });const [, init] = fetchSpy.mock.calls[0]!;expect((init as RequestInit | undefined)?.headers).toEqual({authorization: "Bearer xoxb-rotated-token",diff --git a/packages/eve/src/public/channels/slack/attachments.ts b/packages/eve/src/public/channels/slack/attachments.tsindex 2c571e754..8ebb20f94 100644--- a/packages/eve/src/public/channels/slack/attachments.ts+++ b/packages/eve/src/public/channels/slack/attachments.ts@@ -1,6 +1,6 @@import type { FilePart, TextPart, UserContent } from "ai";-import type { FetchFileResult } from "#channel/adapter.js";+import type { FetchFileContext, FetchFileResult } from "#channel/adapter.js";import { createLogger } from "#internal/logging.js";import {resolveSlackBotToken,@@ -167,12 +167,15 @@ export function buildSlackTurnMessage(*/export function createSlackFetchFile(input: {readonly botToken?: SlackBotToken;-}): (url: string) => Promise<FetchFileResult | null> {- return async (url) => {+}): (url: string, context?: FetchFileContext) => Promise<FetchFileResult | null> {+ return async (url, context) => {if (!isSlackFileUrl(url)) {return null;}- const token = await resolveSlackBotToken(input.botToken);+ const installationTeamId = context?.state.installationTeamId;+ const token = await resolveSlackBotToken(input.botToken, {+ teamId: typeof installationTeamId === "string" ? installationTeamId : undefined,+ });const response = await fetch(url, {headers: { authorization: `Bearer ${token}` },});diff --git a/packages/eve/src/public/channels/slack/hitl.ts b/packages/eve/src/public/channels/slack/hitl.tsindex f1dd580cb..a994f8f26 100644--- a/packages/eve/src/public/channels/slack/hitl.ts+++ b/packages/eve/src/public/channels/slack/hitl.ts@@ -275,6 +275,8 @@ export function formatInputRequestFallbackText(request: InputRequest): string {export interface HitlFreeformModalMetadata {readonly continuationToken: string;readonly channelId: string;+ /** Workspace whose app installation supplies credentials for modal follow-up API calls. */+ readonly installationTeamId?: string;readonly threadTs: string;readonly messageTs: string;readonly requestId: string;diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.tsindex 34a12bc28..20ed503a0 100644--- a/packages/eve/src/public/channels/slack/inbound.test.ts+++ b/packages/eve/src/public/channels/slack/inbound.test.ts@@ -6,6 +6,7 @@ import {parseDirectMessageEvent,parseMessageEvent,parseSlackEventEnvelope,+ slackEventInstallationTeamId,slackMessageFromWebhookPayload,} from "#public/channels/slack/inbound.js";@@ -55,6 +56,33 @@ describe("parseSlackEventEnvelope", () => {});});+describe("slackEventInstallationTeamId", () => {+ const envelope = (+ authorizations: readonly { is_bot?: boolean; team_id?: string; user_id?: string }[],+ ) => ({ type: "event_callback" as const, authorizations });++ it("prefers the bot installation over other authorizations", () => {+ expect(+ slackEventInstallationTeamId(+ envelope([+ { is_bot: false, team_id: "T_USER", user_id: "U1" },+ { is_bot: true, team_id: "T_BOT", user_id: "U_BOT" },+ ]),+ ),+ ).toBe("T_BOT");+ });++ it("falls back to an authorization that omits is_bot", () => {+ expect(slackEventInstallationTeamId(envelope([{ team_id: "T_UNKNOWN" }]))).toBe("T_UNKNOWN");+ });++ it("accepts an is_bot false authorization for a bot app_mention", () => {+ expect(+ slackEventInstallationTeamId(envelope([{ is_bot: false, team_id: "T_INSTALLATION" }])),+ ).toBe("T_INSTALLATION");+ });+});+describe("parseAppMentionEvent", () => {it("returns a SlackMessage with mrkdwn re-rendered as GFM", () => {const message = parseAppMentionEvent({diff --git a/packages/eve/src/public/channels/slack/inbound.ts b/packages/eve/src/public/channels/slack/inbound.tsindex 0c3aff45e..17ae45179 100644--- a/packages/eve/src/public/channels/slack/inbound.ts+++ b/packages/eve/src/public/channels/slack/inbound.ts@@ -138,6 +138,7 @@ export interface SlackEventCallback {readonly team_id?: string;readonly authorizations?: readonly {readonly is_bot?: boolean;+ readonly team_id?: string;readonly user_id?: string;}[];readonly event?: { readonly type?: string } & Record<string, unknown>;@@ -204,6 +205,20 @@ export function slackEventBotUserId(envelope: SlackEventCallback): string | undereturn authorization?.user_id;}+/** Returns the workspace whose app installation authorized this event. */+export function slackEventInstallationTeamId(envelope: SlackEventCallback): string | undefined {+ const authorizations = envelope.authorizations ?? [];+ const botAuthorization = authorizations.find(+ (entry) => entry.is_bot === true && typeof entry.team_id === "string",+ );+ if (botAuthorization?.team_id !== undefined) return botAuthorization.team_id;+ // Slack documents `app_mention`, which requires a bot user, with+ // `is_bot: false`. The flag describes this authorization, not whether the+ // app installation has a bot, so its team id remains valid token context.+ // See https://docs.slack.dev/reference/events/app_mention.+ return authorizations.find((entry) => typeof entry.team_id === "string")?.team_id;+}+/** Parses a Slack message event without applying bot or subtype policy. */export function parseMessageEvent(envelope: SlackEventCallback): SlackMessage | null {if (envelope.type !== "event_callback") return null;diff --git a/packages/eve/src/public/channels/slack/index.ts b/packages/eve/src/public/channels/slack/index.tsindex 1d6d06d55..acc819d27 100644--- a/packages/eve/src/public/channels/slack/index.ts+++ b/packages/eve/src/public/channels/slack/index.ts@@ -62,6 +62,7 @@ export {slackContinuationToken,type SlackPostInput,type SlackPostedMessage,+ type SlackBotTokenContext,type SlackThreadMessage,type SlackUploadFilesOptions,type SlackUploadFilesResult,diff --git a/packages/eve/src/public/channels/slack/input-response.ts b/packages/eve/src/public/channels/slack/input-response.tsindex 5fe29baaf..d9b4ea593 100644--- a/packages/eve/src/public/channels/slack/input-response.ts+++ b/packages/eve/src/public/channels/slack/input-response.ts@@ -32,6 +32,7 @@ export async function authorizeInputResponse(input: {readonly config: SlackChannelConfig;readonly onInputResponse: NonNullable<SlackChannelConfig["onInputResponse"]>;};+ readonly installationTeamId: string | null | undefined;readonly submission: SlackInputResponseSubmission;readonly teamId: string | null | undefined;readonly threadTs: string;@@ -47,6 +48,7 @@ export async function authorizeInputResponse(input: {botToken: input.deps.config.credentials?.botToken,channelId: input.channelId,threadTs: input.threadTs,+ installationTeamId: input.installationTeamId ?? undefined,teamId: input.teamId ?? undefined,});const ctx: SlackInputResponseContext = { defaultAuth, slack, thread };diff --git a/packages/eve/src/public/channels/slack/interaction-cards.ts b/packages/eve/src/public/channels/slack/interaction-cards.tsnew file mode 100644index 000000000..d051b9dbd--- /dev/null+++ b/packages/eve/src/public/channels/slack/interaction-cards.ts@@ -0,0 +1,203 @@+import { resolveSlackBotToken } from "#public/channels/slack/api.js";+import { buildAnsweredBlocks, isHitlAction } from "#public/channels/slack/hitl.js";+import {+ SLACK_CARD_SUBTEXT_MAX_LENGTH,+ truncateCardSubtext,+} from "#public/channels/slack/limits.js";+import type {+ InteractionHandlerDeps,+ ParsedBlockActionsPayload,+} from "#public/channels/slack/interactions.js";++function buildAnsweredHitlMessageBlocks(input: {+ readonly actionId: string;+ readonly answerLabel: string;+ readonly messageBlocks: readonly unknown[];+ readonly userId: string;+}): unknown[] {+ const actionBlockIndex = input.messageBlocks.findIndex((block) =>+ blockContainsActionId(block, input.actionId),+ );+ if (actionBlockIndex === -1) {+ return buildAnsweredBlocks({+ promptBlocks: findPromptBlocks(input.messageBlocks),+ answerLabel: input.answerLabel,+ userId: input.userId,+ });+ }++ const actionBlock = input.messageBlocks[actionBlockIndex];+ const answeredBlocks =+ answeredBlocksFromActionBlock({+ answerLabel: input.answerLabel,+ block: actionBlock,+ userId: input.userId,+ }) ??+ buildAnsweredBlocks({+ promptBlocks: promptBlocksFromActionBlock(actionBlock),+ answerLabel: input.answerLabel,+ userId: input.userId,+ });+ return [+ ...input.messageBlocks.slice(0, actionBlockIndex),+ ...answeredBlocks,+ ...input.messageBlocks.slice(actionBlockIndex + 1),+ ];+}++function findPromptBlocks(blocks: readonly unknown[]): unknown[] {+ const promptBlocks: unknown[] = [];+ for (const block of blocks) {+ if (!isObjectRecord(block)) continue;+ const type = block.type;+ if (type === "actions") break;+ if (type === "section" || type === "context" || type === "divider" || type === "image") {+ promptBlocks.push(block);+ }+ }+ return promptBlocks;+}++function blockContainsActionId(block: unknown, actionId: string): boolean {+ if (!isObjectRecord(block)) return false;+ return (+ actionsContainActionId(block.elements, actionId) ||+ actionsContainActionId(block.actions, actionId)+ );+}++function actionsContainActionId(actions: unknown, actionId: string): boolean {+ if (!Array.isArray(actions)) return false;+ return actions.some((element) => isObjectRecord(element) && element.action_id === actionId);+}++function answeredBlocksFromActionBlock(input: {+ readonly answerLabel: string;+ readonly block: unknown;+ readonly userId: string;+}): unknown[] | undefined {+ if (!isObjectRecord(input.block) || input.block.type !== "card") return undefined;++ const { actions: _actions, subtext: _subtext, ...blockWithoutActions } = input.block;+ const answeredCard = {+ ...blockWithoutActions,+ subtext: {+ type: "mrkdwn",+ text: formatAnsweredCardSubtext(input),+ verbatim: false,+ },+ };+ return hasCardContent(answeredCard) ? [answeredCard] : undefined;+}++const ANSWERED_CARD_SUBTEXT_PREFIX = ":white_check_mark: *";+const ANSWERED_CARD_SUBTEXT_SUFFIX = "*";++function formatAnsweredCardSubtext(input: {+ readonly answerLabel: string;+ readonly userId: string;+}): string {+ const attribution = input.userId.length > 0 ? ` by <@${input.userId}>` : "";+ const labelBudget =+ SLACK_CARD_SUBTEXT_MAX_LENGTH -+ ANSWERED_CARD_SUBTEXT_PREFIX.length -+ ANSWERED_CARD_SUBTEXT_SUFFIX.length -+ attribution.length;+ const label = truncateWithEllipsis(input.answerLabel, labelBudget);+ return truncateCardSubtext(+ `${ANSWERED_CARD_SUBTEXT_PREFIX}${label}${ANSWERED_CARD_SUBTEXT_SUFFIX}${attribution}`,+ );+}++function truncateWithEllipsis(value: string, maxLength: number): string {+ if (maxLength <= 0) return "";+ if (value.length <= maxLength) return value;+ const sliceLength = Math.max(0, maxLength - 3);+ return `${value.slice(0, sliceLength).trimEnd()}...`;+}++function promptBlocksFromActionBlock(block: unknown): unknown[] {+ if (!isObjectRecord(block) || block.type !== "card") return [];++ const { actions: _actions, ...blockWithoutActions } = block;+ return hasCardContent(blockWithoutActions) ? [blockWithoutActions] : [];+}++function hasCardContent(block: Record<string, unknown>): boolean {+ return block.body !== undefined || block.title !== undefined || block.hero_image !== undefined;+}++function isObjectRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null;+}++export async function updateAnsweredHitlCard(+ interaction: ParsedBlockActionsPayload,+ deps: InteractionHandlerDeps,+): Promise<void> {+ const hitlAction = interaction.actions.find((action) => isHitlAction(action.actionId));+ if (!hitlAction?.messageTs) return;++ const answerLabel = hitlAction.label ?? hitlAction.selectedOptionValue ?? hitlAction.value;+ if (!answerLabel) return;++ const blocks = buildAnsweredHitlMessageBlocks({+ actionId: hitlAction.actionId,+ answerLabel,+ messageBlocks: interaction.messageBlocks,+ userId: hitlAction.user.id,+ });+ await updateAnsweredCard({+ answerLabel,+ blocks,+ channelId: interaction.channelId,+ deps,+ installationTeamId: interaction.installationTeamId,+ messageTs: hitlAction.messageTs,+ });+}++export async function updateAnsweredFreeformCard(input: {+ readonly channelId: string;+ readonly messageTs: string;+ readonly answerLabel: string;+ readonly userId?: string;+ readonly installationTeamId?: string;+ readonly deps: InteractionHandlerDeps;+}): Promise<void> {+ await updateAnsweredCard({+ ...input,+ blocks: buildAnsweredBlocks({+ promptBlocks: [],+ answerLabel: input.answerLabel,+ userId: input.userId,+ }),+ });+}++async function updateAnsweredCard(input: {+ readonly answerLabel: string;+ readonly blocks: unknown[];+ readonly channelId: string;+ readonly deps: InteractionHandlerDeps;+ readonly installationTeamId?: string;+ readonly messageTs: string;+}): Promise<void> {+ const token = await resolveSlackBotToken(input.deps.config.credentials?.botToken, {+ teamId: input.installationTeamId,+ });+ const response = await fetch("https://slack.com/api/chat.update", {+ method: "POST",+ headers: {+ authorization: `Bearer ${token}`,+ "content-type": "application/json; charset=utf-8",+ },+ body: JSON.stringify({+ channel: input.channelId,+ ts: input.messageTs,+ blocks: input.blocks,+ text: `Answered: ${input.answerLabel}`,+ }),+ });+ if (!response.ok) throw new Error(`Slack chat.update returned HTTP ${response.status}`);+}diff --git a/packages/eve/src/public/channels/slack/interactions.test.ts b/packages/eve/src/public/channels/slack/interactions.test.tsindex b992fa89f..68d0ef98f 100644--- a/packages/eve/src/public/channels/slack/interactions.test.ts+++ b/packages/eve/src/public/channels/slack/interactions.test.ts@@ -39,11 +39,18 @@ describe("parseBlockActionsPayload", () => {}});- it("accepts the shared Slack webhook block_actions payload", () => {+ it("separates the installation and actor workspaces in block_actions", () => {const body = new URLSearchParams({payload: JSON.stringify(makePayload({type: "block_actions",+ team: { id: "T_INSTALLATION" },+ user: {+ id: "U0123456789",+ username: "jane.doe",+ name: "jane.doe",+ team_id: "T_ACTOR",+ },actions: [{action_id: "priority",@@ -72,8 +79,9 @@ describe("parseBlockActionsPayload", () => {expect(parsed).toMatchObject({channelId: "C0123456789",+ installationTeamId: "T_INSTALLATION",threadTs: "1700000000.000100",- teamId: "T0123456789",+ teamId: "T_ACTOR",});expect(parsed?.messageBlocks).toHaveLength(1);expect(parsed?.actions[0]).toMatchObject({diff --git a/packages/eve/src/public/channels/slack/interactions.ts b/packages/eve/src/public/channels/slack/interactions.tsindex 468cdc6ba..97b6f2c6f 100644--- a/packages/eve/src/public/channels/slack/interactions.ts+++ b/packages/eve/src/public/channels/slack/interactions.ts@@ -18,7 +18,6 @@ import {} from "#public/channels/slack/api.js";import { buildSlackAuthContext } from "#public/channels/slack/auth.js";import {- buildAnsweredBlocks,buildFreeformModalView,deriveHitlResponse,freeformRequestIdFromActionId,@@ -31,9 +30,9 @@ import {} from "#public/channels/slack/hitl.js";import { readSlackTextObject } from "#public/channels/slack/inbound-content.js";import {- SLACK_CARD_SUBTEXT_MAX_LENGTH,- truncateCardSubtext,-} from "#public/channels/slack/limits.js";+ updateAnsweredFreeformCard,+ updateAnsweredHitlCard,+} from "#public/channels/slack/interaction-cards.js";import {approvalResponderStatePatch,authorizeInputResponse,@@ -59,6 +58,7 @@ const log = createLogger("slack.interactions");interface ParsedBlockActionsPayload {readonly actions: SlackInteractionAction[];readonly channelId: string;+ readonly installationTeamId: string | undefined;readonly threadTs: string;readonly teamId: string | undefined;/**@@ -103,7 +103,7 @@ export function parseBlockActionsPayload(username?: string;name?: string;};- const teamId = team?.id ?? userBlock.team_id;+ const teamId = userBlock.team_id ?? team?.id;const user: SlackInteractionUser = {id: userBlock.id,username: userBlock.username,@@ -123,6 +123,7 @@ export function parseBlockActionsPayload(user,})),channelId: channel,+ installationTeamId: readInstallationTeamId(rawBody),threadTs,teamId,messageBlocks,@@ -155,8 +156,9 @@ function parseSharedBlockActionsPayload(},})),channelId: body.channelId,+ installationTeamId: readInstallationTeamId(body.raw),threadTs: body.threadTs,- teamId: body.teamId,+ teamId: body.user?.teamId ?? body.teamId,messageBlocks: body.messageBlocks ?? [],};}@@ -202,117 +204,29 @@ function readPromptTextFromBlocks(blocks: readonly unknown[]): string | undefinereturn text.length > 0 ? text : undefined;}-function buildAnsweredHitlMessageBlocks(input: {- readonly actionId: string;- readonly answerLabel: string;- readonly messageBlocks: readonly unknown[];- readonly userId: string;-}): unknown[] {- const actionBlockIndex = findActionBlockIndex(input.messageBlocks, input.actionId);- if (actionBlockIndex === -1) {- return buildAnsweredBlocks({- promptBlocks: findPromptBlocks(input.messageBlocks),- answerLabel: input.answerLabel,- userId: input.userId,- });- }-- const actionBlock = input.messageBlocks[actionBlockIndex];- const answeredBlocks =- answeredBlocksFromActionBlock({- answerLabel: input.answerLabel,- block: actionBlock,- userId: input.userId,- }) ??- buildAnsweredBlocks({- promptBlocks: promptBlocksFromActionBlock(actionBlock),- answerLabel: input.answerLabel,- userId: input.userId,- });- return [- ...input.messageBlocks.slice(0, actionBlockIndex),- ...answeredBlocks,- ...input.messageBlocks.slice(actionBlockIndex + 1),- ];-}--function findActionBlockIndex(blocks: readonly unknown[], actionId: string): number {- return blocks.findIndex((block) => blockContainsActionId(block, actionId));-}--function blockContainsActionId(block: unknown, actionId: string): boolean {- if (!isObjectRecord(block)) return false;- return (- actionsContainActionId(block.elements, actionId) ||- actionsContainActionId(block.actions, actionId)- );-}--function actionsContainActionId(actions: unknown, actionId: string): boolean {- if (!Array.isArray(actions)) return false;- return actions.some((element) => isObjectRecord(element) && element.action_id === actionId);-}-function isObjectRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null;}-function answeredBlocksFromActionBlock(input: {- readonly answerLabel: string;- readonly block: unknown;- readonly userId: string;-}): unknown[] | undefined {- if (!isObjectRecord(input.block) || input.block.type !== "card") return undefined;-- const { actions: _actions, subtext: _subtext, ...blockWithoutActions } = input.block;- const answeredCard = {- ...blockWithoutActions,- subtext: {- type: "mrkdwn",- text: formatAnsweredCardSubtext(input),- verbatim: false,- },- };- return hasCardContent(answeredCard) ? [answeredCard] : undefined;-}--const ANSWERED_CARD_SUBTEXT_PREFIX = ":white_check_mark: *";-const ANSWERED_CARD_SUBTEXT_SUFFIX = "*";--function formatAnsweredCardSubtext(input: {- readonly answerLabel: string;- readonly userId: string;-}): string {- const attribution = input.userId.length > 0 ? ` by <@${input.userId}>` : "";- const labelBudget =- SLACK_CARD_SUBTEXT_MAX_LENGTH -- ANSWERED_CARD_SUBTEXT_PREFIX.length -- ANSWERED_CARD_SUBTEXT_SUFFIX.length -- attribution.length;- const label = truncateWithEllipsis(input.answerLabel, labelBudget);- return truncateCardSubtext(- `${ANSWERED_CARD_SUBTEXT_PREFIX}${label}${ANSWERED_CARD_SUBTEXT_SUFFIX}${attribution}`,+function readInstallationTeamId(value: unknown): string | undefined {+ if (!isObjectRecord(value)) return undefined;+ const view = isObjectRecord(value.view) ? value.view : undefined;+ const team = isObjectRecord(value.team) ? value.team : undefined;+ const user = isObjectRecord(value.user) ? value.user : undefined;+ // Slack Connect modal submissions put the installation workspace on the+ // nested view, so it must win over the workspace that submitted the view.+ const candidates = [+ view?.app_installed_team_id,+ value.app_installed_team_id,+ team?.id,+ user?.team_id,+ view?.team_id,+ ];+ return candidates.find(+ (candidate): candidate is string => typeof candidate === "string" && candidate.length > 0,);}-function truncateWithEllipsis(value: string, maxLength: number): string {- if (maxLength <= 0) return "";- if (value.length <= maxLength) return value;- const sliceLength = Math.max(0, maxLength - 3);- return `${value.slice(0, sliceLength).trimEnd()}...`;-}--function promptBlocksFromActionBlock(block: unknown): unknown[] {- if (!isObjectRecord(block) || block.type !== "card") return [];-- const { actions: _actions, ...blockWithoutActions } = block;- return hasCardContent(blockWithoutActions) ? [blockWithoutActions] : [];-}--function hasCardContent(block: Record<string, unknown>): boolean {- return block.body !== undefined || block.title !== undefined || block.hero_image !== undefined;-}-/** Channel-supplied dependencies for {@link handleInteractionPost}. */export interface InteractionHandlerDeps {readonly config: SlackChannelConfig;@@ -395,6 +309,7 @@ export async function handleInteractionPost(botToken: deps.config.credentials?.botToken,channelId: interaction.channelId,threadTs: interaction.threadTs,+ installationTeamId: interaction.installationTeamId,teamId: interaction.teamId,});const slackCtx: SlackInteractionContext = {@@ -411,6 +326,7 @@ export async function handleInteractionPost(resolveSession: ctx.resolveSession,state: {channelId: interaction.channelId,+ installationTeamId: interaction.installationTeamId ?? null,teamId: interaction.teamId ?? null,threadTs: interaction.threadTs,triggeringUserId: actionUser.id,@@ -443,6 +359,7 @@ async function dispatchBlockInputResponses(input: {const result = await authorizeInputResponse({channelId: input.interaction.channelId,deps: input.deps,+ installationTeamId: input.interaction.installationTeamId,submission: input.submission,teamId: input.interaction.teamId,threadTs: input.interaction.threadTs,@@ -505,6 +422,7 @@ async function openFreeformModal(input: {input.interaction.threadTs,),channelId: input.interaction.channelId,+ installationTeamId: input.interaction.installationTeamId,threadTs: input.interaction.threadTs,messageTs,requestId,@@ -512,7 +430,9 @@ async function openFreeformModal(input: {const promptText = readPromptTextFromBlocks(input.interaction.messageBlocks);const view = buildFreeformModalView({ metadata, prompt: promptText });- const token = await resolveSlackBotToken(input.deps.config.credentials?.botToken);+ const token = await resolveSlackBotToken(input.deps.config.credentials?.botToken, {+ teamId: input.interaction.installationTeamId,+ });const response = await fetch("https://slack.com/api/views.open", {method: "POST",@@ -569,6 +489,7 @@ async function handleViewSubmission(const user = payload.user;const triggeringUserId = payload.userId;const teamId = user?.teamId ?? payload.teamId ?? null;+ const installationTeamId = metadata.installationTeamId ?? readInstallationTeamId(payload.raw);const submission: SlackInputResponseSubmission = {type: "view_submission",inputResponses: [parseInputResponse({ requestId: metadata.requestId, text })],@@ -580,7 +501,17 @@ async function handleViewSubmission(},};- ctx.waitUntil(dispatchViewInputResponse({ ctx, deps, metadata, submission, teamId, text }));+ ctx.waitUntil(+ dispatchViewInputResponse({+ ctx,+ deps,+ installationTeamId,+ metadata,+ submission,+ teamId,+ text,+ }),+ );return ack;}@@ -588,6 +519,7 @@ async function handleViewSubmission(async function dispatchViewInputResponse(input: {readonly ctx: { from: ChannelFrom<SlackChannelState> };readonly deps: InteractionHandlerDeps;+ readonly installationTeamId: string | undefined;readonly metadata: HitlFreeformModalMetadata;readonly submission: Extract<SlackInputResponseSubmission, { type: "view_submission" }>;readonly teamId: string | null;@@ -596,6 +528,7 @@ async function dispatchViewInputResponse(input: {const result = await authorizeInputResponse({channelId: input.metadata.channelId,deps: input.deps,+ installationTeamId: input.installationTeamId,submission: input.submission,teamId: input.teamId,threadTs: input.metadata.threadTs,@@ -619,6 +552,7 @@ async function dispatchViewInputResponse(input: {messageTs: input.metadata.messageTs,answerLabel: input.text,userId: input.submission.user.id,+ installationTeamId: input.installationTeamId,deps: input.deps,});} catch (error) {@@ -626,71 +560,4 @@ async function dispatchViewInputResponse(input: {}}-async function updateAnsweredHitlCard(- interaction: ParsedBlockActionsPayload,- deps: InteractionHandlerDeps,-): Promise<void> {- const hitlAction = interaction.actions.find((a) => isHitlAction(a.actionId));- if (!hitlAction || !hitlAction.messageTs) return;-- const answerLabel = hitlAction.label ?? hitlAction.selectedOptionValue ?? hitlAction.value;- if (!answerLabel) return;-- const blocks = buildAnsweredHitlMessageBlocks({- actionId: hitlAction.actionId,- answerLabel,- messageBlocks: interaction.messageBlocks,- userId: hitlAction.user.id,- });-- const token = await resolveSlackBotToken(deps.config.credentials?.botToken);- const response = await fetch("https://slack.com/api/chat.update", {- method: "POST",- headers: {- authorization: `Bearer ${token}`,- "content-type": "application/json; charset=utf-8",- },- body: JSON.stringify({- channel: interaction.channelId,- ts: hitlAction.messageTs,- blocks,- text: `Answered: ${answerLabel}`,- }),- });- if (!response.ok) {- throw new Error(`Slack chat.update returned HTTP ${response.status}`);- }-}--async function updateAnsweredFreeformCard(input: {- readonly channelId: string;- readonly messageTs: string;- readonly answerLabel: string;- readonly userId?: string;- readonly deps: InteractionHandlerDeps;-}): Promise<void> {- const blocks = buildAnsweredBlocks({- promptBlocks: [],- answerLabel: input.answerLabel,- userId: input.userId,- });- const token = await resolveSlackBotToken(input.deps.config.credentials?.botToken);- const response = await fetch("https://slack.com/api/chat.update", {- method: "POST",- headers: {- authorization: `Bearer ${token}`,- "content-type": "application/json; charset=utf-8",- },- body: JSON.stringify({- channel: input.channelId,- ts: input.messageTs,- blocks,- text: `Answered: ${input.answerLabel}`,- }),- });- if (!response.ok) {- throw new Error(`Slack chat.update returned HTTP ${response.status}`);- }-}-export type { ParsedBlockActionsPayload };diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 6bac484fb..7819e1e46 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -18,6 +18,7 @@ import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import { decodeSlackApiBody } from "#public/channels/slack/api-encoding.js";import {HITL_ACTION_PREFIX,+ HITL_FREEFORM_ACTION_PREFIX,HITL_FREEFORM_MODAL_ACTION_ID,HITL_FREEFORM_MODAL_BLOCK_ID,HITL_FREEFORM_MODAL_CALLBACK_ID,@@ -1088,6 +1089,48 @@ describe("rebuildSlackContext", () => {expect("id" in ctx.thread).toBe(false);});+ it("keeps actor identity public while reusing the installation workspace for credentials", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ }),+ ),+ );+ const adapter = withState(getAdapter(slackChannel({ credentials: { botToken } })), {+ ...THREAD_STATE,+ installationTeamId: "T_INSTALLATION",+ teamId: "T_ACTOR",+ });+ const ctx = buildAdapterContext(adapter, stubAccessor());++ expect(ctx.slack.teamId).toBe("T_ACTOR");+ await ctx.slack.request("auth.test", {});+ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });+ });++ it("does not fall back to the actor workspace for legacy session credentials", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ }),+ ),+ );+ const adapter = withState(getAdapter(slackChannel({ credentials: { botToken } })), {+ ...THREAD_STATE,+ teamId: "T_ACTOR",+ });+ const ctx = buildAdapterContext(adapter, stubAccessor());++ await ctx.slack.request("auth.test", {});+ expect(botToken).toHaveBeenCalledWith({ teamId: undefined });+ });+it("falls back to empty strings when state has no thread", () => {const adapter = withState(getAdapter(slackChannel()), {channelId: null,@@ -1278,6 +1321,39 @@ describe("slackChannel() inbound mention pipeline", () => {});});+ it("uses the app installation workspace for mention credentials", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ const channel = slackChannel({+ credentials: { botToken },+ async onAppMention(ctx) {+ expect(ctx.slack.teamId).toBe("T_ACTOR");+ return { auth: null };+ },+ });+ const body = buildEventBody(+ {+ channel: "C01",+ event_ts: "1700000000.000001",+ text: "hello",+ ts: "1700000000.000001",+ type: "app_mention",+ user: "U01",+ },+ {+ authorizations: [{ is_bot: true, team_id: "T_INSTALLATION", user_id: "U_BOT" }],+ teamId: "T_ACTOR",+ },+ );++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });+ expect(send.mock.calls[0]?.[1].state).toMatchObject({+ installationTeamId: "T_INSTALLATION",+ teamId: "T_ACTOR",+ });+ });+it("exposes private conversation detection to message handlers", async () => {fetchMock.mockResolvedValue(new Response(JSON.stringify({ ok: true, channel: { is_private: false } }), {@@ -1347,6 +1423,7 @@ describe("slackChannel() inbound mention pipeline", () => {state: {audience: "unknown",channelId: "C_BOUND",+ installationTeamId: null,teamId: "T01",threadTs: "1700000000.000300",triggeringUserId: "U01",@@ -1934,6 +2011,7 @@ describe("slackChannel() generic Events API pipeline", () => {});it("passes arbitrary Events API payloads with workspace API access", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");const onEvent = vi.fn(async (ctx, event) => {expect(event).toEqual({item: { channel: "C01", ts: "1700000000.000001", type: "message" },@@ -1945,16 +2023,16 @@ describe("slackChannel() generic Events API pipeline", () => {api_app_id: "A01",event_id: "Ev_reaction",event_time: 1_700_000_123,- team_id: "T_WORKSPACE",+ team_id: "T_ACTOR",});- expect(ctx.slack.teamId).toBe("T_WORKSPACE");+ expect(ctx.slack.teamId).toBe("T_ACTOR");await ctx.slack.request("reactions.get", {channel: "C01",timestamp: "1700000000.000001",});});const channel = slackChannel({- credentials: { botToken: "xoxb-test" },+ credentials: { botToken },onEvent,});const body = buildEventBody(@@ -1964,7 +2042,12 @@ describe("slackChannel() generic Events API pipeline", () => {type: "reaction_added",user: "U01",},- { eventId: "Ev_reaction", eventTime: 1_700_000_123, teamId: "T_WORKSPACE" },+ {+ authorizations: [{ is_bot: true, team_id: "T_INSTALLATION", user_id: "U_BOT" }],+ eventId: "Ev_reaction",+ eventTime: 1_700_000_123,+ teamId: "T_ACTOR",+ },);const { response, send } = await firePost(channel, buildSignedRequest({ body }));@@ -1974,6 +2057,7 @@ describe("slackChannel() generic Events API pipeline", () => {expect(send).not.toHaveBeenCalled();expect(fetchMock).toHaveBeenCalledTimes(1);expect(String(fetchMock.mock.calls[0]![0])).toBe("https://slack.com/api/reactions.get");+ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });});it("cancels a targeted Slack thread from onEvent", async () => {@@ -2034,6 +2118,7 @@ describe("slackChannel() generic Events API pipeline", () => {message: "follow up",state: {channelId: "C01",+ installationTeamId: null,teamId: "T_WORKSPACE",threadTs: "1700000000.000001",triggeringUserId: "U01",@@ -2501,6 +2586,46 @@ describe("slackChannel() HITL interaction pipeline", () => {expect(send).not.toHaveBeenCalled();});+ it("keeps interaction auth on the actor workspace and credentials on the installation", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ fetchMock.mockImplementation(+ async () =>+ new Response(JSON.stringify({ ok: true }), {+ headers: { "content-type": "application/json" },+ }),+ );+ const channel = slackChannel({+ credentials: { botToken },+ async onInteraction(_action, ctx) {+ expect(ctx.slack.teamId).toBe("T_ACTOR");+ await ctx.slack.request("auth.test", {});+ await ctx.send("inspect result");+ },+ });++ const { send } = await firePost(+ channel,+ buildSignedInteractionRequest({+ type: "block_actions",+ team: { id: "T_INSTALLATION" },+ user: { id: "U01", username: "ada", team_id: "T_ACTOR" },+ channel: { id: "C01" },+ message: {+ ts: "1700000000.000010",+ thread_ts: "1700000000.000001",+ blocks: [],+ },+ actions: [{ action_id: "inspect", text: { type: "plain_text", text: "Inspect" } }],+ }),+ );++ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });+ expect(send.mock.calls[0]?.[1]).toMatchObject({+ auth: { principalId: "slack:T_ACTOR:U01" },+ state: { installationTeamId: "T_INSTALLATION", teamId: "T_ACTOR" },+ });+ });+it("resets the interaction's Slack thread from onInteraction", async () => {const channel = slackChannel({credentials: { botToken: "xoxb-test" },@@ -2539,18 +2664,19 @@ describe("slackChannel() HITL interaction pipeline", () => {});it("resumes HITL button answers with the approving Slack user auth", async () => {- const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ const channel = slackChannel({ credentials: { botToken } });const { send } = await firePost(channel,buildSignedInteractionRequest({type: "block_actions",- team: { id: "T01" },+ team: { id: "T_INSTALLATION" },user: {id: "U_APPROVER",username: "ada",name: "ada",- team_id: "T01",+ team_id: "T_ACTOR",},channel: { id: "C01" },message: {@@ -2576,19 +2702,19 @@ describe("slackChannel() HITL interaction pipeline", () => {attributes: {author_type: "user",channel_id: "C01",- team_id: "T01",+ team_id: "T_ACTOR",thread_ts: "1700000000.000001",user_id: "U_APPROVER",user_name: "ada",},authenticator: "slack-webhook",- issuer: "slack:T01",- principalId: "slack:T01:U_APPROVER",+ issuer: "slack:T_ACTOR",+ principalId: "slack:T_ACTOR:U_APPROVER",principalType: "user",},inputResponses: [{ optionId: "approve", requestId: "approval_abc123" }],state: {- approvalResponderUsers: { "slack:T01:U_APPROVER": "U_APPROVER" },+ approvalResponderUsers: { "slack:T_ACTOR:U_APPROVER": "U_APPROVER" },},});expect(@@ -2603,6 +2729,46 @@ describe("slackChannel() HITL interaction pipeline", () => {});});+ it("opens freeform modals with installation-scoped credentials and metadata", async () => {+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ const channel = slackChannel({ credentials: { botToken } });++ await firePost(+ channel,+ buildSignedInteractionRequest({+ type: "block_actions",+ trigger_id: "trigger-123",+ team: { id: "T_INSTALLATION" },+ user: { id: "U01", username: "ada", team_id: "T_ACTOR" },+ channel: { id: "C01" },+ message: {+ ts: "1700000000.000010",+ thread_ts: "1700000000.000001",+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "Explain" } }],+ },+ actions: [+ {+ action_id: `${HITL_FREEFORM_ACTION_PREFIX}call_abc123`,+ text: { type: "plain_text", text: "Type your answer" },+ value: "call_abc123",+ },+ ],+ }),+ );++ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });+ const openCall = fetchMock.mock.calls.find(+ ([url]) => String(url) === "https://slack.com/api/views.open",+ );+ expect(openCall).toBeDefined();+ const body = JSON.parse(String((openCall![1] as RequestInit).body)) as {+ view: { private_metadata: string };+ };+ expect(JSON.parse(body.view.private_metadata)).toMatchObject({+ installationTeamId: "T_INSTALLATION",+ });+ });+it("authorizes HITL button answers before resuming with the returned auth", async () => {const customAuth = {attributes: { role: "deployer" },@@ -2998,20 +3164,22 @@ describe("slackChannel() HITL interaction pipeline", () => {});it("resumes freeform modal answers with the submitting Slack user auth", async () => {- const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ const channel = slackChannel({ credentials: { botToken } });const { send } = await firePost(channel,buildSignedInteractionRequest({type: "view_submission",- team: { id: "T01" },+ team: { id: "T_ACTOR" },user: {id: "U_SUBMITTER",username: "grace",name: "grace",- team_id: "T01",+ team_id: "T_ACTOR",},view: {+ app_installed_team_id: "T_INSTALLATION",callback_id: HITL_FREEFORM_MODAL_CALLBACK_ID,private_metadata: JSON.stringify({channelId: "C01",@@ -3039,18 +3207,19 @@ describe("slackChannel() HITL interaction pipeline", () => {attributes: {author_type: "user",channel_id: "C01",- team_id: "T01",+ team_id: "T_ACTOR",thread_ts: "1700000000.000001",user_id: "U_SUBMITTER",user_name: "grace",},authenticator: "slack-webhook",- issuer: "slack:T01",- principalId: "slack:T01:U_SUBMITTER",+ issuer: "slack:T_ACTOR",+ principalId: "slack:T_ACTOR:U_SUBMITTER",principalType: "user",},inputResponses: [{ requestId: "call_abc123", text: "approved with context" }],});+ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });});it("authorizes freeform modal answers before resuming", async () => {@@ -3182,8 +3351,10 @@ describe("slackChannel().receive", () => {vi.unstubAllGlobals();});- function buildReceive() {- const channel = slackChannel({ credentials: { botToken: "xoxb-test" } });+ function buildReceive(+ botToken: string | ((context: { readonly teamId?: string }) => string) = "xoxb-test",+ ) {+ const channel = slackChannel({ credentials: { botToken } });const compiled = asCompiled(channel);if (!compiled.receive) throw new Error("expected compiled.receive");return compiled.receive;@@ -3205,6 +3376,7 @@ describe("slackChannel().receive", () => {expect(input.message).toBe("do the thing");expect(input.state).toEqual({channelId: "C123",+ installationTeamId: null,threadTs: "1700000000.000001",teamId: null,triggeringUserId: null,@@ -3212,6 +3384,36 @@ describe("slackChannel().receive", () => {expect(input.auth.principalId).toBe("p");});+ it("selects and persists the installation workspace for proactive sends", async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ ok: true, ts: "1800000000.000900" }), {+ headers: { "content-type": "application/json" },+ }),+ );+ const botToken = vi.fn((_context: { readonly teamId?: string }) => "xoxb-test");+ const send = vi.fn().mockResolvedValue({ id: "s" });+ const { Card, CardText } = await import("#compiled/chat/index.js");++ await buildReceive(botToken)(+ {+ message: "start the investigation",+ target: {+ channelId: "C123",+ installationTeamId: "T_INSTALLATION",+ initialMessage: { card: Card({ children: [CardText("Investigation")] }) },+ },+ auth: null,+ },+ mockChannelContext(send),+ );++ expect(botToken).toHaveBeenCalledWith({ teamId: "T_INSTALLATION" });+ expect(send.mock.calls[0]?.[1].state).toMatchObject({+ installationTeamId: "T_INSTALLATION",+ teamId: null,+ });+ });+it("gives each threadless proactive session a unique temporary continuation token", async () => {const randomUUID = vi.spyOn(crypto, "randomUUID")diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 2d34731aa..ab48fba9e 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -44,6 +44,7 @@ import {parseMessageEvent,type SlackEvent,slackEventBotUserId,+ slackEventInstallationTeamId,type SlackEventEnvelope,type SlackInboundContext,type SlackMessage,@@ -198,6 +199,8 @@ export interface SlackChannelState {threadTs: string | null;/** Slack team id, when the inbound event carried one. */teamId: string | null;+ /** Slack workspace whose app installation supplies this session's credentials. */+ 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.@@ -255,7 +258,8 @@ export interface SlackInstrumentationMetadata extends Record<string, unknown> {*/export interface SlackChannelCredentials {/**- * Bot token for all outbound Slack Web API calls. Falls back to+ * Bot token for all outbound Slack Web API calls. Function providers receive+ * the app installation workspace id when Slack supplies one. Falls back to* `process.env.SLACK_BOT_TOKEN` when omitted.*/readonly botToken?: SlackBotToken;@@ -277,6 +281,8 @@ export interface SlackChannelCredentials {export interface SlackReceiveTarget {readonly channelId: string;readonly threadTs?: string;+ /** Slack workspace whose app installation supplies credentials for this send. */+ readonly installationTeamId?: string;/*** Optional message posted into the Slack channel before the agent runs.* The post becomes the thread root and the first turn is threaded under@@ -674,6 +680,7 @@ function rebuildSlackContext(botToken: credentials?.botToken,channelId: state.channelId ?? "",threadTs: state.threadTs ?? "",+ installationTeamId: state.installationTeamId ?? undefined,teamId: state.teamId ?? undefined,onThreadTsChanged(ts) {state.threadTs = ts;@@ -763,6 +770,7 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {channelId: null as string | null,threadTs: null as string | null,teamId: null as string | null,+ installationTeamId: null as string | null,triggeringUserId: null,pendingToolCallMessage: null,lastReasoningTypingAtMs: null,@@ -861,6 +869,8 @@ async function receiveOnSlack(deps: {readonly from: ChannelFrom<SlackChannelState>;readonly credentials: SlackChannelCredentials | undefined;+ /** Installation workspace inherited from an inbound trigger. */+ readonly installationTeamId?: string;/** Slack team id seeded into session state, when the trigger carried one. */readonly teamId?: string;/** Slack user id seeded into session state, when the trigger carried one. */@@ -874,6 +884,10 @@ async function receiveOnSlack(}const requestedThreadTs =typeof receiveTarget.threadTs === "string" ? receiveTarget.threadTs : "";+ const installationTeamId =+ typeof receiveTarget.installationTeamId === "string"+ ? receiveTarget.installationTeamId+ : deps.installationTeamId;const initialMessage = receiveTarget.initialMessage;if (initialMessage && requestedThreadTs.length > 0) {throw new Error(@@ -887,6 +901,7 @@ async function receiveOnSlack(botToken: deps.credentials?.botToken,channelId,threadTs: "",+ installationTeamId,teamId: deps.teamId,});const postInput: { card: CardElement; fallbackText?: string } = {@@ -907,6 +922,7 @@ async function receiveOnSlack(auth: input.auth,state: {channelId,+ installationTeamId: installationTeamId ?? null,threadTs: threadTs || null,teamId: deps.teamId ?? null,triggeringUserId: deps.triggeringUserId ?? null,@@ -979,6 +995,7 @@ async function handleEventPost(input: {if (envelope === null) return new Response("ok");const appId = typeof envelope.api_app_id === "string" ? envelope.api_app_id : undefined;const botUserId = slackEventBotUserId(envelope);+ const installationTeamId = slackEventInstallationTeamId(envelope);// Handler precedence, in fall-through order:// 1) an authored mention/DM handler for its own event kind,@@ -1000,6 +1017,7 @@ async function handleEventPost(input: {resolveSession: input.resolveSession,credentials: config.credentials,handler,+ installationTeamId,kind,message,threadContext: config.threadContext,@@ -1016,6 +1034,7 @@ async function handleEventPost(input: {resolveSession: input.resolveSession,credentials: config.credentials,handler,+ installationTeamId,kind,message,threadContext: config.threadContext,@@ -1043,6 +1062,7 @@ async function handleEventPost(input: {resolveSession: input.resolveSession,credentials: config.credentials,handler: config.onMessage!,+ installationTeamId,kind: "channel_message",message,threadContext: config.threadContext,@@ -1063,6 +1083,7 @@ async function handleEventPost(input: {credentials: config.credentials,envelope,handler: onEvent,+ installationTeamId,});}@@ -1107,6 +1128,7 @@ async function dispatchSlackMessage(input: {readonly resolveSession: ChannelResolveSession;readonly credentials: SlackChannelCredentials | undefined;readonly handler: NonNullable<SlackChannelConfig["onMessage"]>;+ readonly installationTeamId: string | undefined;readonly kind: "app_mention" | "channel_message" | "direct_message";readonly message: SlackMessage;readonly threadContext: LoadThreadContextMessagesOptions | undefined;@@ -1119,12 +1141,14 @@ async function dispatchSlackMessage(input: {botUserId: input.botUserId,channelId: input.message.channelId,threadTs: input.message.threadTs,+ installationTeamId: input.installationTeamId,teamId: input.message.teamId,});const author = input.message.author;const channelState: SlackChannelState = {audience: "unknown",channelId: input.message.channelId,+ installationTeamId: input.installationTeamId ?? null,teamId: input.message.teamId ?? null,threadTs: input.message.threadTs,triggeringUserId: author?.userId ?? null,@@ -1199,6 +1223,7 @@ async function dispatchSlackEvent(input: {readonly credentials: SlackChannelCredentials | undefined;readonly envelope: SlackEventEnvelope;readonly handler: NonNullable<SlackChannelConfig["onEvent"]>;+ readonly installationTeamId: string | undefined;}): Promise<void> {const eventTeamId = input.envelope.event.team_id;const teamId =@@ -1226,6 +1251,7 @@ async function dispatchSlackEvent(input: {{from: input.from,credentials: input.credentials,+ installationTeamId: input.installationTeamId,teamId,...(typeof input.envelope.event.user === "string"? { triggeringUserId: input.envelope.event.user }@@ -1234,6 +1260,7 @@ async function dispatchSlackEvent(input: {),slack: buildSlackWorkspaceHandle({botToken: input.credentials?.botToken,+ installationTeamId: input.installationTeamId,teamId,}),waitUntil(task) {diff --git a/packages/eve/src/shared/channel-definition.ts b/packages/eve/src/shared/channel-definition.tsindex b54a24d39..4660f6ea5 100644--- a/packages/eve/src/shared/channel-definition.ts+++ b/packages/eve/src/shared/channel-definition.ts@@ -22,7 +22,15 @@ export interface FetchFileResult {readonly filename?: string;}-export type FetchFileFunction = (url: string) => Promise<Buffer | FetchFileResult | null>;+/** Runtime context supplied while resolving a channel-owned file URL. */+export interface FetchFileContext {+ readonly state: Readonly<Record<string, unknown>>;+}++export type FetchFileFunction = (+ url: string,+ context?: FetchFileContext,+) => Promise<Buffer | FetchFileResult | null>;/*** Input passed to a channel's `receive` callback when another channel ordiff --git a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.tsindex 20e8c8824..404efd6f3 100644--- a/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts+++ b/packages/eve/test/scenarios/mounted-extension-installed.scenario.test.ts@@ -249,7 +249,7 @@ describe("mounted extension installed under node_modules", () => {);expect(JSON.parse(extensionFiles[`node_modules/${PACKAGE_NAME}/dist/extension/_manifest.json`]!),- ).toMatchObject({ requires: { channel: 7, schedule: 3, subagent: 2 } });+ ).toMatchObject({ requires: { channel: 8, schedule: 3, subagent: 2 } });const app = await scenarioApp({name: "mounted-extension-installed",installDependencies: true,