The Open Framework for Building Agents
fix(eve): expose receiving bot identity to models (#2561)
Ruid79de0bd78ec
diff --git a/.changeset/tender-bots-context.md b/.changeset/tender-bots-context.mdnew file mode 100644index 000000000..18397152a--- /dev/null+++ b/.changeset/tender-bots-context.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Expose channel-native receiver identity in model context, plus exact mention state for Slack, Teams, Telegram, and GitHub comments.diff --git a/docs/channels/discord.mdx b/docs/channels/discord.mdxindex a4de64d9e..f81b63ed4 100644--- a/docs/channels/discord.mdx+++ b/docs/channels/discord.mdx@@ -56,7 +56,11 @@ Then configure the public `https://…/eve/v1/discord` route as the application'### Dispatch-`onCommand(ctx, interaction)` decides whether to dispatch and under what `auth`. Return `{ auth }` to proceed, `null` to drop the interaction, or `title` alongside `auth` to set the title when the dispatch starts a run. By default, auth comes from the invoking user. Event handlers receive `(eventData, channel, ctx)`, with Discord platform handles on `channel.discord`:+`onCommand(ctx, interaction)` decides whether to dispatch and under what `auth`. Return `{ auth }` to proceed, `null` to drop the interaction, or `title` alongside `auth` to set the title when the dispatch starts a run. By default, auth comes from the invoking user.++The model-visible `<discord_context>` includes `user_id` and the receiving application's `application_id`.++Event handlers receive `(eventData, channel, ctx)`, with Discord platform handles on `channel.discord`:```tsimport { discordChannel } from "eve/channels/discord";diff --git a/docs/channels/github.mdx b/docs/channels/github.mdxindex 1a4a8e473..02bbfb0cd 100644--- a/docs/channels/github.mdx+++ b/docs/channels/github.mdx@@ -68,6 +68,8 @@ Point the GitHub App webhook URL at `https://<deployment>/eve/v1/github`. For coInbound hooks return `{ auth }` to dispatch, or `null` to ignore. Return `title` alongside `auth` to set the title when the dispatch starts a run. Use `defaultGitHubAuth(ctx)` to derive auth from the actor.+The model-visible `<github_context>` includes `sender`, `bot_name` when resolved, and `is_mentioned` for comments. eve computes `is_mentioned` before removing the invocation token.+```tsimport { defaultGitHubAuth, githubChannel } from "eve/channels/github";diff --git a/docs/channels/linear.mdx b/docs/channels/linear.mdxindex d52e47523..572377d6c 100644--- a/docs/channels/linear.mdx+++ b/docs/channels/linear.mdx@@ -71,7 +71,7 @@ Linear sends webhook signatures in `Linear-Signature`; eve verifies the HMAC ove### Dispatch-The default hook dispatches `created` and `prompted` Agent Session events. eve adds a Linear context block with the agent session, issue, comment, and organization identifiers, then continues the same session with `agent-session:<id>`.+The default hook dispatches `created` and `prompted` Agent Session events. The Linear context includes `app_user_id` when available, plus the agent session, issue, comment, and organization identifiers. The session continues with `agent-session:<id>`.### Deliverydiff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 3810d1a0d..3b5021840 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -156,6 +156,8 @@ Only the first available handler runs. A message hook returning `null` drops the`onInteraction(action, ctx)` separately handles user-owned `block_actions` callbacks. eve-owned HITL buttons and modal submissions go through `onInputResponse(ctx, submission)` instead. eve attaches the triggering Slack user id to the same model message as its text, preserving speaker attribution without profile lookups.+The model-visible `<slack_message>` includes `sender_id`, `bot_user_id` when available, and the `is_mentioned` value from `ctx.isBotMentioned()`. Its `<content>` keeps `<@USER_ID>` intact while converting other mrkdwn to Markdown; routing is unchanged.+#### Restrict who can invoke the agentA valid Slack signature proves that Slack sent the event. It does not decide which channel or person your agent should trust. Fail closed in the inbound handler before returning auth, especially when the app is installed in a shared Slack Connect channel:diff --git a/docs/channels/teams.mdx b/docs/channels/teams.mdxindex 633a20ed2..9ec8d7f54 100644--- a/docs/channels/teams.mdx+++ b/docs/channels/teams.mdx@@ -26,7 +26,7 @@ By default the channel mounts at `POST /eve/v1/teams`. Point your Azure Bot or T### Dispatch-The default `onMessage` handles two cases: personal-chat messages, and channel or group-chat messages that mention the bot directly. Ambient resource-specific-consent messages are dropped unless you override it. Return `title` alongside `auth` to set the title when the dispatch starts a run. Before dispatch, eve strips the mention, adds a `<teams_context>` block, and scopes channel and group threads by root activity id (`replyToId ?? id`).+The default `onMessage` handles two cases: personal-chat messages, and channel or group-chat messages that mention the bot directly. Ambient resource-specific-consent messages are dropped unless you override it. Return `title` alongside `auth` to set the title when the dispatch starts a run. Before dispatch, eve strips the mention, adds `<teams_context>` with `user_id`, `bot_id`, and `is_mentioned`, and scopes channel and group threads by root activity id (`replyToId ?? id`).For example, use the contextual `isSubscribed()` helper to continue active threads without requiring another mention:diff --git a/docs/channels/telegram.mdx b/docs/channels/telegram.mdxindex 7ddb65510..f67e5ac06 100644--- a/docs/channels/telegram.mdx+++ b/docs/channels/telegram.mdx@@ -37,6 +37,8 @@ curl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \In a private chat, text, captions, photos, and documents all go through. Groups are stricter. Only three things wake the bot: a command (`/ask`, `/ask@my_bot`), an `@my_bot` mention (when `botUsername` is set), or a reply to one of the bot's own messages. Everything else is ignored.+The model-visible `<telegram_context>` includes `bot_username` and `is_mentioned`. `is_mentioned` is `true` only for an exact `@bot_username` token or targeted command such as `/ask@my_bot`; other accepted messages set it to `false`.+Forum topics carry `message_thread_id` in the continuation token, so each topic stays on its own thread.To customize auth or filtering, override `onMessage`. Return `title` alongside `auth` to set the title when the dispatch starts a run. Group privacy mode itself lives in BotFather, not here.diff --git a/packages/eve/src/public/channels/discord/discordChannel.test.ts b/packages/eve/src/public/channels/discord/discordChannel.test.tsindex 9414fdb05..62cc73bd8 100644--- a/packages/eve/src/public/channels/discord/discordChannel.test.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.test.ts@@ -218,6 +218,7 @@ describe("discordChannel() inbound route", () => {expect(send).toHaveBeenCalledTimes(1);const [continuationToken, input] = send.mock.calls[0]!;expect((input as { context: string[] }).context[0]).toContain("<discord_context>");+ expect((input as { context: string[] }).context[0]).toContain("application_id: APP1");expect(String((input as { message: string }).message)).toContain("hello discord");expect(continuationToken).toBe("C01:I01");expect(input).toMatchObject({diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex e300a919e..cae98085a 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -4,7 +4,6 @@ import type { SessionHandle } from "#channel/session.js";import type { SessionAuthContext, TurnPolicy } from "#channel/types.js";import type { SessionContext } from "#public/definitions/callback-context.js";import type { ChannelContinuationOps } from "#public/definitions/channel.js";-import { createLogger, logError } from "#internal/logging.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";import {@@ -594,6 +593,7 @@ async function dispatchCommand(input: {}): Promise<void> {const turnMessage = commandInteractionMessage(input.interaction);const contextBlock = formatDiscordContextBlock({+ applicationId: input.interaction.applicationId,channelId: input.interaction.channelId,commandName: input.interaction.commandName,guildId: input.interaction.guildId,diff --git a/packages/eve/src/public/channels/discord/inbound.test.ts b/packages/eve/src/public/channels/discord/inbound.test.tsindex 9a8f10033..630f37a7c 100644--- a/packages/eve/src/public/channels/discord/inbound.test.ts+++ b/packages/eve/src/public/channels/discord/inbound.test.ts@@ -145,6 +145,7 @@ describe("commandInteractionMessage", () => {describe("Discord context rendering", () => {it("renders a deterministic context block", () => {const block = formatDiscordContextBlock({+ applicationId: "APP1",channelId: "C01",commandName: "ask",guildId: "G01",@@ -153,6 +154,7 @@ describe("Discord context rendering", () => {username: "ada",});expect(block).toContain("<discord_context>");+ expect(block).toContain("application_id: APP1");expect(block).toContain("user_id: U01");expect(block).toContain("username: ada");});diff --git a/packages/eve/src/public/channels/discord/inbound.ts b/packages/eve/src/public/channels/discord/inbound.tsindex f870e5b72..a005fd4e3 100644--- a/packages/eve/src/public/channels/discord/inbound.ts+++ b/packages/eve/src/public/channels/discord/inbound.ts@@ -113,6 +113,7 @@ const DISCORD_RESPONSE_INSTRUCTIONS =* commandName) are omitted from the block when not provided.*/export interface DiscordInboundContext {+ readonly applicationId?: string;readonly channelId: string;readonly commandName?: string;readonly guildId?: string;@@ -152,6 +153,7 @@ export function formatDiscordContextBlock(context: DiscordInboundContext): strin"<discord_context>","response_medium: discord",`response_instructions: ${DISCORD_RESPONSE_INSTRUCTIONS}`,+ ...(context.applicationId ? [`application_id: ${context.applicationId}`] : []),`user_id: ${context.userId}`,...(context.username ? [`username: ${context.username}`] : []),`channel_id: ${context.channelId}`,diff --git a/packages/eve/src/public/channels/github/dispatch.ts b/packages/eve/src/public/channels/github/dispatch.tsindex 968bf5e78..16883e0c0 100644--- a/packages/eve/src/public/channels/github/dispatch.ts+++ b/packages/eve/src/public/channels/github/dispatch.ts@@ -102,6 +102,7 @@ export async function dispatchPullRequestReviewComment(input: {/** Dispatches an opt-in issue webhook event into the runtime. */export async function dispatchIssue(input: {+ readonly botName: GitHubBotNameResolver;readonly config: GitHubChannelConfig;readonly event: GitHubIssueWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onIssue"]>;@@ -109,6 +110,7 @@ export async function dispatchIssue(input: {}): Promise<void> {const ctx = buildInboundContext(input.config, input.event);await dispatchWebhookEventTurn({+ botName: input.botName,config: input.config,event: input.event,handlerResult: () => input.handler(ctx, input.event.issue),@@ -120,6 +122,7 @@ export async function dispatchIssue(input: {/** Dispatches an opt-in pull-request webhook event into the runtime. */export async function dispatchPullRequest(input: {+ readonly botName: GitHubBotNameResolver;readonly config: GitHubChannelConfig;readonly event: GitHubPullRequestWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onPullRequest"]>;@@ -127,6 +130,7 @@ export async function dispatchPullRequest(input: {}): Promise<void> {const ctx = buildInboundContext(input.config, input.event);await dispatchWebhookEventTurn({+ botName: input.botName,config: input.config,event: input.event,handlerResult: () => input.handler(ctx, input.event.pullRequest),@@ -138,6 +142,7 @@ export async function dispatchPullRequest(input: {/** Dispatches an opt-in check-suite webhook event into the runtime. */export async function dispatchCheckSuite(input: {+ readonly botName: GitHubBotNameResolver;readonly config: GitHubChannelConfig;readonly event: GitHubCheckSuiteWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onCheckSuite"]>;@@ -153,6 +158,7 @@ export async function dispatchCheckSuite(input: {/** Dispatches an opt-in check-run webhook event into the runtime. */export async function dispatchCheckRun(input: {+ readonly botName: GitHubBotNameResolver;readonly config: GitHubChannelConfig;readonly event: GitHubCheckRunWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onCheckRun"]>;@@ -168,6 +174,7 @@ export async function dispatchCheckRun(input: {/** Dispatches an opt-in workflow-run webhook event into the runtime. */export async function dispatchWorkflowRun(input: {+ readonly botName: GitHubBotNameResolver;readonly config: GitHubChannelConfig;readonly event: GitHubWorkflowRunWebhookEvent;readonly handler: NonNullable<GitHubChannelConfig["onWorkflowRun"]>;@@ -182,6 +189,7 @@ export async function dispatchWorkflowRun(input: {}async function dispatchCiEvent(input: {+ readonly botName: GitHubBotNameResolver;readonly ci: GitHubCiPayload;readonly config: GitHubChannelConfig;readonly event: GitHubCiWebhookEvent;@@ -206,6 +214,7 @@ async function dispatchCiEvent(input: {}await dispatchWebhookEventTurn({+ botName: input.botName,config: input.config,event: input.event,handlerResult: () => input.handlerResult(ctx),@@ -216,6 +225,7 @@ async function dispatchCiEvent(input: {}async function dispatchWebhookEventTurn(input: {+ readonly botName: GitHubBotNameResolver;readonly config: GitHubChannelConfig;readonly event: GitHubCiWebhookEvent | GitHubIssueWebhookEvent | GitHubPullRequestWebhookEvent;readonly handlerResult: () => GitHubInboundResultOrPromise;@@ -228,9 +238,11 @@ async function dispatchWebhookEventTurn(input: {handlerResult: input.handlerResult,});if (result === null || result === undefined) return;+ const botName = await input.botName();await sendGitHubTurn({auth: result.auth,+ botName,event: input.event,message: input.message,context: mergeGitHubContext({@@ -267,8 +279,10 @@ async function dispatchCommentTurn(input: {await sendGitHubTurn({auth: result.auth,+ botName: input.botName,commentUrl: input.commentUrl,event: input.event,+ isMentioned: trigger !== null,message,context: mergeGitHubContext({github: await buildPullRequestContext(input.config, input.state, input.event.delivery.id),@@ -296,8 +310,10 @@ async function runInboundHandler(input: {async function sendGitHubTurn(input: {readonly auth: SessionAuthContext | null;+ readonly botName: string | undefined;readonly commentUrl?: string;readonly event: GitHubTurnEvent;+ readonly isMentioned?: boolean;readonly logMessage?: string;readonly message: string;readonly context: readonly string[] | undefined;@@ -306,10 +322,12 @@ async function sendGitHubTurn(input: {readonly title: string | undefined;}): Promise<void> {const contextBlock = formatGitHubContextBlock({+ botName: input.botName,deliveryId: input.event.delivery.id,commentUrl: input.commentUrl,headSha: input.state.headSha,issueNumber: input.state.issueNumber,+ isMentioned: input.isMentioned,pullRequestNumber: input.state.pullRequestNumber,repository: input.event.repository,sender: input.event.sender,diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.tsindex b66d312ed..b96d4882f 100644--- a/packages/eve/src/public/channels/github/githubChannel.test.ts+++ b/packages/eve/src/public/channels/github/githubChannel.test.ts@@ -234,6 +234,8 @@ describe("githubChannel", () => {const [continuationToken, input] = send.mock.calls[0]!;expect(input.message).toBe("help me");expect(input.context).toEqual([expect.stringContaining("<github_context>")]);+ expect(input.context[0]).toContain("bot_name: testbot");+ expect(input.context[0]).toContain("is_mentioned: true");expect(input.inputResponses).toBeUndefined();expect(continuationToken).toBe("repo:123:issue:5");expect(input).toMatchObject({@@ -259,6 +261,33 @@ describe("githubChannel", () => {});});+ it("marks an accepted unmentioned issue comment as not mentioned", async () => {+ const channel = githubChannel({+ botName: "testbot",+ credentials: { webhookSecret: SECRET },+ onComment: () => ({ auth: null }),+ });+ const { send } = await firePost(+ channel,+ signedRequest(+ "issue_comment",+ basePayload({+ action: "created",+ comment: {+ body: "Could you investigate?",+ id: 10,+ user: { id: 1, login: "octocat", type: "User" },+ },+ issue: { number: 5 },+ }),+ ),+ );++ expect(send).toHaveBeenCalledTimes(1);+ expect(send.mock.calls[0]![1].context[0]).toContain("bot_name: testbot");+ expect(send.mock.calls[0]![1].context[0]).toContain("is_mentioned: false");+ });+it("resolves a lazy botName on first dispatch and caches it", async () => {const resolveBotName = vi.fn().mockResolvedValue("testbot");const channel = githubChannel({diff --git a/packages/eve/src/public/channels/github/githubChannel.ts b/packages/eve/src/public/channels/github/githubChannel.tsindex ec77273d0..9467bc303 100644--- a/packages/eve/src/public/channels/github/githubChannel.ts+++ b/packages/eve/src/public/channels/github/githubChannel.ts@@ -326,6 +326,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {if (event.kind === "issues" && config.onIssue !== undefined) {waitUntil(dispatchIssue({+ botName,config,event,handler: config.onIssue,@@ -338,6 +339,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {if (event.kind === "pull_request" && config.onPullRequest !== undefined) {waitUntil(dispatchPullRequest({+ botName,config,event,handler: config.onPullRequest,@@ -350,6 +352,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {if (event.kind === "check_suite" && config.onCheckSuite !== undefined) {waitUntil(dispatchCheckSuite({+ botName,config,event,handler: config.onCheckSuite,@@ -362,6 +365,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {if (event.kind === "check_run" && config.onCheckRun !== undefined) {waitUntil(dispatchCheckRun({+ botName,config,event,handler: config.onCheckRun,@@ -374,6 +378,7 @@ export function githubChannel(config: GitHubChannelConfig = {}): GitHubChannel {if (event.kind === "workflow_run" && config.onWorkflowRun !== undefined) {waitUntil(dispatchWorkflowRun({+ botName,config,event,handler: config.onWorkflowRun,diff --git a/packages/eve/src/public/channels/github/inbound.ts b/packages/eve/src/public/channels/github/inbound.tsindex 534d0026d..9e0c44997 100644--- a/packages/eve/src/public/channels/github/inbound.ts+++ b/packages/eve/src/public/channels/github/inbound.ts@@ -180,10 +180,12 @@ function readHeader(headers: Headers, name: string): string | undefined {/** Renders deterministic GitHub metadata for the model-visible turn. */export function formatGitHubContextBlock(input: {+ readonly botName?: string;readonly commentUrl?: string;readonly deliveryId: string;readonly headSha?: string | null;readonly issueNumber?: number | null;+ readonly isMentioned?: boolean;readonly pullRequestNumber?: number | null;readonly repository: GitHubRepositoryRef;readonly sender: GitHubUser;@@ -198,6 +200,8 @@ export function formatGitHubContextBlock(input: {...(input.pullRequestNumber !== undefined && input.pullRequestNumber !== null? [`pull_request_number: ${input.pullRequestNumber}`]: []),+ ...(input.botName ? [`bot_name: ${input.botName}`] : []),+ ...(input.isMentioned !== undefined ? [`is_mentioned: ${input.isMentioned}`] : []),`sender: ${input.sender.login}`,`sender_type: ${input.sender.type}`,...(input.commentUrl ? [`comment_url: ${input.commentUrl}`] : []),diff --git a/packages/eve/src/public/channels/linear/inbound.ts b/packages/eve/src/public/channels/linear/inbound.tsindex 1afddf9f1..8ea17eab7 100644--- a/packages/eve/src/public/channels/linear/inbound.ts+++ b/packages/eve/src/public/channels/linear/inbound.ts@@ -161,9 +161,11 @@ export function messageFromLinearAgentSessionEvent(event: LinearAgentSessionEvenexport function formatLinearContextBlock(event: LinearAgentSessionEvent): string {const session = event.agentSession;const issue = session.issue;+ const appUserId = event.appUserId ?? session.appUserId;const lines = ["<linear_context>",`action: ${event.action}`,+ ...(appUserId ? [`app_user_id: ${appUserId}`] : []),`agent_session_id: ${session.id}`,`agent_session_url: ${session.url ?? ""}`,`organization_id: ${event.organizationId ?? session.organizationId ?? ""}`,diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex 947fb9ed9..fbb7dfd05 100644--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts@@ -92,6 +92,7 @@ function signedRequest(payload: Record<string, unknown>): Request {function sessionPayload(extra: Record<string, unknown> = {}): Record<string, unknown> {return {action: "created",+ appUserId: "app_user_1",agentSession: {creator: { displayName: "Ada Lovelace", id: "user_1" },id: "agent_session_1",@@ -172,6 +173,7 @@ describe("linearChannel inbound Agent Session events", () => {const [continuationToken, input] = send.mock.calls[0]!;expect(input.message).toBe("Please handle this issue.");expect(input.context?.[0]).toContain("<linear_context>");+ expect(input.context?.[0]).toContain("app_user_id: app_user_1");expect(input.context?.[0]).toContain("issue_identifier: EVE-123");expect(continuationToken).toBe("agent-session:agent_session_1");expect(input).toMatchObject({diff --git a/packages/eve/src/public/channels/slack/inbound.test.ts b/packages/eve/src/public/channels/slack/inbound.test.tsindex 20ed503a0..163f2ee22 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,+ slackEventReceivingBotUserId,slackEventInstallationTeamId,slackMessageFromWebhookPayload,} from "#public/channels/slack/inbound.js";@@ -83,6 +84,25 @@ describe("slackEventInstallationTeamId", () => {});});+describe("slackEventReceivingBotUserId", () => {+ it("accepts an unflagged authorization only when the app mention names the same user", () => {+ expect(+ slackEventReceivingBotUserId({+ authorizations: [{ user_id: "U_BOT" }],+ event: { text: "<@U_BOT> investigate", type: "app_mention" },+ type: "event_callback",+ }),+ ).toBe("U_BOT");+ expect(+ slackEventReceivingBotUserId({+ authorizations: [{ is_bot: false, user_id: "U_INSTALLER" }],+ event: { text: "<@U_INSTALLER> and <@U_BOT>", type: "app_mention" },+ type: "event_callback",+ }),+ ).toBeUndefined();+ });+});+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 17ae45179..e9ba07ba0 100644--- a/packages/eve/src/public/channels/slack/inbound.ts+++ b/packages/eve/src/public/channels/slack/inbound.ts@@ -205,6 +205,27 @@ export function slackEventBotUserId(envelope: SlackEventCallback): string | undereturn authorization?.user_id;}+/**+ * Returns the receiving bot user id that is safe to expose in model context.+ * Authorizations explicitly marked as non-bot identify an installer, not the+ * receiving bot. When Slack omits `is_bot`, an `app_mention` can still prove+ * the identity by mentioning the same authorization user id in its text.+ */+export function slackEventReceivingBotUserId(envelope: SlackEventCallback): string | undefined {+ const botUserId = slackEventBotUserId(envelope);+ if (botUserId !== undefined) return botUserId;++ const event = envelope.event;+ const text = typeof event?.text === "string" ? event.text : undefined;+ if (event?.type !== "app_mention" || text === undefined) return undefined;+ return envelope.authorizations?.find(+ (entry) =>+ entry.is_bot === undefined &&+ typeof entry.user_id === "string" &&+ text.includes(`<@${entry.user_id}>`),+ )?.user_id;+}+/** Returns the workspace whose app installation authorized this event. */export function slackEventInstallationTeamId(envelope: SlackEventCallback): string | undefined {const authorizations = envelope.authorizations ?? [];@@ -382,10 +403,12 @@ function parsePayloadAttachments(files: readonly SlackFile[] | undefined): Slack* `SlackMessage` and is therefore trivially testable in isolation.*/export interface SlackInboundContext {+ readonly botUserId?: string;readonly userId: string;readonly userName?: string;readonly fullName?: string;readonly channelId: string;+ readonly isMentioned?: boolean;readonly threadTs: string;readonly teamId?: string;}diff --git a/packages/eve/src/public/channels/slack/model-context.test.ts b/packages/eve/src/public/channels/slack/model-context.test.tsindex 4ebc82560..ddbf318fa 100644--- a/packages/eve/src/public/channels/slack/model-context.test.ts+++ b/packages/eve/src/public/channels/slack/model-context.test.ts@@ -36,7 +36,7 @@ describe("Slack model context", () => {userId: "U_CURRENT",},{- markdown: "Who owns the deploy?",+ text: "<@U_BOT> Who owns the deploy?",ts: "1700000000.000004",},);@@ -51,7 +51,7 @@ describe("Slack model context", () => {"message_ts: 1700000000.000004","team_id: T01","<content>",- "Who owns the deploy?",+ "<@U_BOT> Who owns the deploy?","</content>","</slack_message>",].join("\n"),@@ -115,7 +115,7 @@ describe("Slack model context", () => {userId: parsed!.author?.userId ?? "",},{- markdown: parsed!.markdown,+ text: parsed!.text,ts: parsed!.ts,},);diff --git a/packages/eve/src/public/channels/slack/model-context.ts b/packages/eve/src/public/channels/slack/model-context.tsindex 2cb47020f..42044aa63 100644--- a/packages/eve/src/public/channels/slack/model-context.ts+++ b/packages/eve/src/public/channels/slack/model-context.ts@@ -1,9 +1,12 @@import type { SlackThreadMessage } from "#public/channels/slack/api.js";import type { SlackInboundContext } from "#public/channels/slack/inbound.js";+import { slackMrkdwnToGfm } from "#public/channels/slack/mrkdwn.js";interface SlackModelMessageInput {+ readonly botUserId?: string;readonly channelId?: string;readonly content: string;+ readonly isMentioned?: boolean;readonly senderId?: string;readonly senderType: "agent" | "bot" | "unknown" | "user";readonly teamId?: string;@@ -21,6 +24,8 @@ export function formatSlackModelMessage(input: SlackModelMessageInput): string {"<slack_message>",`sender_type: ${input.senderType}`,...(input.senderId ? [`sender_id: ${input.senderId}`] : []),+ ...(input.botUserId ? [`bot_user_id: ${input.botUserId}`] : []),+ ...(input.isMentioned !== undefined ? [`is_mentioned: ${input.isMentioned}`] : []),...(input.channelId ? [`channel_id: ${input.channelId}`] : []),`thread_ts: ${input.threadTs}`,`message_ts: ${input.ts}`,@@ -35,11 +40,13 @@ export function formatSlackModelMessage(input: SlackModelMessageInput): string {/** Renders the triggering inbound Slack message as one attributed block. */export function formatSlackInboundMessage(context: SlackInboundContext,- message: { readonly markdown: string; readonly ts: string },+ message: { readonly text: string; readonly ts: string },): string {return formatSlackModelMessage({+ botUserId: context.botUserId,channelId: context.channelId,- content: message.markdown,+ content: slackModelContent(message.text),+ isMentioned: context.isMentioned,senderId: context.userId || undefined,senderType: context.userId ? "user" : "unknown",teamId: context.teamId,@@ -48,6 +55,23 @@ export function formatSlackInboundMessage(});}+function slackModelContent(input: string): string {+ const mentions: string[] = [];+ let markerPrefix = "\uE000eve_slack_user_mention_";+ while (input.includes(markerPrefix)) markerPrefix += "_";++ const protectedInput = input.replace(/<@[A-Z0-9_]+(?:\|[^>\r\n]+)?>/giu, (mention) => {+ const marker = `${markerPrefix}${mentions.length}\uE001`;+ mentions.push(mention);+ return marker;+ });+ let markdown = slackMrkdwnToGfm(protectedInput);+ for (const [index, mention] of mentions.entries()) {+ markdown = markdown.replaceAll(`${markerPrefix}${index}\uE001`, mention);+ }+ return markdown;+}+/*** Renders fetched Slack replies as explicitly attributed background context.* Returns `undefined` when there are no messages to add to the turn.diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex 57b966256..ca9a45280 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -1605,6 +1605,74 @@ describe("slackChannel() inbound mention pipeline", () => {expect(input.title).toBe("hello");});+ it("includes the receiving bot user id in the inbound model message", async () => {+ const onAppMention = vi.fn((_ctx, _message) => ({ auth: null }));+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onAppMention,+ });+ const body = buildEventBody(+ {+ channel: "C01",+ event_ts: "1700000000.000001",+ text: "<@U_BOT> Could you investigate?",+ ts: "1700000000.000001",+ type: "app_mention",+ user: "U_REQUESTER",+ },+ { authorizations: [{ user_id: "U_BOT" }] },+ );++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(send).toHaveBeenCalledTimes(1);+ expect(onAppMention.mock.calls[0]![1].text).toBe("<@U_BOT> Could you investigate?");+ const [, { message }] = send.mock.calls[0]! as [string, { message: string }];+ expect(message).toContain(+ [+ "<slack_message>",+ "sender_type: user",+ "sender_id: U_REQUESTER",+ "bot_user_id: U_BOT",+ "is_mentioned: true",+ "channel_id: C01",+ "thread_ts: 1700000000.000001",+ "message_ts: 1700000000.000001",+ "team_id: T01",+ "<content>",+ "<@U_BOT> Could you investigate?",+ "</content>",+ "</slack_message>",+ ].join("\n"),+ );+ });++ it("marks an accepted unmentioned direct message as not mentioned", async () => {+ const channel = slackChannel({+ credentials: { botToken: "xoxb-test" },+ onDirectMessage: () => ({ auth: null }),+ });+ const body = buildEventBody(+ {+ channel: "D01",+ channel_type: "im",+ event_ts: "1700000000.000002",+ text: "Could you investigate?",+ ts: "1700000000.000002",+ type: "message",+ user: "U_REQUESTER",+ },+ { authorizations: [{ is_bot: true, user_id: "U_BOT" }] },+ );++ const { send } = await firePost(channel, buildSignedRequest({ body }));++ expect(send).toHaveBeenCalledTimes(1);+ const [, { message }] = send.mock.calls[0]! as [string, { message: string }];+ expect(message).toContain("bot_user_id: U_BOT");+ expect(message).toContain("is_mentioned: false");+ });+it("uses the run title returned by onAppMention for a public channel", async () => {const channel = slackChannel({credentials: { botToken: "xoxb-test" },diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 2424660a4..d1327f3c1 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -41,6 +41,7 @@ import {type SlackEvent,slackEventBotUserId,slackEventInstallationTeamId,+ slackEventReceivingBotUserId,type SlackEventEnvelope,type SlackInboundContext,type SlackMessage,@@ -991,6 +992,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 receivingBotUserId = slackEventReceivingBotUserId(envelope);const installationTeamId = slackEventInstallationTeamId(envelope);// Handler precedence, in fall-through order:@@ -1009,6 +1011,7 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,+ receivingBotUserId,from: input.from,resolveSession: input.resolveSession,credentials: config.credentials,@@ -1026,6 +1029,7 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,+ receivingBotUserId,from: input.from,resolveSession: input.resolveSession,credentials: config.credentials,@@ -1054,6 +1058,7 @@ async function handleEventPost(input: {dispatchSlackMessage({appId,botUserId,+ receivingBotUserId,from: input.from,resolveSession: input.resolveSession,credentials: config.credentials,@@ -1120,6 +1125,7 @@ function isSelfAuthoredSlackMessage(async function dispatchSlackMessage(input: {readonly appId: string | undefined;readonly botUserId: string | undefined;+ readonly receivingBotUserId: string | undefined;readonly from: ChannelFrom<SlackChannelState>;readonly resolveSession: ChannelResolveSession;readonly credentials: SlackChannelCredentials | undefined;@@ -1174,11 +1180,12 @@ async function dispatchSlackMessage(input: {raw: input.message.raw,request: slack.request,}));+ const isBotMentioned =+ input.kind === "app_mention" ||+ (input.botUserId !== undefined && input.message.text.includes(`<@${input.botUserId}`));const ctx: SlackInboundMessageContext = {...sessionOperations,- isBotMentioned: () =>- input.kind === "app_mention" ||- (input.botUserId !== undefined && input.message.text.includes(`<@${input.botUserId}`)),+ isBotMentioned: () => isBotMentioned,isDMOrPrivateChannel,isSubscribed: async () => (await sessionOperations.resolveSession()) !== undefined,slack,@@ -1200,9 +1207,11 @@ async function dispatchSlackMessage(input: {channelState.audience =input.kind === "direct_message" || isPrivateConversation ? "private" : "public";await deliverSlackMessage({+ botUserId: input.receivingBotUserId,credentials: input.credentials,kind: input.kind,isPrivateConversation,+ isMentioned: isBotMentioned,message: input.message,result,sessionOperations,@@ -1299,9 +1308,11 @@ async function verifyInbound(}async function deliverSlackMessage(input: {+ readonly botUserId: string | undefined;readonly sessionOperations: SlackSessionOperations;readonly credentials: SlackChannelCredentials | undefined;readonly isPrivateConversation: boolean;+ readonly isMentioned: boolean;readonly kind: string;readonly message: SlackMessage;readonly result: Exclude<SlackInboundResult, null>;@@ -1324,8 +1335,10 @@ async function deliverSlackMessage(input: {policy: input.uploadPolicy,});const inboundContext: SlackInboundContext = {+ botUserId: input.botUserId,channelId: message.channelId,fullName: message.author?.fullName,+ isMentioned: input.isMentioned,teamId: message.teamId,threadTs: message.threadTs,userId: message.author?.userId ?? "",diff --git a/packages/eve/src/public/channels/teams/inbound.test.ts b/packages/eve/src/public/channels/teams/inbound.test.tsindex e7f7d6319..2d5f00111 100644--- a/packages/eve/src/public/channels/teams/inbound.test.ts+++ b/packages/eve/src/public/channels/teams/inbound.test.ts@@ -49,8 +49,10 @@ describe("Teams inbound parsing", () => {it("renders deterministic Teams context", () => {const block = formatTeamsContextBlock({activityId: "A1",+ botId: "BOT",channelId: "CH1",conversationId: "C1",+ isMentioned: true,scope: "channel",teamId: "TEAM",tenantId: "TENANT",@@ -59,6 +61,8 @@ describe("Teams inbound parsing", () => {});expect(block).toContain("<teams_context>");expect(block).toContain("response_medium: microsoft_teams");+ expect(block).toContain("bot_id: BOT");+ expect(block).toContain("is_mentioned: true");expect(block).toContain("user_id: U1");});});diff --git a/packages/eve/src/public/channels/teams/inbound.ts b/packages/eve/src/public/channels/teams/inbound.tsindex 2c77006e9..8ede68854 100644--- a/packages/eve/src/public/channels/teams/inbound.ts+++ b/packages/eve/src/public/channels/teams/inbound.ts@@ -97,9 +97,11 @@ let turndownService: TurndownService | null = null;/** Inbound context rendered into the model-visible `<teams_context>` block. */export interface TeamsInboundContext {readonly activityId: string;+ readonly botId?: string;readonly channelId?: string;readonly conversationId: string;readonly conversationType?: string;+ readonly isMentioned?: boolean;readonly scope: TeamsConversationScope;readonly teamId?: string;readonly tenantId?: string;@@ -139,6 +141,8 @@ export function formatTeamsContextBlock(context: TeamsInboundContext): string {"<teams_context>","response_medium: microsoft_teams",`response_instructions: ${TEAMS_RESPONSE_INSTRUCTIONS}`,+ ...(context.botId ? [`bot_id: ${context.botId}`] : []),+ ...(context.isMentioned !== undefined ? [`is_mentioned: ${context.isMentioned}`] : []),`user_id: ${context.userId}`,...(context.userName ? [`user_name: ${context.userName}`] : []),`conversation_id: ${context.conversationId}`,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 1adc8f854..c99502b53 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -169,6 +169,24 @@ describe("teamsChannel", () => {title: "Teams run",});expect(send.mock.calls[0]![1].context[0]).toContain("<teams_context>");+ expect(send.mock.calls[0]![1].context[0]).toContain("bot_id: BOT");+ expect(send.mock.calls[0]![1].context[0]).toContain("is_mentioned: true");+ });++ it("marks an accepted personal message without a mention as not mentioned", async () => {+ const channel = teamsChannel({+ credentials: { webhookVerifier: () => true },+ onMessage: () => ({ auth: null }),+ });+ const raw = messageActivity({ conversationType: "personal" });+ raw.entities = [];+ raw.text = "Could you investigate?";++ const { send } = await firePost(channel, raw);++ expect(send).toHaveBeenCalledTimes(1);+ expect(send.mock.calls[0]![1].context[0]).toContain("bot_id: BOT");+ expect(send.mock.calls[0]![1].context[0]).toContain("is_mentioned: false");});it("default dispatch ignores unmentioned group messages", async () => {diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex ff6d232e4..e58d6be03 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -638,9 +638,11 @@ async function dispatchMessage(input: {const turnMessage = buildTeamsTurnMessage(input.activity.text, fileParts);const inboundContext: TeamsInboundContext = {activityId: input.activity.id,+ botId: input.activity.recipient.id,channelId: input.activity.teamsChannelId,conversationId: input.activity.conversation.id,conversationType: input.activity.conversationType,+ isMentioned: input.activity.isBotMentioned,scope: input.activity.scope,teamId: input.activity.teamId,tenantId: input.activity.tenantId,diff --git a/packages/eve/src/public/channels/telegram/defaults.ts b/packages/eve/src/public/channels/telegram/defaults.tsindex 6333ea670..2540ec314 100644--- a/packages/eve/src/public/channels/telegram/defaults.ts+++ b/packages/eve/src/public/channels/telegram/defaults.ts@@ -53,6 +53,17 @@ export async function defaultOnMessage(return { auth: defaultTelegramAuth(message) };}+export function isTelegramBotMentioned(+ message: Pick<TelegramMessage, "caption" | "text">,+ botUsername: string | undefined,+): boolean {+ if (botUsername === undefined) return false;+ const text = message.text || message.caption;+ if (isTargetedBotCommand(text, botUsername)) return true;+ const escapedUsername = botUsername.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");+ return new RegExp(`(?:^|[^A-Za-z0-9_])@${escapedUsername}(?=$|[^A-Za-z0-9_])`, "iu").test(text);+}+/** Built-in Telegram event handlers for typing, replies, HITL, and terminal errors. */export const defaultEvents: TelegramChannelEvents = {async "turn.started"(_event, channel, _ctx) {@@ -132,7 +143,7 @@ function shouldDispatchTelegramMessage(if (message.replyToMessage?.from?.isBot === true) return true;if (isBotCommand(text, botUsername)) return true;- if (botUsername !== undefined && mentionsBot(text, botUsername)) return true;+ if (botUsername !== undefined && mentionsBotUsername(text, botUsername)) return true;return false;}@@ -145,6 +156,11 @@ function isBotCommand(text: string, botUsername: string | undefined): boolean {return botUsername !== undefined && target.toLowerCase() === botUsername.toLowerCase();}-function mentionsBot(text: string, botUsername: string): boolean {+function isTargetedBotCommand(text: string, botUsername: string): boolean {+ const match = /^\/[A-Za-z0-9_]+@(?<target>[A-Za-z0-9_]+)(?:\s|$)/u.exec(text);+ return match?.groups?.target?.toLowerCase() === botUsername.toLowerCase();+}++function mentionsBotUsername(text: string, botUsername: string): boolean {return text.toLowerCase().includes(`@${botUsername.toLowerCase()}`);}diff --git a/packages/eve/src/public/channels/telegram/inbound.test.ts b/packages/eve/src/public/channels/telegram/inbound.test.tsindex 42f3484af..f4fe4ebfe 100644--- a/packages/eve/src/public/channels/telegram/inbound.test.ts+++ b/packages/eve/src/public/channels/telegram/inbound.test.ts@@ -105,12 +105,13 @@ describe("Telegram context rendering", () => {chatId: "-1001",chatTitle: "Ops",chatType: "supergroup",+ isMentioned: true,messageId: "10",messageThreadId: 7,userId: "42",username: "ada",}),- ).toContain("<telegram_context>\nresponse_medium: telegram");+ ).toContain("is_mentioned: true");});it("renders chat and actor identity into the block", () => {diff --git a/packages/eve/src/public/channels/telegram/inbound.ts b/packages/eve/src/public/channels/telegram/inbound.tsindex 0b22195a8..3c4ed06e8 100644--- a/packages/eve/src/public/channels/telegram/inbound.ts+++ b/packages/eve/src/public/channels/telegram/inbound.ts@@ -98,6 +98,7 @@ export interface TelegramInboundContext {readonly chatId: string;readonly chatTitle?: string;readonly chatType: TelegramChatType;+ readonly isMentioned?: boolean;readonly messageId: string;readonly messageThreadId?: number;readonly userId?: string;@@ -137,6 +138,7 @@ export function formatTelegramContextBlock(context: TelegramInboundContext): str...(context.userId ? [`user_id: ${context.userId}`] : []),...(context.username ? [`username: ${context.username}`] : []),...(context.botUsername ? [`bot_username: ${context.botUsername}`] : []),+ ...(context.isMentioned !== undefined ? [`is_mentioned: ${context.isMentioned}`] : []),"</telegram_context>",];return lines.join("\n");diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts b/packages/eve/src/public/channels/telegram/telegramChannel.test.tsindex a4bd2c71e..2afcf3ffb 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.test.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.test.ts@@ -13,6 +13,7 @@ import {telegramChannel,type TelegramChannelState,} from "#public/channels/telegram/index.js";+import { isTelegramBotMentioned } from "#public/channels/telegram/defaults.js";const SECRET = "telegram-secret";@@ -156,6 +157,7 @@ describe("telegramChannel() inbound route", () => {it("dispatches verified private messages with Telegram auth and chat-wide token", async () => {const channel = telegramChannel({api: { fetch: fakeTelegramFetch() },+ botUsername: "testbot",credentials: { botToken: "bot-token", webhookSecretToken: SECRET },onMessage: (_ctx, message) => ({auth: defaultTelegramAuth(message),@@ -177,6 +179,8 @@ describe("telegramChannel() inbound route", () => {expect(send).toHaveBeenCalledTimes(1);const [continuationToken, input] = send.mock.calls[0]!;expect((input as { context: string[] }).context[0]).toContain("<telegram_context>");+ expect((input as { context: string[] }).context[0]).toContain("bot_username: testbot");+ expect((input as { context: string[] }).context[0]).toContain("is_mentioned: false");expect(String((input as { message: string }).message)).toContain("hello");expect(continuationToken).toBe("42::");expect(input).toMatchObject({@@ -193,6 +197,15 @@ describe("telegramChannel() inbound route", () => {});});+ it.each([+ ["hello @testbot", true],+ ["/ask@testbot hello", true],+ ["hello @testbotany", false],+ ["email [email protected]", false],+ ])("reports exact bot mention state for %j", (text, expected) => {+ expect(isTelegramBotMentioned({ caption: "", text }, "testbot")).toBe(expected);+ });+it("gates group messages to commands, mentions, and replies to the bot", async () => {const channel = telegramChannel({api: { fetch: fakeTelegramFetch() },@@ -220,6 +233,9 @@ describe("telegramChannel() inbound route", () => {});expect(mentioned.send).toHaveBeenCalledTimes(1);expect(mentioned.send.mock.calls[0]![0]).toBe("-1001::11");+ expect((mentioned.send.mock.calls[0]![1] as { context: string[] }).context[0]).toContain(+ "is_mentioned: true",+ );});it("delivers Telegram callback queries as compact HITL input responses", async () => {diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex 0c5774e30..f18f51e16 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -27,7 +27,11 @@ import {collectTelegramFileParts,createTelegramFetchFile,} from "#public/channels/telegram/attachments.js";-import { defaultEvents, defaultOnMessage } from "#public/channels/telegram/defaults.js";+import {+ defaultEvents,+ defaultOnMessage,+ isTelegramBotMentioned,+} from "#public/channels/telegram/defaults.js";import {TELEGRAM_HITL_CALLBACK_PREFIX,isTelegramSyntheticResponse,@@ -503,6 +507,7 @@ async function dispatchMessage(input: {chatId: input.message.chat.id,chatTitle: input.message.chat.title,chatType: input.message.chat.type,+ isMentioned: isTelegramBotMentioned(input.message, input.config.botUsername),messageId: input.message.messageId,messageThreadId: input.message.messageThreadId,userId: input.message.from?.id,