@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,1015 @@
1
+ import { formatAllowlistMatchMeta } from "autobot/plugin-sdk/allow-from";
2
+ import { resolveInboundMentionDecision } from "autobot/plugin-sdk/channel-inbound";
3
+ import {
4
+ logInboundDrop,
5
+ resolveInboundSessionEnvelopeContext,
6
+ } from "autobot/plugin-sdk/channel-inbound";
7
+ import {
8
+ filterSupplementalContextItems,
9
+ resolveChannelContextVisibilityMode,
10
+ shouldIncludeSupplementalContext,
11
+ } from "autobot/plugin-sdk/context-visibility-runtime";
12
+ import {
13
+ dispatchReplyFromConfigWithSettledDispatcher,
14
+ hasFinalInboundReplyDispatch,
15
+ resolveInboundReplyDispatchCounts,
16
+ } from "autobot/plugin-sdk/inbound-reply-dispatch";
17
+ import {
18
+ DEFAULT_GROUP_HISTORY_LIMIT,
19
+ createChannelHistoryWindow,
20
+ type HistoryEntry,
21
+ } from "autobot/plugin-sdk/reply-history";
22
+ import {
23
+ buildMSTeamsAttachmentPlaceholder,
24
+ buildMSTeamsMediaPayload,
25
+ type MSTeamsAttachmentLike,
26
+ summarizeMSTeamsHtmlAttachments,
27
+ } from "../attachments.js";
28
+ import { isRecord } from "../attachments/shared.js";
29
+ import type { StoredConversationReference } from "../conversation-store.js";
30
+ import { formatUnknownError } from "../errors.js";
31
+ import {
32
+ fetchThreadReplies,
33
+ formatThreadContext,
34
+ resolveTeamGroupId,
35
+ type GraphThreadMessage,
36
+ } from "../graph-thread.js";
37
+ import { resolveGraphChatId } from "../graph-upload.js";
38
+ import {
39
+ extractMSTeamsConversationMessageId,
40
+ extractMSTeamsQuoteInfo,
41
+ normalizeMSTeamsConversationId,
42
+ parseMSTeamsActivityTimestamp,
43
+ stripMSTeamsMentionTags,
44
+ translateMSTeamsDmConversationIdForGraph,
45
+ wasMSTeamsBotMentioned,
46
+ } from "../inbound.js";
47
+ import {
48
+ fetchParentMessageCached,
49
+ formatParentContextEvent,
50
+ markParentContextInjected,
51
+ shouldInjectParentContext,
52
+ summarizeParentMessage,
53
+ } from "../thread-parent-context.js";
54
+
55
+ function extractTextFromHtmlAttachments(attachments: MSTeamsAttachmentLike[]): string {
56
+ for (const attachment of attachments) {
57
+ if (attachment.contentType !== "text/html") {
58
+ continue;
59
+ }
60
+ const content = attachment.content;
61
+ const raw =
62
+ typeof content === "string"
63
+ ? content
64
+ : isRecord(content) && typeof content.text === "string"
65
+ ? content.text
66
+ : isRecord(content) && typeof content.body === "string"
67
+ ? content.body
68
+ : "";
69
+ if (!raw) {
70
+ continue;
71
+ }
72
+ const text = raw
73
+ .replace(/<at[^>]*>.*?<\/at>/gis, " ")
74
+ .replace(/<a\b[^>]*href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gis, "$2 $1")
75
+ .replace(/<br\s*\/?>/gi, "\n")
76
+ .replace(/<\/p>/gi, "\n")
77
+ .replace(/<[^>]+>/g, " ")
78
+ .replace(/&nbsp;/gi, " ")
79
+ .replace(/&amp;/gi, "&")
80
+ .replace(/\s+/g, " ")
81
+ .trim();
82
+ if (text) {
83
+ return text;
84
+ }
85
+ }
86
+ return "";
87
+ }
88
+
89
+ import type { MSTeamsMessageHandlerDeps } from "../monitor-handler.types.js";
90
+ import { resolveMSTeamsAllowlistMatch, resolveMSTeamsReplyPolicy } from "../policy.js";
91
+ import { extractMSTeamsPollVote } from "../polls.js";
92
+ import { createMSTeamsReplyDispatcher } from "../reply-dispatcher.js";
93
+ import { getMSTeamsRuntime } from "../runtime.js";
94
+ import type { MSTeamsTurnContext } from "../sdk-types.js";
95
+ import {
96
+ recordMSTeamsSentMessage,
97
+ wasMSTeamsMessageSentWithPersistence,
98
+ } from "../sent-message-cache.js";
99
+ import { resolveMSTeamsSenderAccess } from "./access.js";
100
+ import { resolveMSTeamsInboundMedia } from "./inbound-media.js";
101
+ import { resolveMSTeamsRouteSessionKey } from "./thread-session.js";
102
+
103
+ function formatMSTeamsSenderReason(params: {
104
+ reasonCode: string;
105
+ dmPolicy?: string;
106
+ groupPolicy?: string;
107
+ }): string {
108
+ switch (params.reasonCode) {
109
+ case "dm_policy_open":
110
+ return "dmPolicy=open";
111
+ case "dm_policy_disabled":
112
+ return "dmPolicy=disabled";
113
+ case "dm_policy_pairing_required":
114
+ return "dmPolicy=pairing (not allowlisted)";
115
+ case "dm_policy_allowlisted":
116
+ return `dmPolicy=${params.dmPolicy ?? "allowlist"} (allowlisted)`;
117
+ case "dm_policy_not_allowlisted":
118
+ return `dmPolicy=${params.dmPolicy ?? "allowlist"} (not allowlisted)`;
119
+ case "group_policy_disabled":
120
+ return "groupPolicy=disabled";
121
+ case "group_policy_empty_allowlist":
122
+ case "route_sender_empty":
123
+ return "groupPolicy=allowlist (empty allowlist)";
124
+ case "group_policy_not_allowlisted":
125
+ return "groupPolicy=allowlist (not allowlisted)";
126
+ case "group_policy_open":
127
+ return "groupPolicy=open";
128
+ case "group_policy_allowed":
129
+ return `groupPolicy=${params.groupPolicy ?? "allowlist"}`;
130
+ default:
131
+ return params.reasonCode;
132
+ }
133
+ }
134
+
135
+ function buildStoredConversationReference(params: {
136
+ activity: MSTeamsTurnContext["activity"];
137
+ conversationId: string;
138
+ conversationType: string;
139
+ teamId?: string;
140
+ /** Thread root message ID for channel thread messages. */
141
+ threadId?: string;
142
+ }): StoredConversationReference {
143
+ const { activity, conversationId, conversationType, teamId, threadId } = params;
144
+ const from = activity.from;
145
+ const conversation = activity.conversation;
146
+ const agent = activity.recipient;
147
+ const clientInfo = activity.entities?.find((e) => e.type === "clientInfo") as
148
+ | { timezone?: string }
149
+ | undefined;
150
+ // Bot Framework requires `tenantId` on outbound proactive activities so the
151
+ // connector can route them to the correct Azure AD tenant; missing it causes
152
+ // HTTP 403. Channel activities often leave `conversation.tenantId` unset, so
153
+ // prefer the canonical `channelData.tenant.id` source when available.
154
+ const channelDataTenantId = activity.channelData?.tenant?.id;
155
+ const tenantId = channelDataTenantId ?? conversation?.tenantId;
156
+ const aadObjectId = from?.aadObjectId;
157
+ return {
158
+ activityId: activity.id,
159
+ user: from ? { id: from.id, name: from.name, aadObjectId: from.aadObjectId } : undefined,
160
+ agent,
161
+ bot: agent ? { id: agent.id, name: agent.name } : undefined,
162
+ conversation: {
163
+ id: conversationId,
164
+ conversationType,
165
+ tenantId,
166
+ },
167
+ ...(tenantId ? { tenantId } : {}),
168
+ ...(aadObjectId ? { aadObjectId } : {}),
169
+ teamId,
170
+ channelId: activity.channelId,
171
+ serviceUrl: activity.serviceUrl,
172
+ locale: activity.locale,
173
+ ...(clientInfo?.timezone ? { timezone: clientInfo.timezone } : {}),
174
+ ...(threadId ? { threadId } : {}),
175
+ };
176
+ }
177
+
178
+ export function createMSTeamsMessageHandler(deps: MSTeamsMessageHandlerDeps) {
179
+ const {
180
+ cfg,
181
+ runtime,
182
+ appId,
183
+ adapter,
184
+ tokenProvider,
185
+ textLimit,
186
+ mediaMaxBytes,
187
+ conversationStore,
188
+ pollStore,
189
+ log,
190
+ } = deps;
191
+ const core = getMSTeamsRuntime();
192
+ const logVerboseMessage = (message: string) => {
193
+ if (core.logging.shouldLogVerbose()) {
194
+ log.debug?.(message);
195
+ }
196
+ };
197
+ const msteamsCfg = cfg.channels?.msteams;
198
+ const contextVisibilityMode = resolveChannelContextVisibilityMode({
199
+ cfg,
200
+ channel: "msteams",
201
+ });
202
+ const historyLimit = Math.max(
203
+ 0,
204
+ msteamsCfg?.historyLimit ??
205
+ cfg.messages?.groupChat?.historyLimit ??
206
+ DEFAULT_GROUP_HISTORY_LIMIT,
207
+ );
208
+ const conversationHistories = new Map<string, HistoryEntry[]>();
209
+ const inboundDebounceMs = core.channel.debounce.resolveInboundDebounceMs({
210
+ cfg,
211
+ channel: "msteams",
212
+ });
213
+
214
+ type MSTeamsDebounceEntry = {
215
+ context: MSTeamsTurnContext;
216
+ rawText: string;
217
+ text: string;
218
+ attachments: MSTeamsAttachmentLike[];
219
+ wasMentioned: boolean;
220
+ implicitMentionKinds: Array<"reply_to_bot">;
221
+ };
222
+
223
+ const handleTeamsMessageNow = async (params: MSTeamsDebounceEntry) => {
224
+ const context = params.context;
225
+ const activity = context.activity;
226
+ const rawText = params.rawText;
227
+ const text = params.text;
228
+ const attachments = params.attachments;
229
+ const attachmentPlaceholder = buildMSTeamsAttachmentPlaceholder(attachments, {
230
+ maxInlineBytes: mediaMaxBytes,
231
+ maxInlineTotalBytes: mediaMaxBytes,
232
+ });
233
+ const rawBody = text || attachmentPlaceholder;
234
+ const quoteInfo = extractMSTeamsQuoteInfo(attachments);
235
+ let quoteSenderId: string | undefined;
236
+ let quoteSenderName: string | undefined;
237
+ const from = activity.from;
238
+ const conversation = activity.conversation;
239
+
240
+ const attachmentTypes = attachments
241
+ .map((att) => (typeof att.contentType === "string" ? att.contentType : undefined))
242
+ .filter(Boolean)
243
+ .slice(0, 3);
244
+ const htmlSummary = summarizeMSTeamsHtmlAttachments(attachments);
245
+
246
+ log.info("received message", {
247
+ rawText: rawText.slice(0, 50),
248
+ text: text.slice(0, 50),
249
+ attachments: attachments.length,
250
+ attachmentTypes,
251
+ from: from?.id,
252
+ conversation: conversation?.id,
253
+ });
254
+ if (htmlSummary) {
255
+ log.debug?.("html attachment summary", htmlSummary);
256
+ }
257
+
258
+ if (!from?.id) {
259
+ log.debug?.("skipping message without from.id");
260
+ return;
261
+ }
262
+
263
+ // Teams conversation.id may include ";messageid=..." suffix - strip it for session key.
264
+ const rawConversationId = conversation?.id ?? "";
265
+ const conversationId = normalizeMSTeamsConversationId(rawConversationId);
266
+ const conversationMessageId = extractMSTeamsConversationMessageId(rawConversationId);
267
+ const conversationType = conversation?.conversationType ?? "personal";
268
+ const teamId = activity.channelData?.team?.id;
269
+ // For channel thread messages, resolve the thread root message ID so outbound
270
+ // replies land in the correct thread. The root ID comes from the `messageid=`
271
+ // portion of conversation.id (preferred) or from activity.replyToId.
272
+ const threadId =
273
+ conversationType === "channel"
274
+ ? (conversationMessageId ?? activity.replyToId ?? undefined)
275
+ : undefined;
276
+ const conversationRef = buildStoredConversationReference({
277
+ activity,
278
+ conversationId,
279
+ conversationType,
280
+ teamId,
281
+ threadId,
282
+ });
283
+
284
+ const {
285
+ dmPolicy,
286
+ senderId,
287
+ senderName,
288
+ pairing,
289
+ isDirectMessage,
290
+ channelGate,
291
+ senderAccess,
292
+ commandAccess,
293
+ allowNameMatching,
294
+ groupPolicy,
295
+ } = await resolveMSTeamsSenderAccess({
296
+ cfg,
297
+ activity,
298
+ hasControlCommand: core.channel.text.hasControlCommand(text, cfg),
299
+ });
300
+ const commandAuthorized = commandAccess.requested ? commandAccess.authorized : undefined;
301
+ const effectiveDmAllowFrom = senderAccess.effectiveAllowFrom;
302
+ const effectiveGroupAllowFrom = senderAccess.effectiveGroupAllowFrom;
303
+ const isChannel = conversationType === "channel";
304
+
305
+ if (isDirectMessage && msteamsCfg && senderAccess.decision !== "allow") {
306
+ if (senderAccess.reasonCode === "dm_policy_disabled") {
307
+ log.info("dropping dm (dms disabled)", {
308
+ sender: senderId,
309
+ label: senderName,
310
+ });
311
+ log.debug?.("dropping dm (dms disabled)");
312
+ return;
313
+ }
314
+ const allowMatch = resolveMSTeamsAllowlistMatch({
315
+ allowFrom: effectiveDmAllowFrom,
316
+ senderId,
317
+ senderName,
318
+ allowNameMatching,
319
+ });
320
+ if (senderAccess.decision === "pairing") {
321
+ conversationStore.upsert(conversationId, conversationRef).catch((err) => {
322
+ log.debug?.("failed to save conversation reference", {
323
+ error: formatUnknownError(err),
324
+ });
325
+ });
326
+ const request = await pairing.upsertPairingRequest({
327
+ id: senderId,
328
+ meta: { name: senderName },
329
+ });
330
+ if (request) {
331
+ log.info("msteams pairing request created", {
332
+ sender: senderId,
333
+ label: senderName,
334
+ });
335
+ }
336
+ }
337
+ log.debug?.("dropping dm (not allowlisted)", {
338
+ sender: senderId,
339
+ label: senderName,
340
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch),
341
+ });
342
+ log.info("dropping dm (not allowlisted)", {
343
+ sender: senderId,
344
+ label: senderName,
345
+ dmPolicy,
346
+ reason: formatMSTeamsSenderReason({
347
+ reasonCode: senderAccess.reasonCode,
348
+ dmPolicy,
349
+ groupPolicy,
350
+ }),
351
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch),
352
+ });
353
+ return;
354
+ }
355
+
356
+ if (!isDirectMessage && msteamsCfg) {
357
+ if (channelGate.allowlistConfigured && !channelGate.allowed) {
358
+ log.info("dropping group message (not in team/channel allowlist)", {
359
+ conversationId,
360
+ teamKey: channelGate.teamKey ?? "none",
361
+ channelKey: channelGate.channelKey ?? "none",
362
+ channelMatchKey: channelGate.channelMatchKey ?? "none",
363
+ channelMatchSource: channelGate.channelMatchSource ?? "none",
364
+ });
365
+ log.debug?.("dropping group message (not in team/channel allowlist)", {
366
+ conversationId,
367
+ teamKey: channelGate.teamKey ?? "none",
368
+ channelKey: channelGate.channelKey ?? "none",
369
+ channelMatchKey: channelGate.channelMatchKey ?? "none",
370
+ channelMatchSource: channelGate.channelMatchSource ?? "none",
371
+ });
372
+ return;
373
+ }
374
+
375
+ if (!senderAccess.allowed && senderAccess.reasonCode === "group_policy_disabled") {
376
+ log.info("dropping group message (groupPolicy: disabled)", {
377
+ conversationId,
378
+ });
379
+ log.debug?.("dropping group message (groupPolicy: disabled)", {
380
+ conversationId,
381
+ });
382
+ return;
383
+ }
384
+ if (
385
+ !senderAccess.allowed &&
386
+ (senderAccess.reasonCode === "group_policy_empty_allowlist" ||
387
+ senderAccess.reasonCode === "route_sender_empty")
388
+ ) {
389
+ log.info("dropping group message (groupPolicy: allowlist, no allowlist)", {
390
+ conversationId,
391
+ });
392
+ log.debug?.("dropping group message (groupPolicy: allowlist, no allowlist)", {
393
+ conversationId,
394
+ });
395
+ return;
396
+ }
397
+ if (!senderAccess.allowed && senderAccess.reasonCode === "group_policy_not_allowlisted") {
398
+ const allowMatch = resolveMSTeamsAllowlistMatch({
399
+ allowFrom: effectiveGroupAllowFrom,
400
+ senderId,
401
+ senderName,
402
+ allowNameMatching,
403
+ });
404
+ log.debug?.("dropping group message (not in groupAllowFrom)", {
405
+ sender: senderId,
406
+ label: senderName,
407
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch),
408
+ });
409
+ log.info("dropping group message (not in groupAllowFrom)", {
410
+ sender: senderId,
411
+ label: senderName,
412
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch),
413
+ });
414
+ return;
415
+ }
416
+ }
417
+
418
+ if (commandAccess.shouldBlockControlCommand) {
419
+ logInboundDrop({
420
+ log: logVerboseMessage,
421
+ channel: "msteams",
422
+ reason: "control command (unauthorized)",
423
+ target: senderId,
424
+ });
425
+ return;
426
+ }
427
+
428
+ conversationStore.upsert(conversationId, conversationRef).catch((err) => {
429
+ log.debug?.("failed to save conversation reference", {
430
+ error: formatUnknownError(err),
431
+ });
432
+ });
433
+
434
+ const pollVote = extractMSTeamsPollVote(activity);
435
+ if (pollVote) {
436
+ try {
437
+ const poll = await pollStore.recordVote({
438
+ pollId: pollVote.pollId,
439
+ voterId: senderId,
440
+ selections: pollVote.selections,
441
+ });
442
+ if (!poll) {
443
+ log.debug?.("poll vote ignored (poll not found)", {
444
+ pollId: pollVote.pollId,
445
+ });
446
+ } else {
447
+ log.info("recorded poll vote", {
448
+ pollId: pollVote.pollId,
449
+ voter: senderId,
450
+ selections: pollVote.selections,
451
+ });
452
+ }
453
+ } catch (err) {
454
+ log.error("failed to record poll vote", {
455
+ pollId: pollVote.pollId,
456
+ error: formatUnknownError(err),
457
+ });
458
+ }
459
+ return;
460
+ }
461
+
462
+ if (!rawBody) {
463
+ log.debug?.("skipping empty message after stripping mentions");
464
+ return;
465
+ }
466
+
467
+ const teamsFrom = isDirectMessage
468
+ ? `msteams:${senderId}`
469
+ : isChannel
470
+ ? `msteams:channel:${conversationId}`
471
+ : `msteams:group:${conversationId}`;
472
+ const teamsTo = isDirectMessage ? `user:${senderId}` : `conversation:${conversationId}`;
473
+
474
+ const route = core.channel.routing.resolveAgentRoute({
475
+ cfg,
476
+ channel: "msteams",
477
+ teamId,
478
+ peer: {
479
+ kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
480
+ id: isDirectMessage ? senderId : conversationId,
481
+ },
482
+ });
483
+
484
+ // Isolate channel thread sessions: each thread gets its own session key so
485
+ // context does not bleed across threads. Prefer conversationMessageId (the
486
+ // ;messageid= portion of conversation.id, i.e. the thread root) over
487
+ // activity.replyToId (which may point to a non-root parent in deep threads).
488
+ // DMs and group chats are unaffected — only channel thread replies fork.
489
+ route.sessionKey = resolveMSTeamsRouteSessionKey({
490
+ baseSessionKey: route.sessionKey,
491
+ isChannel,
492
+ conversationMessageId,
493
+ replyToId: activity.replyToId,
494
+ });
495
+
496
+ const preview = rawBody.replace(/\s+/g, " ").slice(0, 160);
497
+ const inboundLabel = isDirectMessage
498
+ ? `Teams DM from ${senderName}`
499
+ : `Teams message in ${conversationType} from ${senderName}`;
500
+
501
+ const enqueuePrimaryMessageSystemEvent = (opts?: {
502
+ forceSenderIsOwnerFalse?: boolean;
503
+ trusted?: boolean;
504
+ }) =>
505
+ core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, {
506
+ sessionKey: route.sessionKey,
507
+ contextKey: `msteams:message:${conversationId}:${activity.id ?? "unknown"}`,
508
+ ...opts,
509
+ });
510
+
511
+ const channelId = conversationId;
512
+ const { teamConfig, channelConfig } = channelGate;
513
+ const { requireMention, replyStyle } = resolveMSTeamsReplyPolicy({
514
+ isDirectMessage,
515
+ globalConfig: msteamsCfg,
516
+ teamConfig,
517
+ channelConfig,
518
+ });
519
+ const timestamp = parseMSTeamsActivityTimestamp(activity.timestamp);
520
+ const mentionDecision = resolveInboundMentionDecision({
521
+ facts: {
522
+ canDetectMention: true,
523
+ wasMentioned: params.wasMentioned,
524
+ implicitMentionKinds: params.implicitMentionKinds,
525
+ },
526
+ policy: {
527
+ isGroup: !isDirectMessage,
528
+ requireMention,
529
+ allowTextCommands: false,
530
+ hasControlCommand: false,
531
+ commandAuthorized: false,
532
+ },
533
+ });
534
+
535
+ if (!isDirectMessage) {
536
+ const mentioned = mentionDecision.effectiveWasMentioned;
537
+ if (requireMention && mentionDecision.shouldSkip) {
538
+ log.debug?.("skipping message (mention required)", {
539
+ teamId,
540
+ channelId,
541
+ requireMention,
542
+ mentioned,
543
+ });
544
+ enqueuePrimaryMessageSystemEvent({
545
+ forceSenderIsOwnerFalse: true,
546
+ trusted: false,
547
+ });
548
+ createChannelHistoryWindow({ historyMap: conversationHistories }).record({
549
+ historyKey: conversationId,
550
+ limit: historyLimit,
551
+ entry: {
552
+ sender: senderName,
553
+ body: rawBody,
554
+ timestamp: timestamp?.getTime(),
555
+ messageId: activity.id ?? undefined,
556
+ },
557
+ });
558
+ return;
559
+ }
560
+ }
561
+ enqueuePrimaryMessageSystemEvent();
562
+ let graphConversationId = translateMSTeamsDmConversationIdForGraph({
563
+ isDirectMessage,
564
+ conversationId,
565
+ aadObjectId: from.aadObjectId,
566
+ appId,
567
+ });
568
+
569
+ // For personal DMs the Bot Framework conversation ID (`a:...`) and the
570
+ // synthetic `19:{userId}_{appId}@unq.gbl.spaces` format produced by
571
+ // translateMSTeamsDmConversationIdForGraph are not always accepted by the
572
+ // Graph `/chats/{chatId}/messages` endpoint. Resolve the real Graph chat
573
+ // ID via the API (with conversation store caching) so the Graph media
574
+ // download fallback works when the direct Bot Framework download fails.
575
+ if (isDirectMessage && conversationId.startsWith("a:")) {
576
+ const cached = await conversationStore.get(conversationId);
577
+ if (cached?.graphChatId) {
578
+ graphConversationId = cached.graphChatId;
579
+ } else {
580
+ try {
581
+ const resolved = await resolveGraphChatId({
582
+ botFrameworkConversationId: conversationId,
583
+ userAadObjectId: from.aadObjectId ?? undefined,
584
+ tokenProvider,
585
+ });
586
+ if (resolved) {
587
+ graphConversationId = resolved;
588
+ conversationStore
589
+ .upsert(conversationId, { ...conversationRef, graphChatId: resolved })
590
+ .catch(() => {});
591
+ }
592
+ } catch {
593
+ log.debug?.("failed to resolve Graph chat ID for inbound media", { conversationId });
594
+ }
595
+ }
596
+ }
597
+
598
+ const mediaList = await resolveMSTeamsInboundMedia({
599
+ attachments,
600
+ htmlSummary: htmlSummary ?? undefined,
601
+ maxBytes: mediaMaxBytes,
602
+ tokenProvider,
603
+ allowHosts: msteamsCfg?.mediaAllowHosts,
604
+ authAllowHosts: msteamsCfg?.mediaAuthAllowHosts,
605
+ conversationType,
606
+ conversationId: graphConversationId,
607
+ conversationMessageId: conversationMessageId ?? undefined,
608
+ serviceUrl: activity.serviceUrl,
609
+ activity: {
610
+ id: activity.id,
611
+ replyToId: activity.replyToId,
612
+ channelData: activity.channelData,
613
+ },
614
+ log,
615
+ preserveFilenames: (cfg as { media?: { preserveFilenames?: boolean } }).media
616
+ ?.preserveFilenames,
617
+ });
618
+
619
+ const mediaPayload = buildMSTeamsMediaPayload(mediaList);
620
+
621
+ // Fetch thread history when the message is a reply inside a Teams channel thread.
622
+ // This is a best-effort enhancement; errors are logged and do not block the reply.
623
+ //
624
+ // We also enqueue a compact `Replying to @sender: …` system event when the parent
625
+ // is resolvable. On brand-new thread sessions (see PR #62713), this gives the agent
626
+ // immediate parent context even before the fuller `[Thread history]` block is assembled.
627
+ // Parent fetches are cached (5 min LRU, 100 entries) and per-session deduped so
628
+ // consecutive replies in the same thread do not re-inject identical context.
629
+ let threadContext: string | undefined;
630
+ if (activity.replyToId && isChannel && teamId) {
631
+ try {
632
+ const graphToken = await tokenProvider.getAccessToken("https://graph.microsoft.com");
633
+ const groupId = await resolveTeamGroupId(graphToken, teamId);
634
+ // Use allSettled so a failure in one fetch does not discard the other.
635
+ // For example, reply-fetch 403 should not throw away a successful parent fetch.
636
+ const [parentResult, repliesResult] = await Promise.allSettled([
637
+ fetchParentMessageCached(graphToken, groupId, conversationId, activity.replyToId),
638
+ fetchThreadReplies(graphToken, groupId, conversationId, activity.replyToId),
639
+ ]);
640
+ const parentMsg = parentResult.status === "fulfilled" ? parentResult.value : undefined;
641
+ const replies = repliesResult.status === "fulfilled" ? repliesResult.value : [];
642
+ if (parentResult.status === "rejected") {
643
+ log.debug?.("failed to fetch parent message", {
644
+ error: formatUnknownError(parentResult.reason),
645
+ });
646
+ }
647
+ if (repliesResult.status === "rejected") {
648
+ log.debug?.("failed to fetch thread replies", {
649
+ error: formatUnknownError(repliesResult.reason),
650
+ });
651
+ }
652
+ const isThreadSenderAllowed = (msg: GraphThreadMessage) =>
653
+ groupPolicy === "allowlist"
654
+ ? resolveMSTeamsAllowlistMatch({
655
+ allowFrom: effectiveGroupAllowFrom,
656
+ senderId: msg.from?.user?.id ?? "",
657
+ senderName: msg.from?.user?.displayName,
658
+ allowNameMatching,
659
+ }).allowed
660
+ : true;
661
+ const parentSummary = summarizeParentMessage(parentMsg);
662
+ const visibleParentMessages = parentMsg
663
+ ? filterSupplementalContextItems({
664
+ items: [parentMsg],
665
+ mode: contextVisibilityMode,
666
+ kind: "thread",
667
+ isSenderAllowed: isThreadSenderAllowed,
668
+ }).items
669
+ : [];
670
+ if (
671
+ parentSummary &&
672
+ visibleParentMessages.length > 0 &&
673
+ shouldInjectParentContext(route.sessionKey, activity.replyToId)
674
+ ) {
675
+ core.system.enqueueSystemEvent(formatParentContextEvent(parentSummary), {
676
+ sessionKey: route.sessionKey,
677
+ contextKey: `msteams:thread-parent:${conversationId}:${activity.replyToId}`,
678
+ forceSenderIsOwnerFalse: true,
679
+ trusted: false,
680
+ });
681
+ markParentContextInjected(route.sessionKey, activity.replyToId);
682
+ }
683
+ const allMessages = parentMsg ? [parentMsg, ...replies] : replies;
684
+ quoteSenderId = parentMsg?.from?.user?.id ?? parentMsg?.from?.application?.id ?? undefined;
685
+ quoteSenderName =
686
+ parentMsg?.from?.user?.displayName ??
687
+ parentMsg?.from?.application?.displayName ??
688
+ quoteInfo?.sender;
689
+ const { items: threadMessages } = filterSupplementalContextItems({
690
+ items: allMessages,
691
+ mode: contextVisibilityMode,
692
+ kind: "thread",
693
+ isSenderAllowed: isThreadSenderAllowed,
694
+ });
695
+ const formatted = formatThreadContext(threadMessages, activity.id);
696
+ if (formatted) {
697
+ threadContext = formatted;
698
+ }
699
+ } catch (err) {
700
+ log.debug?.("failed to fetch thread history", { error: formatUnknownError(err) });
701
+ // Graceful degradation: thread history is an optional enhancement.
702
+ }
703
+ }
704
+ quoteSenderName ??= quoteInfo?.sender;
705
+
706
+ const envelopeFrom = isDirectMessage ? senderName : conversationType;
707
+ const { storePath, envelopeOptions, previousTimestamp } = resolveInboundSessionEnvelopeContext({
708
+ cfg,
709
+ agentId: route.agentId,
710
+ sessionKey: route.sessionKey,
711
+ });
712
+ const body = core.channel.reply.formatAgentEnvelope({
713
+ channel: "Teams",
714
+ from: envelopeFrom,
715
+ timestamp,
716
+ previousTimestamp,
717
+ envelope: envelopeOptions,
718
+ body: rawBody,
719
+ });
720
+ let combinedBody = body;
721
+ const isRoomish = !isDirectMessage;
722
+ const historyKey = isRoomish ? conversationId : undefined;
723
+ if (isRoomish && historyKey) {
724
+ const channelHistory = createChannelHistoryWindow({ historyMap: conversationHistories });
725
+ combinedBody = channelHistory.buildPendingContext({
726
+ historyKey,
727
+ limit: historyLimit,
728
+ currentMessage: combinedBody,
729
+ formatEntry: (entry) =>
730
+ core.channel.reply.formatAgentEnvelope({
731
+ channel: "Teams",
732
+ from: conversationType,
733
+ timestamp: entry.timestamp,
734
+ body: `${entry.sender}: ${entry.body}${entry.messageId ? ` [id:${entry.messageId}]` : ""}`,
735
+ envelope: envelopeOptions,
736
+ }),
737
+ });
738
+ }
739
+
740
+ const inboundHistory =
741
+ isRoomish && historyKey && historyLimit > 0
742
+ ? createChannelHistoryWindow({ historyMap: conversationHistories }).buildInboundHistory({
743
+ historyKey,
744
+ limit: historyLimit,
745
+ })
746
+ : undefined;
747
+ const commandBody = text.trim();
748
+ const quoteSenderAllowed =
749
+ quoteInfo && quoteInfo.sender
750
+ ? !isChannel || groupPolicy !== "allowlist"
751
+ ? true
752
+ : resolveMSTeamsAllowlistMatch({
753
+ allowFrom: effectiveGroupAllowFrom,
754
+ senderId: quoteSenderId ?? "",
755
+ senderName: quoteSenderName,
756
+ allowNameMatching,
757
+ }).allowed
758
+ : true;
759
+ const includeQuoteContext =
760
+ quoteInfo &&
761
+ shouldIncludeSupplementalContext({
762
+ mode: contextVisibilityMode,
763
+ kind: "quote",
764
+ senderAllowed: quoteSenderAllowed,
765
+ });
766
+
767
+ // Prepend thread history to the agent body so the agent has full thread context.
768
+ const bodyForAgent = threadContext
769
+ ? `[Thread history]\n${threadContext}\n[/Thread history]\n\n${rawBody}`
770
+ : rawBody;
771
+
772
+ // For Teams *channel* messages (not group chats / DMs), preserve the
773
+ // `teamId/channelId` pair on NativeChannelId so downstream action handlers
774
+ // can route through `/teams/{teamId}/channels/{channelId}` via Graph API.
775
+ // The bare conversation id (`19:...@thread.tacv2`) is insufficient on its
776
+ // own because channel Graph endpoints require the owning team id too.
777
+ const nativeChannelId = isChannel && teamId ? `${teamId}/${conversationId}` : undefined;
778
+
779
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
780
+ Body: combinedBody,
781
+ BodyForAgent: bodyForAgent,
782
+ InboundHistory: inboundHistory,
783
+ RawBody: rawBody,
784
+ CommandBody: commandBody,
785
+ BodyForCommands: commandBody,
786
+ From: teamsFrom,
787
+ To: teamsTo,
788
+ SessionKey: route.sessionKey,
789
+ AccountId: route.accountId,
790
+ ChatType: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
791
+ ConversationLabel: envelopeFrom,
792
+ GroupSubject: !isDirectMessage ? conversationType : undefined,
793
+ GroupSpace: teamId,
794
+ SenderName: senderName,
795
+ SenderId: senderId,
796
+ Provider: "msteams" as const,
797
+ Surface: "msteams" as const,
798
+ MessageSid: activity.id,
799
+ Timestamp: timestamp?.getTime() ?? Date.now(),
800
+ WasMentioned: isDirectMessage || mentionDecision.effectiveWasMentioned,
801
+ CommandAuthorized: commandAuthorized,
802
+ OriginatingChannel: "msteams" as const,
803
+ OriginatingTo: teamsTo,
804
+ NativeChannelId: nativeChannelId,
805
+ ReplyToId: activity.replyToId ?? undefined,
806
+ ReplyToBody: includeQuoteContext ? quoteInfo?.body : undefined,
807
+ ReplyToSender: includeQuoteContext ? quoteInfo?.sender : undefined,
808
+ ReplyToIsQuote: quoteInfo ? true : undefined,
809
+ ...mediaPayload,
810
+ });
811
+
812
+ logVerboseMessage(`msteams inbound: from=${ctxPayload.From} preview="${preview}"`);
813
+
814
+ const sharePointSiteId = msteamsCfg?.sharePointSiteId;
815
+ const { dispatcher, replyOptions, markDispatchIdle } = createMSTeamsReplyDispatcher({
816
+ cfg,
817
+ agentId: route.agentId,
818
+ sessionKey: route.sessionKey,
819
+ accountId: route.accountId,
820
+ runtime,
821
+ log,
822
+ adapter,
823
+ appId,
824
+ conversationRef,
825
+ context,
826
+ replyStyle,
827
+ textLimit,
828
+ onSentMessageIds: (ids) => {
829
+ for (const id of ids) {
830
+ recordMSTeamsSentMessage(conversationId, id);
831
+ }
832
+ },
833
+ tokenProvider,
834
+ sharePointSiteId,
835
+ });
836
+
837
+ // Use Teams clientInfo timezone if no explicit userTimezone is configured.
838
+ // This ensures the agent knows the sender's timezone for time-aware responses
839
+ // and proactive sends within the same session.
840
+ const activityClientInfo = activity.entities?.find((e) => e.type === "clientInfo") as
841
+ | { timezone?: string }
842
+ | undefined;
843
+ const senderTimezone = activityClientInfo?.timezone || conversationRef.timezone;
844
+ const configOverride =
845
+ senderTimezone && !cfg.agents?.defaults?.userTimezone
846
+ ? {
847
+ agents: {
848
+ defaults: { ...cfg.agents?.defaults, userTimezone: senderTimezone },
849
+ },
850
+ }
851
+ : undefined;
852
+
853
+ log.info("dispatching to agent", { sessionKey: route.sessionKey });
854
+ try {
855
+ const turnResult = await core.channel.turn.run({
856
+ channel: "msteams",
857
+ accountId: route.accountId,
858
+ raw: context,
859
+ adapter: {
860
+ ingest: () => ({
861
+ id: activity.id ?? `${teamsFrom}:${Date.now()}`,
862
+ timestamp: timestamp?.getTime(),
863
+ rawText: rawBody,
864
+ textForAgent: bodyForAgent,
865
+ textForCommands: commandBody,
866
+ raw: activity,
867
+ }),
868
+ resolveTurn: () => ({
869
+ channel: "msteams",
870
+ accountId: route.accountId,
871
+ routeSessionKey: route.sessionKey,
872
+ storePath,
873
+ ctxPayload,
874
+ recordInboundSession: core.channel.session.recordInboundSession,
875
+ record: {
876
+ onRecordError: (err) => {
877
+ logVerboseMessage(
878
+ `msteams: failed updating session meta: ${formatUnknownError(err)}`,
879
+ );
880
+ },
881
+ },
882
+ history: {
883
+ isGroup: isRoomish,
884
+ historyKey,
885
+ historyMap: conversationHistories,
886
+ limit: historyLimit,
887
+ },
888
+ onPreDispatchFailure: () =>
889
+ core.channel.reply.settleReplyDispatcher({
890
+ dispatcher,
891
+ onSettled: () => markDispatchIdle(),
892
+ }),
893
+ runDispatch: () =>
894
+ dispatchReplyFromConfigWithSettledDispatcher({
895
+ cfg,
896
+ ctxPayload,
897
+ dispatcher,
898
+ onSettled: () => markDispatchIdle(),
899
+ replyOptions,
900
+ configOverride,
901
+ }),
902
+ }),
903
+ },
904
+ });
905
+ const dispatchResult = turnResult.dispatched ? turnResult.dispatchResult : undefined;
906
+ const queuedFinal = dispatchResult?.queuedFinal ?? false;
907
+ const counts = resolveInboundReplyDispatchCounts(dispatchResult);
908
+ const hasFinalResponse = hasFinalInboundReplyDispatch(dispatchResult);
909
+
910
+ log.info("dispatch complete", { queuedFinal, counts });
911
+
912
+ if (!hasFinalResponse) {
913
+ return;
914
+ }
915
+ const finalCount = counts.final;
916
+ logVerboseMessage(
917
+ `msteams: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${teamsTo}`,
918
+ );
919
+ } catch (err) {
920
+ log.error("dispatch failed", { error: formatUnknownError(err) });
921
+ runtime.error(`msteams dispatch failed: ${formatUnknownError(err)}`);
922
+ try {
923
+ await context.sendActivity("⚠️ Something went wrong. Please try again.");
924
+ } catch {
925
+ // Best effort.
926
+ }
927
+ }
928
+ };
929
+
930
+ const inboundDebouncer = core.channel.debounce.createInboundDebouncer<MSTeamsDebounceEntry>({
931
+ debounceMs: inboundDebounceMs,
932
+ buildKey: (entry) => {
933
+ const conversationId = normalizeMSTeamsConversationId(
934
+ entry.context.activity.conversation?.id ?? "",
935
+ );
936
+ const senderId =
937
+ entry.context.activity.from?.aadObjectId ?? entry.context.activity.from?.id ?? "";
938
+ if (!senderId || !conversationId) {
939
+ return null;
940
+ }
941
+ return `msteams:${appId}:${conversationId}:${senderId}`;
942
+ },
943
+ shouldDebounce: (entry) => {
944
+ if (!entry.text.trim()) {
945
+ return false;
946
+ }
947
+ if (entry.attachments.length > 0) {
948
+ return false;
949
+ }
950
+ return !core.channel.text.hasControlCommand(entry.text, cfg);
951
+ },
952
+ onFlush: async (entries) => {
953
+ const last = entries.at(-1);
954
+ if (!last) {
955
+ return;
956
+ }
957
+ if (entries.length === 1) {
958
+ await handleTeamsMessageNow(last);
959
+ return;
960
+ }
961
+ const combinedText = entries
962
+ .map((entry) => entry.text)
963
+ .filter(Boolean)
964
+ .join("\n");
965
+ if (!combinedText.trim()) {
966
+ return;
967
+ }
968
+ const combinedRawText = entries
969
+ .map((entry) => entry.rawText)
970
+ .filter(Boolean)
971
+ .join("\n");
972
+ const wasMentioned = entries.some((entry) => entry.wasMentioned);
973
+ const implicitMentionKinds = entries.flatMap((entry) => entry.implicitMentionKinds);
974
+ await handleTeamsMessageNow({
975
+ context: last.context,
976
+ rawText: combinedRawText,
977
+ text: combinedText,
978
+ attachments: [],
979
+ wasMentioned,
980
+ implicitMentionKinds,
981
+ });
982
+ },
983
+ onError: (err) => {
984
+ runtime.error(`msteams debounce flush failed: ${formatUnknownError(err)}`);
985
+ },
986
+ });
987
+
988
+ return async function handleTeamsMessage(context: MSTeamsTurnContext) {
989
+ const activity = context.activity;
990
+ const attachments = Array.isArray(activity.attachments)
991
+ ? (activity.attachments as unknown as MSTeamsAttachmentLike[])
992
+ : [];
993
+ const rawText = activity.text?.trim() ?? "";
994
+ const htmlText = extractTextFromHtmlAttachments(attachments);
995
+ const text = stripMSTeamsMentionTags(rawText || htmlText);
996
+ const wasMentioned = wasMSTeamsBotMentioned(activity);
997
+ const conversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "");
998
+ const replyToId = activity.replyToId ?? undefined;
999
+ const implicitMentionKinds: Array<"reply_to_bot"> =
1000
+ conversationId &&
1001
+ replyToId &&
1002
+ (await wasMSTeamsMessageSentWithPersistence({ conversationId, messageId: replyToId }))
1003
+ ? ["reply_to_bot"]
1004
+ : [];
1005
+
1006
+ await inboundDebouncer.enqueue({
1007
+ context,
1008
+ rawText,
1009
+ text,
1010
+ attachments,
1011
+ wasMentioned,
1012
+ implicitMentionKinds,
1013
+ });
1014
+ };
1015
+ }