@gakr-gakr/msteams 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/api.ts +3 -0
  2. package/autobot.plugin.json +15 -0
  3. package/channel-config-api.ts +1 -0
  4. package/channel-plugin-api.ts +2 -0
  5. package/config-api.ts +4 -0
  6. package/contract-api.ts +4 -0
  7. package/index.ts +20 -0
  8. package/package.json +72 -0
  9. package/runtime-api.ts +66 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.ts +348 -0
  16. package/src/attachments/download.ts +328 -0
  17. package/src/attachments/graph.ts +489 -0
  18. package/src/attachments/html.ts +122 -0
  19. package/src/attachments/payload.ts +14 -0
  20. package/src/attachments/remote-media.ts +86 -0
  21. package/src/attachments/shared.ts +655 -0
  22. package/src/attachments/types.ts +47 -0
  23. package/src/attachments.ts +18 -0
  24. package/src/channel-api.ts +1 -0
  25. package/src/channel.runtime.ts +56 -0
  26. package/src/channel.setup.ts +77 -0
  27. package/src/channel.ts +1176 -0
  28. package/src/config-schema.ts +6 -0
  29. package/src/config-ui-hints.ts +40 -0
  30. package/src/conversation-store-fs.ts +149 -0
  31. package/src/conversation-store-helpers.ts +105 -0
  32. package/src/conversation-store-memory.ts +51 -0
  33. package/src/conversation-store.ts +71 -0
  34. package/src/directory-live.ts +111 -0
  35. package/src/doctor.ts +27 -0
  36. package/src/errors.ts +270 -0
  37. package/src/feedback-reflection-prompt.ts +117 -0
  38. package/src/feedback-reflection-store.ts +113 -0
  39. package/src/feedback-reflection.ts +271 -0
  40. package/src/file-consent-helpers.ts +115 -0
  41. package/src/file-consent-invoke.ts +150 -0
  42. package/src/file-consent.ts +223 -0
  43. package/src/graph-chat.ts +36 -0
  44. package/src/graph-group-management.ts +168 -0
  45. package/src/graph-members.ts +48 -0
  46. package/src/graph-messages.ts +534 -0
  47. package/src/graph-teams.ts +114 -0
  48. package/src/graph-thread.ts +146 -0
  49. package/src/graph-upload.ts +531 -0
  50. package/src/graph-users.ts +29 -0
  51. package/src/graph.ts +308 -0
  52. package/src/inbound.ts +148 -0
  53. package/src/index.ts +4 -0
  54. package/src/media-helpers.ts +105 -0
  55. package/src/mentions.ts +114 -0
  56. package/src/messenger.ts +608 -0
  57. package/src/monitor-handler/access.ts +136 -0
  58. package/src/monitor-handler/inbound-media.ts +180 -0
  59. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  60. package/src/monitor-handler/message-handler.test-support.ts +102 -0
  61. package/src/monitor-handler/message-handler.ts +1015 -0
  62. package/src/monitor-handler/reaction-handler.ts +124 -0
  63. package/src/monitor-handler/thread-session.ts +30 -0
  64. package/src/monitor-handler.ts +538 -0
  65. package/src/monitor-handler.types.ts +27 -0
  66. package/src/monitor-types.ts +6 -0
  67. package/src/monitor.ts +476 -0
  68. package/src/oauth.flow.ts +77 -0
  69. package/src/oauth.shared.ts +37 -0
  70. package/src/oauth.token.ts +162 -0
  71. package/src/oauth.ts +130 -0
  72. package/src/outbound.ts +198 -0
  73. package/src/pending-uploads-fs.ts +235 -0
  74. package/src/pending-uploads.ts +121 -0
  75. package/src/policy.ts +245 -0
  76. package/src/polls-store-memory.ts +32 -0
  77. package/src/polls.ts +312 -0
  78. package/src/presentation.ts +93 -0
  79. package/src/probe.ts +132 -0
  80. package/src/reply-dispatcher.ts +523 -0
  81. package/src/reply-stream-controller.ts +334 -0
  82. package/src/resolve-allowlist.ts +309 -0
  83. package/src/revoked-context.ts +17 -0
  84. package/src/runtime.ts +12 -0
  85. package/src/sdk-types.ts +59 -0
  86. package/src/sdk.ts +916 -0
  87. package/src/secret-contract.ts +49 -0
  88. package/src/secret-input.ts +7 -0
  89. package/src/send-context.ts +269 -0
  90. package/src/send.ts +697 -0
  91. package/src/sent-message-cache.ts +174 -0
  92. package/src/session-route.ts +40 -0
  93. package/src/setup-core.ts +162 -0
  94. package/src/setup-surface.ts +319 -0
  95. package/src/sso-token-store.ts +166 -0
  96. package/src/sso.ts +300 -0
  97. package/src/storage.ts +25 -0
  98. package/src/store-fs.ts +42 -0
  99. package/src/streaming-message.ts +327 -0
  100. package/src/thread-parent-context.ts +159 -0
  101. package/src/token-response.ts +11 -0
  102. package/src/token.ts +194 -0
  103. package/src/user-agent.ts +53 -0
  104. package/src/webhook-timeouts.ts +27 -0
  105. package/src/welcome-card.ts +57 -0
  106. package/test-api.ts +1 -0
  107. package/tsconfig.json +16 -0
@@ -0,0 +1,124 @@
1
+ import { normalizeMSTeamsConversationId } from "../inbound.js";
2
+ import type { MSTeamsMessageHandlerDeps } from "../monitor-handler.types.js";
3
+ import { getMSTeamsRuntime } from "../runtime.js";
4
+ import type { MSTeamsTurnContext } from "../sdk-types.js";
5
+ import { resolveMSTeamsSenderAccess } from "./access.js";
6
+
7
+ /** Teams reaction type names → Unicode emoji. */
8
+ const TEAMS_REACTION_EMOJI: Record<string, string> = {
9
+ like: "👍",
10
+ heart: "❤️",
11
+ laugh: "😆",
12
+ surprised: "😮",
13
+ sad: "😢",
14
+ angry: "😡",
15
+ };
16
+
17
+ /**
18
+ * Map a Teams reaction type string to a Unicode emoji.
19
+ * Falls back to the raw type if not recognized.
20
+ */
21
+ function mapReactionEmoji(reactionType: string): string {
22
+ return TEAMS_REACTION_EMOJI[reactionType] ?? reactionType;
23
+ }
24
+
25
+ type ReactionDirection = "added" | "removed";
26
+
27
+ /**
28
+ * Create a handler for MS Teams reaction activities (reactionsAdded / reactionsRemoved).
29
+ * The returned function accepts a turn context and a direction string.
30
+ */
31
+ export function createMSTeamsReactionHandler(deps: MSTeamsMessageHandlerDeps) {
32
+ const { cfg, log } = deps;
33
+ const core = getMSTeamsRuntime();
34
+ const msteamsCfg = cfg.channels?.msteams;
35
+
36
+ return async function handleReaction(
37
+ context: MSTeamsTurnContext,
38
+ direction: ReactionDirection,
39
+ ): Promise<void> {
40
+ const activity = context.activity;
41
+
42
+ // Reactions are carried in reactionsAdded / reactionsRemoved on the activity.
43
+ const reactions: Array<{ type?: string }> =
44
+ direction === "added"
45
+ ? ((activity as unknown as { reactionsAdded?: Array<{ type?: string }> }).reactionsAdded ??
46
+ [])
47
+ : ((activity as unknown as { reactionsRemoved?: Array<{ type?: string }> })
48
+ .reactionsRemoved ?? []);
49
+
50
+ if (reactions.length === 0) {
51
+ log.debug?.("reaction activity has no reactions; skipping");
52
+ return;
53
+ }
54
+
55
+ const from = activity.from;
56
+ if (!from?.id) {
57
+ log.debug?.("reaction activity missing from.id; skipping");
58
+ return;
59
+ }
60
+
61
+ const rawConversationId = activity.conversation?.id ?? "";
62
+ const conversationId = normalizeMSTeamsConversationId(rawConversationId);
63
+ const conversationType = activity.conversation?.conversationType ?? "personal";
64
+ const isGroupChat = conversationType === "groupChat" || activity.conversation?.isGroup === true;
65
+ const isChannel = conversationType === "channel";
66
+ const isDirectMessage = !isGroupChat && !isChannel;
67
+
68
+ const senderId = from.aadObjectId ?? from.id;
69
+ const senderName = from.name ?? from.id;
70
+
71
+ if (msteamsCfg) {
72
+ const senderAccess = await resolveMSTeamsSenderAccess({ cfg, activity });
73
+ if (senderAccess.senderAccess.decision !== "allow") {
74
+ log.debug?.("dropping reaction (access denied)", {
75
+ sender: senderId,
76
+ reason: senderAccess.senderAccess.reasonCode,
77
+ });
78
+ return;
79
+ }
80
+ }
81
+
82
+ // Resolve the agent route for this conversation/sender.
83
+ // Extract teamId for team-scoped routing bindings (channel/group reactions).
84
+ const teamId = isDirectMessage
85
+ ? undefined
86
+ : (activity as unknown as { channelData?: { team?: { id?: string } } }).channelData?.team?.id;
87
+ const route = core.channel.routing.resolveAgentRoute({
88
+ cfg,
89
+ channel: "msteams",
90
+ peer: {
91
+ kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
92
+ id: isDirectMessage ? senderId : conversationId,
93
+ },
94
+ ...(teamId ? { teamId } : {}),
95
+ });
96
+
97
+ // The replyToId points to the message that was reacted to.
98
+ const targetMessageId = (activity as unknown as { replyToId?: string }).replyToId ?? "unknown";
99
+
100
+ for (const reaction of reactions) {
101
+ const reactionType = reaction.type ?? "unknown";
102
+ const emoji = mapReactionEmoji(reactionType);
103
+ const label =
104
+ direction === "added"
105
+ ? `Teams reaction ${emoji} added by ${senderName} on message ${targetMessageId}`
106
+ : `Teams reaction ${emoji} removed by ${senderName} from message ${targetMessageId}`;
107
+
108
+ log.info(`reaction ${direction}`, {
109
+ sender: senderId,
110
+ reactionType,
111
+ emoji,
112
+ targetMessageId,
113
+ conversationId,
114
+ });
115
+
116
+ core.system.enqueueSystemEvent(label, {
117
+ sessionKey: route.sessionKey,
118
+ contextKey: `msteams:reaction:${conversationId}:${targetMessageId}:${senderId}:${reactionType}:${direction}`,
119
+ forceSenderIsOwnerFalse: true,
120
+ trusted: false,
121
+ });
122
+ }
123
+ };
124
+ }
@@ -0,0 +1,30 @@
1
+ import { resolveThreadSessionKeys } from "autobot/plugin-sdk/routing";
2
+
3
+ // Strip any trailing `:thread:<id>` segments from a session key. Thread ids are
4
+ // timestamps/uuids and never contain `:`, so the segment boundary is unambiguous;
5
+ // the `+` covers pathological keys with multiple compounded suffixes.
6
+ const TRAILING_THREAD_SUFFIX = /(?::thread:[^:]+)+$/;
7
+
8
+ export function resolveMSTeamsRouteSessionKey(params: {
9
+ baseSessionKey: string;
10
+ isChannel: boolean;
11
+ conversationMessageId?: string;
12
+ replyToId?: string;
13
+ }): string {
14
+ const channelThreadId = params.isChannel
15
+ ? (params.conversationMessageId ?? params.replyToId ?? undefined)
16
+ : undefined;
17
+ // Re-derive from a clean base. If a caller hands us a session key that is
18
+ // already thread-qualified (e.g. a `route.sessionKey` mutated in place by a
19
+ // prior turn whose object is still held in the resolved-route cache, see
20
+ // src/routing/resolve-route.ts cache-miss return), naively appending the
21
+ // current thread id would compound into `…:thread:OLD:thread:NEW` and route
22
+ // the turn to a malformed lane that splits same-thread context across turns.
23
+ // Stripping makes this helper idempotent regardless of caller hygiene. (#66771)
24
+ const cleanBase = params.baseSessionKey.replace(TRAILING_THREAD_SUFFIX, "");
25
+ return resolveThreadSessionKeys({
26
+ baseSessionKey: cleanBase,
27
+ threadId: channelThreadId,
28
+ parentSessionKey: channelThreadId ? cleanBase : undefined,
29
+ }).sessionKey;
30
+ }
@@ -0,0 +1,538 @@
1
+ import path from "node:path";
2
+ import { resolveThreadSessionKeys } from "autobot/plugin-sdk/routing";
3
+ import { appendRegularFile } from "autobot/plugin-sdk/security-runtime";
4
+ import { normalizeOptionalLowercaseString } from "autobot/plugin-sdk/string-coerce-runtime";
5
+ import { formatUnknownError } from "./errors.js";
6
+ import { buildFeedbackEvent, runFeedbackReflection } from "./feedback-reflection.js";
7
+ import { respondToMSTeamsFileConsentInvoke } from "./file-consent-invoke.js";
8
+ import { extractMSTeamsConversationMessageId, normalizeMSTeamsConversationId } from "./inbound.js";
9
+ import { resolveMSTeamsSenderAccess } from "./monitor-handler/access.js";
10
+ import { createMSTeamsMessageHandler } from "./monitor-handler/message-handler.js";
11
+ import { createMSTeamsReactionHandler } from "./monitor-handler/reaction-handler.js";
12
+ import { getMSTeamsRuntime } from "./runtime.js";
13
+ import type { MSTeamsTurnContext } from "./sdk-types.js";
14
+ import {
15
+ handleSigninTokenExchangeInvoke,
16
+ handleSigninVerifyStateInvoke,
17
+ parseSigninTokenExchangeValue,
18
+ parseSigninVerifyStateValue,
19
+ } from "./sso.js";
20
+ import { buildGroupWelcomeText, buildWelcomeCard } from "./welcome-card.js";
21
+ export type { MSTeamsMessageHandlerDeps } from "./monitor-handler.types.js";
22
+ import type { MSTeamsMessageHandlerDeps } from "./monitor-handler.types.js";
23
+
24
+ export type MSTeamsActivityHandler = {
25
+ onMessage: (
26
+ handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
27
+ ) => MSTeamsActivityHandler;
28
+ onMembersAdded: (
29
+ handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
30
+ ) => MSTeamsActivityHandler;
31
+ onReactionsAdded: (
32
+ handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
33
+ ) => MSTeamsActivityHandler;
34
+ onReactionsRemoved: (
35
+ handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
36
+ ) => MSTeamsActivityHandler;
37
+ run?: (context: unknown) => Promise<void>;
38
+ };
39
+
40
+ function serializeAdaptiveCardActionValue(value: unknown): string | null {
41
+ if (typeof value === "string") {
42
+ const trimmed = value.trim();
43
+ return trimmed ? trimmed : null;
44
+ }
45
+ if (value === undefined) {
46
+ return null;
47
+ }
48
+ try {
49
+ return JSON.stringify(value);
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ async function isInvokeAuthorized(params: {
56
+ context: MSTeamsTurnContext;
57
+ deps: MSTeamsMessageHandlerDeps;
58
+ deniedLogs: {
59
+ dm: string;
60
+ channel: string;
61
+ group: string;
62
+ };
63
+ includeInvokeName?: boolean;
64
+ }): Promise<boolean> {
65
+ const { context, deps, deniedLogs, includeInvokeName = false } = params;
66
+ const resolved = await resolveMSTeamsSenderAccess({
67
+ cfg: deps.cfg,
68
+ activity: context.activity,
69
+ });
70
+ const { msteamsCfg, isDirectMessage, conversationId, senderId } = resolved;
71
+ if (!msteamsCfg) {
72
+ return true;
73
+ }
74
+
75
+ const maybeInvokeName = includeInvokeName ? { name: context.activity.name } : undefined;
76
+
77
+ if (isDirectMessage && resolved.senderAccess.decision !== "allow") {
78
+ deps.log.debug?.(deniedLogs.dm, {
79
+ sender: senderId,
80
+ conversationId,
81
+ ...maybeInvokeName,
82
+ });
83
+ return false;
84
+ }
85
+
86
+ if (
87
+ !isDirectMessage &&
88
+ resolved.channelGate.allowlistConfigured &&
89
+ !resolved.channelGate.allowed
90
+ ) {
91
+ deps.log.debug?.(deniedLogs.channel, {
92
+ conversationId,
93
+ teamKey: resolved.channelGate.teamKey ?? "none",
94
+ channelKey: resolved.channelGate.channelKey ?? "none",
95
+ ...maybeInvokeName,
96
+ });
97
+ return false;
98
+ }
99
+
100
+ if (!isDirectMessage && !resolved.senderAccess.allowed) {
101
+ deps.log.debug?.(deniedLogs.group, {
102
+ sender: senderId,
103
+ conversationId,
104
+ ...maybeInvokeName,
105
+ });
106
+ return false;
107
+ }
108
+
109
+ return true;
110
+ }
111
+
112
+ async function isFeedbackInvokeAuthorized(
113
+ context: MSTeamsTurnContext,
114
+ deps: MSTeamsMessageHandlerDeps,
115
+ ): Promise<boolean> {
116
+ return isInvokeAuthorized({
117
+ context,
118
+ deps,
119
+ deniedLogs: {
120
+ dm: "dropping feedback invoke (dm sender not allowlisted)",
121
+ channel: "dropping feedback invoke (not in team/channel allowlist)",
122
+ group: "dropping feedback invoke (group sender not allowlisted)",
123
+ },
124
+ });
125
+ }
126
+
127
+ async function isSigninInvokeAuthorized(
128
+ context: MSTeamsTurnContext,
129
+ deps: MSTeamsMessageHandlerDeps,
130
+ ): Promise<boolean> {
131
+ return isInvokeAuthorized({
132
+ context,
133
+ deps,
134
+ deniedLogs: {
135
+ dm: "dropping signin invoke (dm sender not allowlisted)",
136
+ channel: "dropping signin invoke (not in team/channel allowlist)",
137
+ group: "dropping signin invoke (group sender not allowlisted)",
138
+ },
139
+ includeInvokeName: true,
140
+ });
141
+ }
142
+
143
+ /**
144
+ * Parse and handle feedback invoke activities (thumbs up/down).
145
+ * Returns true if the activity was a feedback invoke, false otherwise.
146
+ */
147
+ async function handleFeedbackInvoke(
148
+ context: MSTeamsTurnContext,
149
+ deps: MSTeamsMessageHandlerDeps,
150
+ ): Promise<boolean> {
151
+ const activity = context.activity;
152
+ const value = activity.value as
153
+ | {
154
+ actionName?: string;
155
+ actionValue?: { reaction?: string; feedback?: string };
156
+ replyToId?: string;
157
+ }
158
+ | undefined;
159
+
160
+ if (!value) {
161
+ return false;
162
+ }
163
+
164
+ // Teams feedback invoke format: actionName="feedback", actionValue.reaction="like"|"dislike"
165
+ if (value.actionName !== "feedback") {
166
+ return false;
167
+ }
168
+
169
+ const reaction = value.actionValue?.reaction;
170
+ if (reaction !== "like" && reaction !== "dislike") {
171
+ deps.log.debug?.("ignoring feedback with unknown reaction", { reaction });
172
+ return false;
173
+ }
174
+
175
+ const msteamsCfg = deps.cfg.channels?.msteams;
176
+ if (msteamsCfg?.feedbackEnabled === false) {
177
+ deps.log.debug?.("feedback handling disabled");
178
+ return true; // Still consume the invoke
179
+ }
180
+
181
+ if (!(await isFeedbackInvokeAuthorized(context, deps))) {
182
+ return true;
183
+ }
184
+
185
+ // Extract user comment from the nested JSON string
186
+ let userComment: string | undefined;
187
+ if (value.actionValue?.feedback) {
188
+ try {
189
+ const parsed = JSON.parse(value.actionValue.feedback) as { feedbackText?: string };
190
+ userComment = parsed.feedbackText || undefined;
191
+ } catch {
192
+ // Best effort — feedback text is optional
193
+ }
194
+ }
195
+
196
+ // Strip ;messageid=... suffix to match the normalized ID used by the message handler.
197
+ const rawConversationId = activity.conversation?.id ?? "unknown";
198
+ const conversationId = normalizeMSTeamsConversationId(rawConversationId);
199
+ const senderId = activity.from?.aadObjectId ?? activity.from?.id ?? "unknown";
200
+ const messageId = value.replyToId ?? activity.replyToId ?? "unknown";
201
+ const isNegative = reaction === "dislike";
202
+
203
+ // Route feedback using the same chat-type logic as normal messages
204
+ // so session keys, agent IDs, and transcript paths match.
205
+ const convType = normalizeOptionalLowercaseString(activity.conversation?.conversationType);
206
+ const isDirectMessage = convType === "personal" || (!convType && !activity.conversation?.isGroup);
207
+ const isChannel = convType === "channel";
208
+
209
+ const core = getMSTeamsRuntime();
210
+ const route = core.channel.routing.resolveAgentRoute({
211
+ cfg: deps.cfg,
212
+ channel: "msteams",
213
+ peer: {
214
+ kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
215
+ id: isDirectMessage ? senderId : conversationId,
216
+ },
217
+ });
218
+
219
+ // Match the thread-aware session key used by the message handler so feedback
220
+ // events land in the correct per-thread transcript. For channel threads, the
221
+ // thread root ID comes from the ;messageid= suffix on the conversation ID or
222
+ // from activity.replyToId.
223
+ const feedbackThreadId = isChannel
224
+ ? (extractMSTeamsConversationMessageId(rawConversationId) ?? activity.replyToId ?? undefined)
225
+ : undefined;
226
+ if (feedbackThreadId) {
227
+ const threadKeys = resolveThreadSessionKeys({
228
+ baseSessionKey: route.sessionKey,
229
+ threadId: feedbackThreadId,
230
+ parentSessionKey: route.sessionKey,
231
+ });
232
+ route.sessionKey = threadKeys.sessionKey;
233
+ }
234
+
235
+ // Log feedback event to session JSONL
236
+ const feedbackEvent = buildFeedbackEvent({
237
+ messageId,
238
+ value: isNegative ? "negative" : "positive",
239
+ comment: userComment,
240
+ sessionKey: route.sessionKey,
241
+ agentId: route.agentId,
242
+ conversationId,
243
+ });
244
+
245
+ deps.log.info("received feedback", {
246
+ value: feedbackEvent.value,
247
+ messageId,
248
+ conversationId,
249
+ hasComment: Boolean(userComment),
250
+ });
251
+
252
+ // Write feedback event to session transcript
253
+ try {
254
+ const storePath = core.channel.session.resolveStorePath(deps.cfg.session?.store, {
255
+ agentId: route.agentId,
256
+ });
257
+ const safeKey = route.sessionKey.replace(/[^a-zA-Z0-9_-]/g, "_");
258
+ const transcriptFile = path.join(storePath, `${safeKey}.jsonl`);
259
+ await appendRegularFile({
260
+ filePath: transcriptFile,
261
+ content: `${JSON.stringify(feedbackEvent)}\n`,
262
+ rejectSymlinkParents: true,
263
+ }).catch(() => {
264
+ // Best effort — transcript dir may not exist yet
265
+ });
266
+ } catch {
267
+ // Best effort
268
+ }
269
+
270
+ // Build conversation reference for proactive messages (ack + reflection follow-up)
271
+ const conversationRef = {
272
+ activityId: activity.id,
273
+ user: {
274
+ id: activity.from?.id,
275
+ name: activity.from?.name,
276
+ aadObjectId: activity.from?.aadObjectId,
277
+ },
278
+ agent: activity.recipient
279
+ ? { id: activity.recipient.id, name: activity.recipient.name }
280
+ : undefined,
281
+ bot: activity.recipient
282
+ ? { id: activity.recipient.id, name: activity.recipient.name }
283
+ : undefined,
284
+ conversation: {
285
+ id: conversationId,
286
+ conversationType: activity.conversation?.conversationType,
287
+ tenantId: activity.conversation?.tenantId,
288
+ },
289
+ channelId: activity.channelId ?? "msteams",
290
+ serviceUrl: activity.serviceUrl,
291
+ locale: activity.locale,
292
+ };
293
+
294
+ // For negative feedback, trigger background reflection (fire-and-forget).
295
+ // No ack message — the reflection follow-up serves as the acknowledgement.
296
+ // Sending anything during the invoke handler causes "unable to reach app" errors.
297
+ if (isNegative && msteamsCfg?.feedbackReflection !== false) {
298
+ // Note: thumbedDownResponse is not populated here because we don't cache
299
+ // sent message text. The agent still has full session context for reflection
300
+ // since the reflection runs in the same session. The user comment (if any)
301
+ // provides additional signal.
302
+ runFeedbackReflection({
303
+ cfg: deps.cfg,
304
+ adapter: deps.adapter,
305
+ appId: deps.appId,
306
+ conversationRef,
307
+ sessionKey: route.sessionKey,
308
+ agentId: route.agentId,
309
+ conversationId,
310
+ feedbackMessageId: messageId,
311
+ userComment,
312
+ log: deps.log,
313
+ }).catch((err) => {
314
+ deps.log.error("feedback reflection failed", { error: formatUnknownError(err) });
315
+ });
316
+ }
317
+
318
+ return true;
319
+ }
320
+
321
+ export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
322
+ handler: T,
323
+ deps: MSTeamsMessageHandlerDeps,
324
+ ): T {
325
+ const handleTeamsMessage = createMSTeamsMessageHandler(deps);
326
+ const handleReaction = createMSTeamsReactionHandler(deps);
327
+
328
+ // Wrap the original run method to intercept invokes
329
+ const originalRun = handler.run;
330
+ if (originalRun) {
331
+ handler.run = async (context: unknown) => {
332
+ const ctx = context as MSTeamsTurnContext;
333
+ // Handle file consent invokes before passing to normal flow
334
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "fileConsent/invoke") {
335
+ await respondToMSTeamsFileConsentInvoke(ctx, deps.log);
336
+ return;
337
+ }
338
+
339
+ // Handle feedback invokes (thumbs up/down on AI-generated messages).
340
+ // Just return after handling — the process() handler sends HTTP 200 automatically.
341
+ // Do NOT call sendActivity with invokeResponse; our custom adapter would POST
342
+ // a new activity to Bot Framework instead of responding to the HTTP request.
343
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "message/submitAction") {
344
+ const handled = await handleFeedbackInvoke(ctx, deps);
345
+ if (handled) {
346
+ return;
347
+ }
348
+ }
349
+
350
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "adaptiveCard/action") {
351
+ const text = serializeAdaptiveCardActionValue(ctx.activity?.value);
352
+ if (text) {
353
+ await handleTeamsMessage({
354
+ ...ctx,
355
+ activity: {
356
+ ...ctx.activity,
357
+ type: "message",
358
+ text,
359
+ },
360
+ });
361
+ return;
362
+ }
363
+ deps.log.debug?.("skipping adaptive card action invoke without value payload");
364
+ }
365
+
366
+ // Bot Framework OAuth SSO: Teams sends signin/tokenExchange (with a
367
+ // Teams-provided exchangeable token) or signin/verifyState (magic
368
+ // code fallback) after an oauthCard is presented. We must ack with
369
+ // HTTP 200 and, if configured, exchange the token with the Bot
370
+ // Framework User Token service and persist it for downstream tools.
371
+ if (
372
+ ctx.activity?.type === "invoke" &&
373
+ (ctx.activity?.name === "signin/tokenExchange" ||
374
+ ctx.activity?.name === "signin/verifyState")
375
+ ) {
376
+ // Always ack immediately — silently dropping the invoke causes
377
+ // the Teams card UI to report "Something went wrong".
378
+ await ctx.sendActivity({ type: "invokeResponse", value: { status: 200, body: {} } });
379
+
380
+ if (!(await isSigninInvokeAuthorized(ctx, deps))) {
381
+ return;
382
+ }
383
+
384
+ if (!deps.sso) {
385
+ deps.log.debug?.("signin invoke received but msteams.sso is not configured", {
386
+ name: ctx.activity.name,
387
+ });
388
+ return;
389
+ }
390
+
391
+ const user = {
392
+ userId: ctx.activity.from?.aadObjectId ?? ctx.activity.from?.id ?? "",
393
+ channelId: ctx.activity.channelId ?? "msteams",
394
+ };
395
+
396
+ try {
397
+ if (ctx.activity.name === "signin/tokenExchange") {
398
+ const parsed = parseSigninTokenExchangeValue(ctx.activity.value);
399
+ if (!parsed) {
400
+ deps.log.debug?.("invalid signin/tokenExchange invoke value");
401
+ return;
402
+ }
403
+ const result = await handleSigninTokenExchangeInvoke({
404
+ value: parsed,
405
+ user,
406
+ deps: deps.sso,
407
+ });
408
+ if (result.ok) {
409
+ deps.log.info("msteams sso token exchanged", {
410
+ userId: user.userId,
411
+ hasExpiry: Boolean(result.expiresAt),
412
+ });
413
+ } else {
414
+ deps.log.error("msteams sso token exchange failed", {
415
+ code: result.code,
416
+ status: result.status,
417
+ message: result.message,
418
+ });
419
+ }
420
+ return;
421
+ }
422
+
423
+ // signin/verifyState
424
+ const parsed = parseSigninVerifyStateValue(ctx.activity.value);
425
+ if (!parsed) {
426
+ deps.log.debug?.("invalid signin/verifyState invoke value");
427
+ return;
428
+ }
429
+ const result = await handleSigninVerifyStateInvoke({
430
+ value: parsed,
431
+ user,
432
+ deps: deps.sso,
433
+ });
434
+ if (result.ok) {
435
+ deps.log.info("msteams sso verifyState succeeded", {
436
+ userId: user.userId,
437
+ hasExpiry: Boolean(result.expiresAt),
438
+ });
439
+ } else {
440
+ deps.log.error("msteams sso verifyState failed", {
441
+ code: result.code,
442
+ status: result.status,
443
+ message: result.message,
444
+ });
445
+ }
446
+ } catch (err) {
447
+ deps.log.error("msteams sso invoke handler error", {
448
+ error: formatUnknownError(err),
449
+ });
450
+ }
451
+ return;
452
+ }
453
+
454
+ return originalRun.call(handler, context);
455
+ };
456
+ }
457
+
458
+ handler.onMessage(async (context, next) => {
459
+ try {
460
+ await handleTeamsMessage(context as MSTeamsTurnContext);
461
+ } catch (err) {
462
+ deps.runtime.error(`msteams handler failed: ${formatUnknownError(err)}`);
463
+ }
464
+ await next();
465
+ });
466
+
467
+ handler.onMembersAdded(async (context, next) => {
468
+ const ctx = context as MSTeamsTurnContext;
469
+ const membersAdded = ctx.activity?.membersAdded ?? [];
470
+ const botId = ctx.activity?.recipient?.id;
471
+ const msteamsCfg = deps.cfg.channels?.msteams;
472
+
473
+ for (const member of membersAdded) {
474
+ if (member.id === botId) {
475
+ // Bot was added to a conversation — send welcome card if configured.
476
+ const conversationType =
477
+ normalizeOptionalLowercaseString(ctx.activity?.conversation?.conversationType) ??
478
+ "personal";
479
+ const isPersonal = conversationType === "personal";
480
+
481
+ if (isPersonal && msteamsCfg?.welcomeCard !== false) {
482
+ const botName = ctx.activity?.recipient?.name ?? undefined;
483
+ const card = buildWelcomeCard({
484
+ botName,
485
+ promptStarters: msteamsCfg?.promptStarters,
486
+ });
487
+ try {
488
+ await ctx.sendActivity({
489
+ type: "message",
490
+ attachments: [
491
+ {
492
+ contentType: "application/vnd.microsoft.card.adaptive",
493
+ content: card,
494
+ },
495
+ ],
496
+ });
497
+ deps.log.info("sent welcome card");
498
+ } catch (err) {
499
+ deps.log.debug?.("failed to send welcome card", { error: formatUnknownError(err) });
500
+ }
501
+ } else if (!isPersonal && msteamsCfg?.groupWelcomeCard === true) {
502
+ const botName = ctx.activity?.recipient?.name ?? undefined;
503
+ try {
504
+ await ctx.sendActivity(buildGroupWelcomeText(botName));
505
+ deps.log.info("sent group welcome message");
506
+ } catch (err) {
507
+ deps.log.debug?.("failed to send group welcome", { error: formatUnknownError(err) });
508
+ }
509
+ } else {
510
+ deps.log.debug?.("skipping welcome (disabled by config or conversation type)");
511
+ }
512
+ } else {
513
+ deps.log.debug?.("member added", { member: member.id });
514
+ }
515
+ }
516
+ await next();
517
+ });
518
+
519
+ handler.onReactionsAdded(async (context, next) => {
520
+ try {
521
+ await handleReaction(context as MSTeamsTurnContext, "added");
522
+ } catch (err) {
523
+ deps.runtime.error(`msteams reaction handler failed: ${String(err)}`);
524
+ }
525
+ await next();
526
+ });
527
+
528
+ handler.onReactionsRemoved(async (context, next) => {
529
+ try {
530
+ await handleReaction(context as MSTeamsTurnContext, "removed");
531
+ } catch (err) {
532
+ deps.runtime.error(`msteams reaction handler failed: ${String(err)}`);
533
+ }
534
+ await next();
535
+ });
536
+
537
+ return handler;
538
+ }