@kodelyth/msteams 2026.5.42 → 2026.6.1

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 (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +16 -4
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
package/src/messenger.ts DELETED
@@ -1,608 +0,0 @@
1
- import {
2
- isSilentReplyText,
3
- SILENT_REPLY_TOKEN,
4
- type ChunkMode,
5
- } from "klaw/plugin-sdk/reply-chunking";
6
- import {
7
- resolveSendableOutboundReplyParts,
8
- type ReplyPayload,
9
- } from "klaw/plugin-sdk/reply-payload";
10
- import { normalizeOptionalLowercaseString } from "klaw/plugin-sdk/string-coerce-runtime";
11
- import { sleep } from "klaw/plugin-sdk/text-utility-runtime";
12
- import { loadWebMedia } from "klaw/plugin-sdk/web-media";
13
- import type { MarkdownTableMode, MSTeamsReplyStyle, KlawConfig } 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 KlawConfig,
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
- }