@openclaw/msteams 2026.5.2 → 2026.5.3-beta.2

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