The Open Framework for Building Agents
feat(eve): Update teams to add `isSubscribed`, `isBotMentioned` utility (#1068)
Ben Pankow9679abc56bb0
diff --git a/.changeset/gentle-teams-continue.md b/.changeset/gentle-teams-continue.mdnew file mode 100644index 000000000..8721fd859--- /dev/null+++ b/.changeset/gentle-teams-continue.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Added an `isSubscribed()` helper to the Microsoft Teams `onMessage` hook for custom routing that can continue conversations without repeated mentions.diff --git a/docs/channels/teams.mdx b/docs/channels/teams.mdxindex 48b9ecede..2e5dfd8b9 100644--- a/docs/channels/teams.mdx+++ b/docs/channels/teams.mdx@@ -28,17 +28,24 @@ By default the channel mounts at `POST /eve/v1/teams`. Point your Azure Bot or TThe 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. Before dispatch, eve strips the mention, adds a `<teams_context>` block, 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:+```tsimport { defaultTeamsAuth, teamsChannel } from "eve/channels/teams";export default teamsChannel({- onMessage(ctx, message) {- if (message.scope !== "personal" && !message.isBotMentioned) return null;- return { auth: defaultTeamsAuth(message) };+ async onMessage(ctx, message) {+ if (message.from.role === "bot" || message.from.id === message.recipient.id) return null;+ const isDirectMessage = message.scope === "personal";+ return isDirectMessage || message.isBotMentioned || (await ctx.isSubscribed())+ ? { auth: defaultTeamsAuth(message) }+ : null;},});```+`isSubscribed()` checks whether the conversation has previously involved the agent.+### DeliveryReplies post as Markdown (`textFormat: "markdown"`), with oversized text split across messages and a typing indicator sent on turn start and action requests.diff --git a/packages/eve/src/public/channels/teams/defaults.ts b/packages/eve/src/public/channels/teams/defaults.tsindex a217f8a88..46e6eb391 100644--- a/packages/eve/src/public/channels/teams/defaults.ts+++ b/packages/eve/src/public/channels/teams/defaults.ts@@ -51,6 +51,7 @@ export async function defaultOnMessage(ctx: TeamsContext,message: TeamsMessageActivity,): Promise<TeamsInboundResult> {+ if (message.from.role === "bot" || message.from.id === message.recipient.id) return null;if (message.scope !== "personal" && !message.isBotMentioned) return null;await ctx.thread.startTyping();return { auth: defaultTeamsAuth(message) };diff --git a/packages/eve/src/public/channels/teams/index.ts b/packages/eve/src/public/channels/teams/index.tsindex f84f0b707..00aa05b15 100644--- a/packages/eve/src/public/channels/teams/index.ts+++ b/packages/eve/src/public/channels/teams/index.ts@@ -22,6 +22,7 @@ export {type TeamsContext,type TeamsEventContext,type TeamsHandle,+ type TeamsInboundMessageContext,type TeamsInboundResult,type TeamsInboundResultOrPromise,type TeamsInputResponseResult,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex e66bfbfbd..ddfbc023d 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -14,6 +14,11 @@ function asCompiled<T = unknown>(channel: unknown): CompiledChannel<T> {async function firePost(channel: unknown,body: Record<string, unknown>,+ overrides: {+ readonly resolveActiveSession?: (options: {+ readonly continuationToken: string;+ }) => Promise<{ readonly sessionId: string } | undefined>;+ } = {},): Promise<{readonly response: Response;readonly send: ReturnType<typeof vi.fn>;@@ -40,7 +45,7 @@ async function firePost(}),{getSession: vi.fn(),- resolveActiveSession: async () => undefined,+ resolveActiveSession: overrides.resolveActiveSession ?? vi.fn().mockResolvedValue(undefined),cancel: vi.fn(),params: {},receive: vi.fn(),@@ -111,6 +116,76 @@ describe("teamsChannel", () => {expect(send).not.toHaveBeenCalled();});+ it("default dispatch ignores bot-authored personal messages", async () => {+ const channel = teamsChannel({ credentials: { webhookVerifier: () => true } });+ const raw = messageActivity({ conversationType: "personal" });+ raw.from = { id: "OTHER_BOT", name: "Other bot", role: "bot" };++ const { send } = await firePost(channel, raw);++ expect(send).not.toHaveBeenCalled();+ });++ it("exposes the subscription helper to onMessage", async () => {+ const observed: boolean[] = [];+ const resolveActiveSession = vi.fn().mockResolvedValue({ sessionId: "SESSION" });+ const channel = teamsChannel({+ credentials: { webhookVerifier: () => true },+ async onMessage(ctx) {+ observed.push(await ctx.isSubscribed());+ return null;+ },+ });+ const raw = messageActivity({ conversationType: "channel" });+ raw.entities = [];+ raw.conversation = { conversationType: "channel", id: "CONV;messageid=THREAD_ROOT" };++ await firePost(channel, raw, { resolveActiveSession });++ expect(observed).toEqual([true]);+ expect(resolveActiveSession).toHaveBeenCalledWith({+ continuationToken: "TENANT:CONV:THREAD_ROOT",+ });+ });++ it("allows a mention-or-subscription onMessage policy", async () => {+ const channel = teamsChannel({+ credentials: { webhookVerifier: () => true },+ async onMessage(ctx, message) {+ return message.isBotMentioned || (await ctx.isSubscribed()) ? { auth: null } : null;+ },+ });+ const raw = messageActivity({ conversationType: "channel" });+ raw.entities = [];+ raw.conversation = { conversationType: "channel", id: "CONV;messageid=THREAD_ROOT" };++ const { send } = await firePost(channel, raw, {+ resolveActiveSession: vi.fn().mockResolvedValue({ sessionId: "SESSION" }),+ });++ expect(send).toHaveBeenCalledTimes(1);+ });++ it("passes bot-authored messages to onMessage", async () => {+ const onMessage = vi.fn((_ctx: unknown, _message: unknown) => null);+ const channel = teamsChannel({+ credentials: { webhookVerifier: () => true },+ onMessage,+ });+ const raw = messageActivity({ conversationType: "channel" });+ raw.entities = [];+ raw.from = { id: "OTHER_BOT", name: "Other bot", role: "bot" };++ const { send } = await firePost(channel, raw);++ expect(onMessage).toHaveBeenCalledTimes(1);+ expect(onMessage).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ from: expect.objectContaining({ id: "OTHER_BOT", role: "bot" }) }),+ );+ expect(send).not.toHaveBeenCalled();+ });+it("resumes invoke HITL responses with the clicker's auth and recorded thread", async () => {const channel = teamsChannel({ credentials: { webhookVerifier: () => true } });const { response, send } = await firePost(channel, {diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex 520ab7ce5..430a8e717 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -62,12 +62,18 @@ const log = createLogger("teams.channel");type EventData<T extends HandleMessageStreamEvent["type"]> =Extract<HandleMessageStreamEvent, { type: T }> extends { data: infer D } ? D : undefined;-/** Pre-dispatch Teams context passed to inbound message and invoke hooks. */+/** Pre-dispatch Teams context passed to invoke hooks. */export interface TeamsContext {readonly teams: TeamsHandle;readonly thread: TeamsThread;}+/** Message-scoped context handed to `teamsChannel({ onMessage })`. */+export interface TeamsInboundMessageContext extends TeamsContext {+ /** Returns whether this message belongs to a thread with an active eve session. */+ isSubscribed(): Promise<boolean>;+}+/** Channel-owned Teams context returned by `context()`. */export interface TeamsChannelContext extends TeamsContext {readonly adaptiveCardVersion: string;@@ -188,7 +194,10 @@ export interface TeamsChannelConfig {readonly route?: string;/** Inbound message hook. Defaults to user-scoped auth and mention-gated dispatch outside personal chats. */- onMessage?(ctx: TeamsContext, message: TeamsMessageActivity): TeamsInboundResultOrPromise;+ onMessage?(+ ctx: TeamsInboundMessageContext,+ message: TeamsMessageActivity,+ ): TeamsInboundResultOrPromise;/** Authorizes HITL card submissions. Defaults to the submitting Teams user. */onInputResponse?(@@ -284,48 +293,52 @@ export function teamsChannel(config: TeamsChannelConfig = {}): TeamsChannel {},routes: [- POST<TeamsChannelState>(config.route ?? "/eve/v1/teams", async (req, { send, waitUntil }) => {- const body = await verifyInbound(req, config.credentials);- if (body === null) return new Response("unauthorized", { status: 401 });-- let raw: JsonObject;- try {- raw = parseJsonObject(JSON.parse(body) as unknown);- } catch (error) {- log.warn("inbound Teams body is not valid JSON", { error });- return teamsOk();- }+ POST<TeamsChannelState>(+ config.route ?? "/eve/v1/teams",+ async (req, { resolveActiveSession, send, waitUntil }) => {+ const body = await verifyInbound(req, config.credentials);+ if (body === null) return new Response("unauthorized", { status: 401 });++ let raw: JsonObject;+ try {+ raw = parseJsonObject(JSON.parse(body) as unknown);+ } catch (error) {+ log.warn("inbound Teams body is not valid JSON", { error });+ return teamsOk();+ }++ const activity = parseTeamsActivity(raw);+ if (activity === null) return teamsOk();++ if (activity.type === "message") {+ waitUntil(+ isTeamsInputResponseActivity(activity)+ ? dispatchInputResponses({ activity, config, onInputResponse, send })+ : dispatchMessage({+ activity,+ config,+ filesPolicy,+ onMessage,+ resolveActiveSession,+ send,+ }),+ );+ return teamsOk();+ }++ if (activity.type === "invoke") {+ return handleInvoke({+ activity,+ config,+ onInputResponse,+ send,+ waitUntil,+ });+ }- const activity = parseTeamsActivity(raw);- if (activity === null) return teamsOk();-- if (activity.type === "message") {- waitUntil(- isTeamsInputResponseActivity(activity)- ? dispatchInputResponses({ activity, config, onInputResponse, send })- : dispatchMessage({- activity,- config,- filesPolicy,- onMessage,- send,- }),- );return teamsOk();- }-- if (activity.type === "invoke") {- return handleInvoke({- activity,- config,- onInputResponse,- send,- waitUntil,- });- }-- return teamsOk();- }),+ },+ ),],async receive(input, { send }) {@@ -555,10 +568,19 @@ async function dispatchMessage(input: {readonly config: TeamsChannelConfig;readonly filesPolicy: TeamsFilesPolicy;readonly onMessage: NonNullable<TeamsChannelConfig["onMessage"]>;+ readonly resolveActiveSession: (options: {+ readonly continuationToken: string;+ }) => Promise<{ readonly sessionId: string } | undefined>;readonly send: SendFn<TeamsChannelState>;}): Promise<void> {const state = stateFromActivity(input.activity);- const ctx = buildTeamsBinding({ config: input.config, state });+ const binding = buildTeamsBinding({ config: input.config, state });+ const continuationToken = stateToken(state);+ const ctx: TeamsInboundMessageContext = {+ ...binding,+ isSubscribed: async () =>+ (await input.resolveActiveSession({ continuationToken })) !== undefined,+ };let result: TeamsInboundResult;try {@@ -592,7 +614,7 @@ async function dispatchMessage(input: {},{auth: result.auth,- continuationToken: stateToken(state),+ continuationToken,state,},);