@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,608 @@
1
+ import {
2
+ isSilentReplyText,
3
+ SILENT_REPLY_TOKEN,
4
+ type ChunkMode,
5
+ } from "autobot/plugin-sdk/reply-chunking";
6
+ import {
7
+ resolveSendableOutboundReplyParts,
8
+ type ReplyPayload,
9
+ } from "autobot/plugin-sdk/reply-payload";
10
+ import { normalizeOptionalLowercaseString } from "autobot/plugin-sdk/string-coerce-runtime";
11
+ import { sleep } from "autobot/plugin-sdk/text-utility-runtime";
12
+ import { loadWebMedia } from "autobot/plugin-sdk/web-media";
13
+ import type { MarkdownTableMode, MSTeamsReplyStyle, AutoBotConfig } from "../runtime-api.js";
14
+ import type { MSTeamsAccessTokenProvider } from "./attachments/types.js";
15
+ import type { StoredConversationReference } from "./conversation-store.js";
16
+ import { classifyMSTeamsSendError } from "./errors.js";
17
+ import { prepareFileConsentActivity, requiresFileConsent } from "./file-consent-helpers.js";
18
+ import { buildTeamsFileInfoCard } from "./graph-chat.js";
19
+ import {
20
+ getDriveItemProperties,
21
+ uploadAndShareOneDrive,
22
+ uploadAndShareSharePoint,
23
+ } from "./graph-upload.js";
24
+ import { extractFilename, extractMessageId, getMimeType, isLocalPath } from "./media-helpers.js";
25
+ import { parseMentions } from "./mentions.js";
26
+ import { setPendingUploadActivityId } from "./pending-uploads.js";
27
+ import { withRevokedProxyFallback } from "./revoked-context.js";
28
+ import { getMSTeamsRuntime } from "./runtime.js";
29
+
30
+ /**
31
+ * MSTeams-specific media size limit (100MB).
32
+ * Higher than the default because OneDrive upload handles large files well.
33
+ */
34
+ const MSTEAMS_MAX_MEDIA_BYTES = 100 * 1024 * 1024;
35
+
36
+ /**
37
+ * Threshold for large files that require FileConsentCard flow in personal chats.
38
+ * Files >= 4MB use consent flow; smaller images can use inline base64.
39
+ */
40
+ const FILE_CONSENT_THRESHOLD_BYTES = 4 * 1024 * 1024;
41
+
42
+ type SendContext = {
43
+ sendActivity: (textOrActivity: string | object) => Promise<unknown>;
44
+ updateActivity: (activity: object) => Promise<{ id?: string } | void>;
45
+ deleteActivity: (activityId: string) => Promise<void>;
46
+ };
47
+
48
+ type MSTeamsConversationReference = {
49
+ activityId?: string;
50
+ user?: { id?: string; name?: string; aadObjectId?: string };
51
+ agent?: { id?: string; name?: string; aadObjectId?: string } | null;
52
+ conversation: { id: string; conversationType?: string; tenantId?: string };
53
+ channelId: string;
54
+ serviceUrl?: string;
55
+ locale?: string;
56
+ /**
57
+ * Top-level tenant ID echoed onto the Bot Framework connector request. Included
58
+ * alongside `conversation.tenantId` so the connector can route proactive sends
59
+ * to the correct Azure AD tenant. Missing it causes HTTP 403 on proactive
60
+ * (bot-initiated) messages.
61
+ */
62
+ tenantId?: string;
63
+ /**
64
+ * Azure AD object ID of the target user, forwarded on proactive sends so
65
+ * Bot Framework can resolve the personal DM recipient on the connector side.
66
+ */
67
+ aadObjectId?: string;
68
+ };
69
+
70
+ export type MSTeamsAdapter = {
71
+ continueConversation: (
72
+ appId: string,
73
+ reference: MSTeamsConversationReference,
74
+ logic: (context: SendContext) => Promise<void>,
75
+ ) => Promise<void>;
76
+ process: (
77
+ req: unknown,
78
+ res: unknown,
79
+ logic: (context: unknown) => Promise<void>,
80
+ ) => Promise<void>;
81
+ updateActivity: (context: unknown, activity: object) => Promise<void>;
82
+ deleteActivity: (context: unknown, reference: { activityId?: string }) => Promise<void>;
83
+ };
84
+
85
+ type MSTeamsReplyRenderOptions = {
86
+ textChunkLimit: number;
87
+ chunkText?: boolean;
88
+ mediaMode?: "split" | "inline";
89
+ tableMode?: MarkdownTableMode;
90
+ chunkMode?: ChunkMode;
91
+ };
92
+
93
+ /**
94
+ * A rendered message that preserves media vs text distinction.
95
+ * When mediaUrl is present, it will be sent as a Bot Framework attachment.
96
+ */
97
+ export type MSTeamsRenderedMessage = {
98
+ text?: string;
99
+ mediaUrl?: string;
100
+ };
101
+
102
+ type MSTeamsSendRetryOptions = {
103
+ maxAttempts?: number;
104
+ baseDelayMs?: number;
105
+ maxDelayMs?: number;
106
+ };
107
+
108
+ type MSTeamsSendRetryEvent = {
109
+ messageIndex: number;
110
+ messageCount: number;
111
+ nextAttempt: number;
112
+ maxAttempts: number;
113
+ delayMs: number;
114
+ classification: ReturnType<typeof classifyMSTeamsSendError>;
115
+ };
116
+
117
+ function normalizeConversationId(rawId: string): string {
118
+ return rawId.split(";")[0] ?? rawId;
119
+ }
120
+
121
+ export function buildConversationReference(
122
+ ref: StoredConversationReference,
123
+ ): MSTeamsConversationReference {
124
+ const conversationId = ref.conversation?.id?.trim();
125
+ if (!conversationId) {
126
+ throw new Error("Invalid stored reference: missing conversation.id");
127
+ }
128
+ const agent = ref.agent ?? ref.bot ?? undefined;
129
+ if (agent == null || !agent.id) {
130
+ throw new Error("Invalid stored reference: missing agent.id");
131
+ }
132
+ const user = ref.user;
133
+ if (!user?.id) {
134
+ throw new Error("Invalid stored reference: missing user.id");
135
+ }
136
+ // Bot Framework proactive sends require `tenantId` on the outbound activity
137
+ // so the connector routes to the correct Azure AD tenant; otherwise it rejects
138
+ // with HTTP 403. Prefer the explicit top-level `ref.tenantId` (captured from
139
+ // `channelData.tenant.id` inbound) and fall back to `conversation.tenantId`.
140
+ const tenantId = ref.tenantId ?? ref.conversation?.tenantId;
141
+ const aadObjectId = ref.aadObjectId ?? user.aadObjectId;
142
+ return {
143
+ activityId: ref.activityId,
144
+ user: aadObjectId ? { ...user, aadObjectId } : user,
145
+ agent,
146
+ conversation: {
147
+ id: normalizeConversationId(conversationId),
148
+ conversationType: ref.conversation?.conversationType,
149
+ tenantId,
150
+ },
151
+ channelId: ref.channelId ?? "msteams",
152
+ serviceUrl: ref.serviceUrl,
153
+ locale: ref.locale,
154
+ ...(tenantId ? { tenantId } : {}),
155
+ ...(aadObjectId ? { aadObjectId } : {}),
156
+ };
157
+ }
158
+
159
+ function pushTextMessages(
160
+ out: MSTeamsRenderedMessage[],
161
+ text: string,
162
+ opts: {
163
+ chunkText: boolean;
164
+ chunkLimit: number;
165
+ chunkMode: ChunkMode;
166
+ },
167
+ ) {
168
+ if (!text) {
169
+ return;
170
+ }
171
+ if (opts.chunkText) {
172
+ for (const chunk of getMSTeamsRuntime().channel.text.chunkMarkdownTextWithMode(
173
+ text,
174
+ opts.chunkLimit,
175
+ opts.chunkMode,
176
+ )) {
177
+ const trimmed = chunk.trim();
178
+ if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) {
179
+ continue;
180
+ }
181
+ out.push({ text: trimmed });
182
+ }
183
+ return;
184
+ }
185
+
186
+ const trimmed = text.trim();
187
+ if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) {
188
+ return;
189
+ }
190
+ out.push({ text: trimmed });
191
+ }
192
+
193
+ function clampMs(value: number, maxMs: number): number {
194
+ if (!Number.isFinite(value) || value < 0) {
195
+ return 0;
196
+ }
197
+ return Math.min(value, maxMs);
198
+ }
199
+
200
+ function resolveRetryOptions(
201
+ retry: false | MSTeamsSendRetryOptions | undefined,
202
+ ): Required<MSTeamsSendRetryOptions> & { enabled: boolean } {
203
+ if (!retry) {
204
+ return { enabled: false, maxAttempts: 1, baseDelayMs: 0, maxDelayMs: 0 };
205
+ }
206
+ return {
207
+ enabled: true,
208
+ maxAttempts: Math.max(1, retry?.maxAttempts ?? 3),
209
+ baseDelayMs: Math.max(0, retry?.baseDelayMs ?? 250),
210
+ maxDelayMs: Math.max(0, retry?.maxDelayMs ?? 10_000),
211
+ };
212
+ }
213
+
214
+ function computeRetryDelayMs(
215
+ attempt: number,
216
+ classification: ReturnType<typeof classifyMSTeamsSendError>,
217
+ opts: Required<MSTeamsSendRetryOptions>,
218
+ ): number {
219
+ if (classification.retryAfterMs != null) {
220
+ return clampMs(classification.retryAfterMs, opts.maxDelayMs);
221
+ }
222
+ const exponential = opts.baseDelayMs * 2 ** Math.max(0, attempt - 1);
223
+ return clampMs(exponential, opts.maxDelayMs);
224
+ }
225
+
226
+ function shouldRetry(classification: ReturnType<typeof classifyMSTeamsSendError>): boolean {
227
+ return classification.kind === "throttled" || classification.kind === "transient";
228
+ }
229
+
230
+ export function renderReplyPayloadsToMessages(
231
+ replies: ReplyPayload[],
232
+ options: MSTeamsReplyRenderOptions,
233
+ ): MSTeamsRenderedMessage[] {
234
+ const out: MSTeamsRenderedMessage[] = [];
235
+ const chunkLimit = Math.min(options.textChunkLimit, 4000);
236
+ const chunkText = options.chunkText !== false;
237
+ const chunkMode = options.chunkMode ?? "length";
238
+ const mediaMode = options.mediaMode ?? "split";
239
+ const tableMode =
240
+ options.tableMode ??
241
+ getMSTeamsRuntime().channel.text.resolveMarkdownTableMode({
242
+ cfg: getMSTeamsRuntime().config.current() as AutoBotConfig,
243
+ channel: "msteams",
244
+ });
245
+
246
+ for (const payload of replies) {
247
+ const reply = resolveSendableOutboundReplyParts(payload, {
248
+ text: getMSTeamsRuntime().channel.text.convertMarkdownTables(payload.text ?? "", tableMode),
249
+ });
250
+
251
+ if (!reply.hasContent) {
252
+ continue;
253
+ }
254
+
255
+ if (!reply.hasMedia) {
256
+ pushTextMessages(out, reply.text, { chunkText, chunkLimit, chunkMode });
257
+ continue;
258
+ }
259
+
260
+ if (mediaMode === "inline") {
261
+ // For inline mode, combine text with first media as attachment
262
+ const firstMedia = reply.mediaUrls[0];
263
+ if (firstMedia) {
264
+ out.push({ text: reply.text || undefined, mediaUrl: firstMedia });
265
+ // Additional media URLs as separate messages
266
+ for (let i = 1; i < reply.mediaUrls.length; i++) {
267
+ if (reply.mediaUrls[i]) {
268
+ out.push({ mediaUrl: reply.mediaUrls[i] });
269
+ }
270
+ }
271
+ } else {
272
+ pushTextMessages(out, reply.text, { chunkText, chunkLimit, chunkMode });
273
+ }
274
+ continue;
275
+ }
276
+
277
+ // mediaMode === "split"
278
+ pushTextMessages(out, reply.text, { chunkText, chunkLimit, chunkMode });
279
+ for (const mediaUrl of reply.mediaUrls) {
280
+ if (!mediaUrl) {
281
+ continue;
282
+ }
283
+ out.push({ mediaUrl });
284
+ }
285
+ }
286
+
287
+ return out;
288
+ }
289
+
290
+ import { AI_GENERATED_ENTITY } from "./ai-entity.js";
291
+
292
+ export async function buildActivity(
293
+ msg: MSTeamsRenderedMessage,
294
+ conversationRef: StoredConversationReference,
295
+ tokenProvider?: MSTeamsAccessTokenProvider,
296
+ sharePointSiteId?: string,
297
+ mediaMaxBytes?: number,
298
+ options?: { feedbackLoopEnabled?: boolean },
299
+ ): Promise<Record<string, unknown>> {
300
+ const activity: Record<string, unknown> = { type: "message" };
301
+
302
+ // Mark as AI-generated so Teams renders the "AI generated" badge.
303
+ activity.channelData = {
304
+ feedbackLoopEnabled: options?.feedbackLoopEnabled ?? false,
305
+ };
306
+
307
+ if (msg.text) {
308
+ // Parse mentions from text (format: @[Name](id))
309
+ const { text: formattedText, entities } = parseMentions(msg.text);
310
+ activity.text = formattedText;
311
+
312
+ // Start with mention entities (if any) + AI-generated entity
313
+ activity.entities = [...(entities.length > 0 ? entities : []), AI_GENERATED_ENTITY];
314
+ } else {
315
+ activity.entities = [AI_GENERATED_ENTITY];
316
+ }
317
+
318
+ if (msg.mediaUrl) {
319
+ let contentUrl = msg.mediaUrl;
320
+ let contentType = await getMimeType(msg.mediaUrl);
321
+ let fileName = await extractFilename(msg.mediaUrl);
322
+
323
+ if (isLocalPath(msg.mediaUrl)) {
324
+ const maxBytes = mediaMaxBytes ?? MSTEAMS_MAX_MEDIA_BYTES;
325
+ const media = await loadWebMedia(msg.mediaUrl, maxBytes);
326
+ contentType = media.contentType ?? contentType;
327
+ fileName = media.fileName ?? fileName;
328
+
329
+ // Determine conversation type and file type
330
+ // Teams only accepts base64 data URLs for images
331
+ const conversationType = normalizeOptionalLowercaseString(
332
+ conversationRef.conversation?.conversationType,
333
+ );
334
+ const isPersonal = conversationType === "personal";
335
+ const isImage = media.kind === "image";
336
+
337
+ if (
338
+ requiresFileConsent({
339
+ conversationType,
340
+ contentType,
341
+ bufferSize: media.buffer.length,
342
+ thresholdBytes: FILE_CONSENT_THRESHOLD_BYTES,
343
+ })
344
+ ) {
345
+ // Large file or non-image in personal chat: use FileConsentCard flow
346
+ const conversationId = conversationRef.conversation?.id ?? "unknown";
347
+ const { activity: consentActivity, uploadId } = prepareFileConsentActivity({
348
+ media: { buffer: media.buffer, filename: fileName, contentType },
349
+ conversationId,
350
+ description: msg.text || undefined,
351
+ });
352
+
353
+ // Tag the activity so the caller can store the activity ID after sending
354
+ consentActivity["_pendingUploadId"] = uploadId;
355
+
356
+ // Return the consent activity (caller sends it)
357
+ return consentActivity;
358
+ }
359
+
360
+ if (!isPersonal && !isImage && tokenProvider && sharePointSiteId) {
361
+ // Non-image in group chat/channel with SharePoint site configured:
362
+ // Upload to SharePoint and use native file card attachment.
363
+ // Use the cached Graph-native chat ID when available — Bot Framework conversation IDs
364
+ // for personal DMs use a format (e.g. `a:1xxx`) that Graph API rejects.
365
+ const chatId = conversationRef.graphChatId ?? conversationRef.conversation?.id;
366
+
367
+ // Upload to SharePoint
368
+ const uploaded = await uploadAndShareSharePoint({
369
+ buffer: media.buffer,
370
+ filename: fileName,
371
+ contentType,
372
+ tokenProvider,
373
+ siteId: sharePointSiteId,
374
+ chatId: chatId ?? undefined,
375
+ usePerUserSharing: conversationType === "groupchat",
376
+ });
377
+
378
+ // Get driveItem properties needed for native file card attachment
379
+ const driveItem = await getDriveItemProperties({
380
+ siteId: sharePointSiteId,
381
+ itemId: uploaded.itemId,
382
+ tokenProvider,
383
+ });
384
+
385
+ // Build native Teams file card attachment
386
+ const fileCardAttachment = buildTeamsFileInfoCard(driveItem);
387
+ activity.attachments = [fileCardAttachment];
388
+
389
+ return activity;
390
+ }
391
+
392
+ if (!isPersonal && media.kind !== "image" && tokenProvider) {
393
+ // Fallback: no SharePoint site configured, try OneDrive upload
394
+ const uploaded = await uploadAndShareOneDrive({
395
+ buffer: media.buffer,
396
+ filename: fileName,
397
+ contentType,
398
+ tokenProvider,
399
+ });
400
+
401
+ // Bot Framework doesn't support "reference" attachment type for sending
402
+ const fileLink = `📎 [${uploaded.name}](${uploaded.shareUrl})`;
403
+ const existingText = typeof activity.text === "string" ? activity.text : undefined;
404
+ activity.text = existingText ? `${existingText}\n\n${fileLink}` : fileLink;
405
+ return activity;
406
+ }
407
+
408
+ // Image (any chat): use base64 (works for images in all conversation types)
409
+ const base64 = media.buffer.toString("base64");
410
+ contentUrl = `data:${media.contentType};base64,${base64}`;
411
+ }
412
+
413
+ activity.attachments = [
414
+ {
415
+ name: fileName,
416
+ contentType,
417
+ contentUrl,
418
+ },
419
+ ];
420
+ }
421
+
422
+ return activity;
423
+ }
424
+
425
+ export async function sendMSTeamsMessages(params: {
426
+ replyStyle: MSTeamsReplyStyle;
427
+ adapter: MSTeamsAdapter;
428
+ appId: string;
429
+ conversationRef: StoredConversationReference;
430
+ context?: SendContext;
431
+ messages: MSTeamsRenderedMessage[];
432
+ retry?: false | MSTeamsSendRetryOptions;
433
+ onRetry?: (event: MSTeamsSendRetryEvent) => void;
434
+ /** Token provider for OneDrive/SharePoint uploads in group chats/channels */
435
+ tokenProvider?: MSTeamsAccessTokenProvider;
436
+ /** SharePoint site ID for file uploads in group chats/channels */
437
+ sharePointSiteId?: string;
438
+ /** Max media size in bytes. Default: 100MB. */
439
+ mediaMaxBytes?: number;
440
+ /** Enable the Teams feedback loop (thumbs up/down) on sent messages. */
441
+ feedbackLoopEnabled?: boolean;
442
+ }): Promise<string[]> {
443
+ const messages = params.messages.filter(
444
+ (m) => (m.text && m.text.trim().length > 0) || m.mediaUrl,
445
+ );
446
+ if (messages.length === 0) {
447
+ return [];
448
+ }
449
+
450
+ const retryOptions = resolveRetryOptions(params.retry);
451
+
452
+ const sendWithRetry = async (
453
+ sendOnce: () => Promise<unknown>,
454
+ meta: { messageIndex: number; messageCount: number },
455
+ ): Promise<unknown> => {
456
+ if (!retryOptions.enabled) {
457
+ return await sendOnce();
458
+ }
459
+
460
+ let attempt = 1;
461
+ while (true) {
462
+ try {
463
+ return await sendOnce();
464
+ } catch (err) {
465
+ const classification = classifyMSTeamsSendError(err);
466
+ const canRetry = attempt < retryOptions.maxAttempts && shouldRetry(classification);
467
+ if (!canRetry) {
468
+ throw err;
469
+ }
470
+
471
+ const delayMs = computeRetryDelayMs(attempt, classification, retryOptions);
472
+ const nextAttempt = attempt + 1;
473
+ params.onRetry?.({
474
+ messageIndex: meta.messageIndex,
475
+ messageCount: meta.messageCount,
476
+ nextAttempt,
477
+ maxAttempts: retryOptions.maxAttempts,
478
+ delayMs,
479
+ classification,
480
+ });
481
+
482
+ await sleep(delayMs);
483
+ attempt = nextAttempt;
484
+ }
485
+ }
486
+ };
487
+
488
+ const sendMessageInContext = async (
489
+ ctx: SendContext,
490
+ message: MSTeamsRenderedMessage,
491
+ messageIndex: number,
492
+ ): Promise<string> => {
493
+ let pendingUploadId: string | undefined;
494
+ const response = await sendWithRetry(
495
+ async () => {
496
+ const activity = await buildActivity(
497
+ message,
498
+ params.conversationRef,
499
+ params.tokenProvider,
500
+ params.sharePointSiteId,
501
+ params.mediaMaxBytes,
502
+ { feedbackLoopEnabled: params.feedbackLoopEnabled },
503
+ );
504
+
505
+ // Extract and strip the internal-only pending upload tag before sending.
506
+ pendingUploadId =
507
+ typeof activity["_pendingUploadId"] === "string"
508
+ ? activity["_pendingUploadId"]
509
+ : undefined;
510
+ if (pendingUploadId) {
511
+ delete activity["_pendingUploadId"];
512
+ }
513
+
514
+ return await ctx.sendActivity(activity);
515
+ },
516
+ {
517
+ messageIndex,
518
+ messageCount: messages.length,
519
+ },
520
+ );
521
+ const messageId = extractMessageId(response) ?? "unknown";
522
+
523
+ // Store the activity ID so the accept handler can replace the consent card in-place
524
+ if (pendingUploadId && messageId !== "unknown") {
525
+ setPendingUploadActivityId(pendingUploadId, messageId);
526
+ }
527
+
528
+ return messageId;
529
+ };
530
+
531
+ const sendMessageBatchInContext = async (
532
+ ctx: SendContext,
533
+ batch: MSTeamsRenderedMessage[],
534
+ startIndex: number,
535
+ ): Promise<string[]> => {
536
+ const messageIds: string[] = [];
537
+ for (const [idx, message] of batch.entries()) {
538
+ messageIds.push(await sendMessageInContext(ctx, message, startIndex + idx));
539
+ }
540
+ return messageIds;
541
+ };
542
+
543
+ const sendProactively = async (
544
+ batch: MSTeamsRenderedMessage[],
545
+ startIndex: number,
546
+ threadActivityId?: string,
547
+ ): Promise<string[]> => {
548
+ const baseRef = buildConversationReference(params.conversationRef);
549
+ const isChannel = params.conversationRef.conversation?.conversationType === "channel";
550
+ // For Teams channels, reconstruct the threaded conversation ID so the
551
+ // proactive message lands in the correct thread instead of creating a
552
+ // new top-level post in the channel.
553
+ const conversationId =
554
+ isChannel && threadActivityId
555
+ ? `${baseRef.conversation.id};messageid=${threadActivityId}`
556
+ : baseRef.conversation.id;
557
+ const proactiveRef: MSTeamsConversationReference = {
558
+ ...baseRef,
559
+ activityId: undefined,
560
+ conversation: { ...baseRef.conversation, id: conversationId },
561
+ };
562
+
563
+ const messageIds: string[] = [];
564
+ await params.adapter.continueConversation(params.appId, proactiveRef, async (ctx) => {
565
+ messageIds.push(...(await sendMessageBatchInContext(ctx, batch, startIndex)));
566
+ });
567
+ return messageIds;
568
+ };
569
+
570
+ // Resolve the thread root message ID for channel thread routing.
571
+ // `threadId` is the canonical thread root (set on inbound for channel threads);
572
+ // fall back to `activityId` for backward compatibility with older stored refs.
573
+ const resolvedThreadId = params.conversationRef.threadId ?? params.conversationRef.activityId;
574
+
575
+ if (params.replyStyle === "thread") {
576
+ const ctx = params.context;
577
+ if (!ctx) {
578
+ return await sendProactively(messages, 0, resolvedThreadId);
579
+ }
580
+ const messageIds: string[] = [];
581
+ for (const [idx, message] of messages.entries()) {
582
+ const result = await withRevokedProxyFallback({
583
+ run: async () => ({
584
+ ids: [await sendMessageInContext(ctx, message, idx)],
585
+ fellBack: false,
586
+ }),
587
+ onRevoked: async () => {
588
+ // When the live turn context is revoked (e.g. debounced messages),
589
+ // reconstruct the threaded conversation ID so the proactive
590
+ // fallback delivers the reply into the correct channel thread.
591
+ const remaining = messages.slice(idx);
592
+ return {
593
+ ids:
594
+ remaining.length > 0 ? await sendProactively(remaining, idx, resolvedThreadId) : [],
595
+ fellBack: true,
596
+ };
597
+ },
598
+ });
599
+ messageIds.push(...result.ids);
600
+ if (result.fellBack) {
601
+ return messageIds;
602
+ }
603
+ }
604
+ return messageIds;
605
+ }
606
+
607
+ return await sendProactively(messages, 0);
608
+ }