@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
@@ -0,0 +1,2194 @@
1
+ import { L as getMSTeamsRuntime, O as resolveChannelMediaMaxBytes, _ as getFileExtension, b as loadOutboundMediaFromUrl, d as detectMime, h as extractOriginalFilename, m as extensionForMime, w as normalizeStringEntries } from "./runtime-api-DV1iVMn1.js";
2
+ import { C as loadMSTeamsSdkWithAuth, D as formatMSTeamsSendErrorHint, E as classifyMSTeamsSendError, O as formatUnknownError, S as createMSTeamsTokenProvider, _ as resolveMSTeamsStorePath, h as resolveMSTeamsCredentials, k as isRevokedProxyError, m as loadDelegatedTokens, w as buildUserAgent, x as createMSTeamsAdapter, y as readAccessToken } from "./graph-users-9uQJepqr.js";
3
+ import { convertMarkdownTables, normalizeLowercaseStringOrEmpty, normalizeOptionalLowercaseString, sleep } from "openclaw/plugin-sdk/text-runtime";
4
+ import { withFileLock } from "openclaw/plugin-sdk/file-lock";
5
+ import { resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
6
+ import { lookup } from "node:dns/promises";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { readJsonFileWithFallback, writeJsonFileAtomically } from "openclaw/plugin-sdk/json-store";
10
+ import crypto from "node:crypto";
11
+ import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
12
+ import { SILENT_REPLY_TOKEN, isSilentReplyText } from "openclaw/plugin-sdk/reply-chunking";
13
+ import { loadWebMedia } from "openclaw/plugin-sdk/web-media";
14
+ //#region extensions/msteams/src/conversation-store-helpers.ts
15
+ function normalizeStoredConversationId(raw) {
16
+ return raw.split(";")[0] ?? raw;
17
+ }
18
+ function parseStoredConversationTimestamp(value) {
19
+ if (!value) return null;
20
+ const parsed = Date.parse(value);
21
+ if (!Number.isFinite(parsed)) return null;
22
+ return parsed;
23
+ }
24
+ function toConversationStoreEntries(entries) {
25
+ return Array.from(entries, ([conversationId, reference]) => ({
26
+ conversationId,
27
+ reference
28
+ }));
29
+ }
30
+ function mergeStoredConversationReference(existing, incoming, nowIso) {
31
+ return {
32
+ ...existing?.timezone && !incoming.timezone ? { timezone: existing.timezone } : {},
33
+ ...existing?.graphChatId && !incoming.graphChatId ? { graphChatId: existing.graphChatId } : {},
34
+ ...existing?.tenantId && !incoming.tenantId ? { tenantId: existing.tenantId } : {},
35
+ ...existing?.aadObjectId && !incoming.aadObjectId ? { aadObjectId: existing.aadObjectId } : {},
36
+ ...incoming,
37
+ lastSeenAt: nowIso
38
+ };
39
+ }
40
+ function findPreferredDmConversationByUserId(entries, id) {
41
+ const target = id.trim();
42
+ if (!target) return null;
43
+ const personalMatches = [];
44
+ const unknownTypeMatches = [];
45
+ for (const entry of entries) {
46
+ if (entry.reference.user?.aadObjectId !== target && entry.reference.user?.id !== target) continue;
47
+ const convType = normalizeLowercaseStringOrEmpty(entry.reference.conversation?.conversationType ?? "");
48
+ if (convType === "personal") personalMatches.push(entry);
49
+ else if (convType === "channel" || convType === "groupchat") {} else unknownTypeMatches.push(entry);
50
+ }
51
+ const candidates = personalMatches.length > 0 ? personalMatches : unknownTypeMatches;
52
+ if (candidates.length === 0) return null;
53
+ if (candidates.length > 1) candidates.sort((a, b) => (parseStoredConversationTimestamp(b.reference.lastSeenAt) ?? 0) - (parseStoredConversationTimestamp(a.reference.lastSeenAt) ?? 0));
54
+ return candidates[0] ?? null;
55
+ }
56
+ //#endregion
57
+ //#region extensions/msteams/src/store-fs.ts
58
+ const STORE_LOCK_OPTIONS = {
59
+ retries: {
60
+ retries: 10,
61
+ factor: 2,
62
+ minTimeout: 100,
63
+ maxTimeout: 1e4,
64
+ randomize: true
65
+ },
66
+ stale: 3e4
67
+ };
68
+ async function readJsonFile(filePath, fallback) {
69
+ return await readJsonFileWithFallback(filePath, fallback);
70
+ }
71
+ async function writeJsonFile(filePath, value) {
72
+ await writeJsonFileAtomically(filePath, value);
73
+ }
74
+ async function ensureJsonFile(filePath, fallback) {
75
+ try {
76
+ await fs.promises.access(filePath);
77
+ } catch {
78
+ await writeJsonFile(filePath, fallback);
79
+ }
80
+ }
81
+ async function withFileLock$1(filePath, fallback, fn) {
82
+ await ensureJsonFile(filePath, fallback);
83
+ return await withFileLock(filePath, STORE_LOCK_OPTIONS, async () => {
84
+ return await fn();
85
+ });
86
+ }
87
+ //#endregion
88
+ //#region extensions/msteams/src/conversation-store-fs.ts
89
+ const STORE_FILENAME$2 = "msteams-conversations.json";
90
+ const MAX_CONVERSATIONS = 1e3;
91
+ const CONVERSATION_TTL_MS = 365 * 24 * 60 * 60 * 1e3;
92
+ function pruneToLimit$2(conversations) {
93
+ const entries = Object.entries(conversations);
94
+ if (entries.length <= MAX_CONVERSATIONS) return conversations;
95
+ entries.sort((a, b) => {
96
+ return (parseStoredConversationTimestamp(a[1].lastSeenAt) ?? 0) - (parseStoredConversationTimestamp(b[1].lastSeenAt) ?? 0);
97
+ });
98
+ const keep = entries.slice(entries.length - MAX_CONVERSATIONS);
99
+ return Object.fromEntries(keep);
100
+ }
101
+ function pruneExpired$2(conversations, nowMs, ttlMs) {
102
+ let removed = false;
103
+ const kept = {};
104
+ for (const [conversationId, reference] of Object.entries(conversations)) {
105
+ const lastSeenAt = parseStoredConversationTimestamp(reference.lastSeenAt);
106
+ if (lastSeenAt != null && nowMs - lastSeenAt > ttlMs) {
107
+ removed = true;
108
+ continue;
109
+ }
110
+ kept[conversationId] = reference;
111
+ }
112
+ return {
113
+ conversations: kept,
114
+ removed
115
+ };
116
+ }
117
+ function createMSTeamsConversationStoreFs(params) {
118
+ const ttlMs = params?.ttlMs ?? CONVERSATION_TTL_MS;
119
+ const filePath = resolveMSTeamsStorePath({
120
+ filename: STORE_FILENAME$2,
121
+ env: params?.env,
122
+ homedir: params?.homedir,
123
+ stateDir: params?.stateDir,
124
+ storePath: params?.storePath
125
+ });
126
+ const empty = {
127
+ version: 1,
128
+ conversations: {}
129
+ };
130
+ const readStore = async () => {
131
+ const { value } = await readJsonFile(filePath, empty);
132
+ if (value.version !== 1 || !value.conversations || typeof value.conversations !== "object" || Array.isArray(value.conversations)) return empty;
133
+ const nowMs = Date.now();
134
+ const pruned = pruneExpired$2(value.conversations, nowMs, ttlMs).conversations;
135
+ return {
136
+ version: 1,
137
+ conversations: pruneToLimit$2(pruned)
138
+ };
139
+ };
140
+ const list = async () => {
141
+ const store = await readStore();
142
+ return toConversationStoreEntries(Object.entries(store.conversations));
143
+ };
144
+ const get = async (conversationId) => {
145
+ return (await readStore()).conversations[normalizeStoredConversationId(conversationId)] ?? null;
146
+ };
147
+ const findPreferredDmByUserId = async (id) => {
148
+ return findPreferredDmConversationByUserId(await list(), id);
149
+ };
150
+ const upsert = async (conversationId, reference) => {
151
+ const normalizedId = normalizeStoredConversationId(conversationId);
152
+ await withFileLock$1(filePath, empty, async () => {
153
+ const store = await readStore();
154
+ store.conversations[normalizedId] = mergeStoredConversationReference(store.conversations[normalizedId], reference, (/* @__PURE__ */ new Date()).toISOString());
155
+ const nowMs = Date.now();
156
+ store.conversations = pruneExpired$2(store.conversations, nowMs, ttlMs).conversations;
157
+ store.conversations = pruneToLimit$2(store.conversations);
158
+ await writeJsonFile(filePath, store);
159
+ });
160
+ };
161
+ const remove = async (conversationId) => {
162
+ const normalizedId = normalizeStoredConversationId(conversationId);
163
+ return await withFileLock$1(filePath, empty, async () => {
164
+ const store = await readStore();
165
+ if (!(normalizedId in store.conversations)) return false;
166
+ delete store.conversations[normalizedId];
167
+ await writeJsonFile(filePath, store);
168
+ return true;
169
+ });
170
+ };
171
+ return {
172
+ upsert,
173
+ get,
174
+ list,
175
+ remove,
176
+ findPreferredDmByUserId,
177
+ findByUserId: findPreferredDmByUserId
178
+ };
179
+ }
180
+ //#endregion
181
+ //#region extensions/msteams/src/polls.ts
182
+ const STORE_FILENAME$1 = "msteams-polls.json";
183
+ const MAX_POLLS = 1e3;
184
+ const POLL_TTL_MS = 720 * 60 * 60 * 1e3;
185
+ function isRecord(value) {
186
+ return typeof value === "object" && value !== null && !Array.isArray(value);
187
+ }
188
+ function normalizeOptionalString$1(value) {
189
+ if (typeof value !== "string") return;
190
+ const trimmed = value.trim();
191
+ return trimmed ? trimmed : void 0;
192
+ }
193
+ function normalizeChoiceValue(value) {
194
+ if (typeof value === "string") {
195
+ const trimmed = value.trim();
196
+ return trimmed ? trimmed : null;
197
+ }
198
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
199
+ return null;
200
+ }
201
+ function extractSelections(value) {
202
+ if (Array.isArray(value)) return value.map(normalizeChoiceValue).filter((entry) => Boolean(entry));
203
+ const normalized = normalizeChoiceValue(value);
204
+ if (!normalized) return [];
205
+ if (normalized.includes(",")) return normalized.split(",").map((entry) => entry.trim()).filter(Boolean);
206
+ return [normalized];
207
+ }
208
+ function readNestedValue(value, keys) {
209
+ let current = value;
210
+ for (const key of keys) {
211
+ if (!isRecord(current)) return;
212
+ current = current[key];
213
+ }
214
+ return current;
215
+ }
216
+ function readNestedString(value, keys) {
217
+ return normalizeOptionalString$1(readNestedValue(value, keys));
218
+ }
219
+ function extractMSTeamsPollVote(activity) {
220
+ const value = activity?.value;
221
+ if (!value || !isRecord(value)) return null;
222
+ const pollId = readNestedString(value, ["openclawPollId"]) ?? readNestedString(value, ["pollId"]) ?? readNestedString(value, ["openclaw", "pollId"]) ?? readNestedString(value, [
223
+ "openclaw",
224
+ "poll",
225
+ "id"
226
+ ]) ?? readNestedString(value, ["data", "openclawPollId"]) ?? readNestedString(value, ["data", "pollId"]) ?? readNestedString(value, [
227
+ "data",
228
+ "openclaw",
229
+ "pollId"
230
+ ]);
231
+ if (!pollId) return null;
232
+ const directSelections = extractSelections(value.choices);
233
+ const nestedSelections = extractSelections(readNestedValue(value, ["choices"]));
234
+ const dataSelections = extractSelections(readNestedValue(value, ["data", "choices"]));
235
+ const selections = directSelections.length > 0 ? directSelections : nestedSelections.length > 0 ? nestedSelections : dataSelections;
236
+ if (selections.length === 0) return null;
237
+ return {
238
+ pollId,
239
+ selections
240
+ };
241
+ }
242
+ function buildMSTeamsPollCard(params) {
243
+ const pollId = params.pollId ?? crypto.randomUUID();
244
+ const maxSelections = typeof params.maxSelections === "number" && params.maxSelections > 1 ? Math.floor(params.maxSelections) : 1;
245
+ const cappedMaxSelections = Math.min(Math.max(1, maxSelections), params.options.length);
246
+ const choices = params.options.map((option, index) => ({
247
+ title: option,
248
+ value: String(index)
249
+ }));
250
+ const hint = cappedMaxSelections > 1 ? `Select up to ${cappedMaxSelections} option${cappedMaxSelections === 1 ? "" : "s"}.` : "Select one option.";
251
+ const card = {
252
+ type: "AdaptiveCard",
253
+ version: "1.5",
254
+ body: [
255
+ {
256
+ type: "TextBlock",
257
+ text: params.question,
258
+ wrap: true,
259
+ weight: "Bolder",
260
+ size: "Medium"
261
+ },
262
+ {
263
+ type: "Input.ChoiceSet",
264
+ id: "choices",
265
+ isMultiSelect: cappedMaxSelections > 1,
266
+ style: "expanded",
267
+ choices
268
+ },
269
+ {
270
+ type: "TextBlock",
271
+ text: hint,
272
+ wrap: true,
273
+ isSubtle: true,
274
+ spacing: "Small"
275
+ }
276
+ ],
277
+ actions: [{
278
+ type: "Action.Submit",
279
+ title: "Vote",
280
+ data: {
281
+ openclawPollId: pollId,
282
+ pollId
283
+ },
284
+ msteams: {
285
+ type: "messageBack",
286
+ text: "openclaw poll vote",
287
+ displayText: "Vote recorded",
288
+ value: {
289
+ openclawPollId: pollId,
290
+ pollId
291
+ }
292
+ }
293
+ }]
294
+ };
295
+ const fallbackLines = [`Poll: ${params.question}`, ...params.options.map((option, index) => `${index + 1}. ${option}`)];
296
+ return {
297
+ pollId,
298
+ question: params.question,
299
+ options: params.options,
300
+ maxSelections: cappedMaxSelections,
301
+ card,
302
+ fallbackText: fallbackLines.join("\n")
303
+ };
304
+ }
305
+ function parseTimestamp(value) {
306
+ if (!value) return null;
307
+ const parsed = Date.parse(value);
308
+ return Number.isFinite(parsed) ? parsed : null;
309
+ }
310
+ function pruneExpired$1(polls) {
311
+ const cutoff = Date.now() - POLL_TTL_MS;
312
+ const entries = Object.entries(polls).filter(([, poll]) => {
313
+ return (parseTimestamp(poll.updatedAt ?? poll.createdAt) ?? 0) >= cutoff;
314
+ });
315
+ return Object.fromEntries(entries);
316
+ }
317
+ function pruneToLimit$1(polls) {
318
+ const entries = Object.entries(polls);
319
+ if (entries.length <= MAX_POLLS) return polls;
320
+ entries.sort((a, b) => {
321
+ return (parseTimestamp(a[1].updatedAt ?? a[1].createdAt) ?? 0) - (parseTimestamp(b[1].updatedAt ?? b[1].createdAt) ?? 0);
322
+ });
323
+ const keep = entries.slice(entries.length - MAX_POLLS);
324
+ return Object.fromEntries(keep);
325
+ }
326
+ function normalizeMSTeamsPollSelections(poll, selections) {
327
+ const maxSelections = Math.max(1, poll.maxSelections);
328
+ const mapped = selections.map((entry) => Number.parseInt(entry, 10)).filter((value) => Number.isFinite(value)).filter((value) => value >= 0 && value < poll.options.length).map((value) => String(value));
329
+ const limited = maxSelections > 1 ? mapped.slice(0, maxSelections) : mapped.slice(0, 1);
330
+ return Array.from(new Set(limited));
331
+ }
332
+ function createMSTeamsPollStoreFs(params) {
333
+ const filePath = resolveMSTeamsStorePath({
334
+ filename: STORE_FILENAME$1,
335
+ env: params?.env,
336
+ homedir: params?.homedir,
337
+ stateDir: params?.stateDir,
338
+ storePath: params?.storePath
339
+ });
340
+ const empty = {
341
+ version: 1,
342
+ polls: {}
343
+ };
344
+ const readStore = async () => {
345
+ const { value } = await readJsonFile(filePath, empty);
346
+ return {
347
+ version: 1,
348
+ polls: pruneToLimit$1(pruneExpired$1(value.polls ?? {}))
349
+ };
350
+ };
351
+ const writeStore = async (data) => {
352
+ await writeJsonFile(filePath, data);
353
+ };
354
+ const createPoll = async (poll) => {
355
+ await withFileLock$1(filePath, empty, async () => {
356
+ const data = await readStore();
357
+ data.polls[poll.id] = poll;
358
+ await writeStore({
359
+ version: 1,
360
+ polls: pruneToLimit$1(data.polls)
361
+ });
362
+ });
363
+ };
364
+ const getPoll = async (pollId) => await withFileLock$1(filePath, empty, async () => {
365
+ return (await readStore()).polls[pollId] ?? null;
366
+ });
367
+ const recordVote = async (params) => await withFileLock$1(filePath, empty, async () => {
368
+ const data = await readStore();
369
+ const poll = data.polls[params.pollId];
370
+ if (!poll) return null;
371
+ const normalized = normalizeMSTeamsPollSelections(poll, params.selections);
372
+ poll.votes[params.voterId] = normalized;
373
+ poll.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
374
+ data.polls[poll.id] = poll;
375
+ await writeStore({
376
+ version: 1,
377
+ polls: pruneToLimit$1(data.polls)
378
+ });
379
+ return poll;
380
+ });
381
+ return {
382
+ createPoll,
383
+ getPoll,
384
+ recordVote
385
+ };
386
+ }
387
+ //#endregion
388
+ //#region extensions/msteams/src/file-consent.ts
389
+ /**
390
+ * FileConsentCard utilities for MS Teams large file uploads (>4MB) in personal chats.
391
+ *
392
+ * Teams requires user consent before the bot can upload large files. This module provides
393
+ * utilities for:
394
+ * - Building FileConsentCard attachments (to request upload permission)
395
+ * - Building FileInfoCard attachments (to confirm upload completion)
396
+ * - Parsing fileConsent/invoke activities
397
+ */
398
+ function normalizeLowercaseStringOrEmpty$1(value) {
399
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
400
+ }
401
+ /**
402
+ * Allowlist of domains that are valid targets for file consent uploads.
403
+ * These are the Microsoft/SharePoint domains that Teams legitimately provides
404
+ * as upload destinations in the FileConsentCard flow.
405
+ */
406
+ const CONSENT_UPLOAD_HOST_ALLOWLIST = [
407
+ "sharepoint.com",
408
+ "sharepoint.us",
409
+ "sharepoint.de",
410
+ "sharepoint.cn",
411
+ "sharepoint-df.com",
412
+ "storage.live.com",
413
+ "onedrive.com",
414
+ "1drv.ms",
415
+ "graph.microsoft.com",
416
+ "graph.microsoft.us",
417
+ "graph.microsoft.de",
418
+ "graph.microsoft.cn"
419
+ ];
420
+ /**
421
+ * Returns true if the given IPv4 or IPv6 address is in a private, loopback,
422
+ * or link-local range that must never be reached via consent uploads.
423
+ */
424
+ function isPrivateOrReservedIP(ip) {
425
+ const ipv4MappedMatch = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip);
426
+ if (ipv4MappedMatch) return isPrivateOrReservedIP(ipv4MappedMatch[1]);
427
+ const v4Parts = ip.split(".");
428
+ if (v4Parts.length === 4) {
429
+ const octets = v4Parts.map(Number);
430
+ if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
431
+ const [a, b] = octets;
432
+ if (a === 10) return true;
433
+ if (a === 172 && b >= 16 && b <= 31) return true;
434
+ if (a === 192 && b === 168) return true;
435
+ if (a === 127) return true;
436
+ if (a === 169 && b === 254) return true;
437
+ if (a === 0) return true;
438
+ }
439
+ const normalized = normalizeLowercaseStringOrEmpty$1(ip);
440
+ if (normalized === "::1") return true;
441
+ if (normalized.startsWith("fe80:") || normalized.startsWith("fe80")) return true;
442
+ if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
443
+ if (normalized === "::") return true;
444
+ return false;
445
+ }
446
+ /**
447
+ * Validate that a consent upload URL is safe to PUT to.
448
+ * Checks:
449
+ * 1. Protocol is HTTPS
450
+ * 2. Hostname matches the consent upload allowlist
451
+ * 3. Resolved IP is not in a private/reserved range (anti-SSRF)
452
+ *
453
+ * @throws Error if the URL fails validation
454
+ */
455
+ async function validateConsentUploadUrl(url, opts) {
456
+ let parsed;
457
+ try {
458
+ parsed = new URL(url);
459
+ } catch {
460
+ throw new Error("Consent upload URL is not a valid URL");
461
+ }
462
+ if (parsed.protocol !== "https:") throw new Error(`Consent upload URL must use HTTPS, got ${parsed.protocol}`);
463
+ const hostname = normalizeLowercaseStringOrEmpty$1(parsed.hostname);
464
+ if (!(opts?.allowlist ?? CONSENT_UPLOAD_HOST_ALLOWLIST).some((entry) => hostname === entry || hostname.endsWith(`.${entry}`))) throw new Error(`Consent upload URL hostname "${hostname}" is not in the allowed domains`);
465
+ const resolveFn = opts?.resolveFn ?? ((name) => lookup(name, { all: true }));
466
+ let resolved;
467
+ try {
468
+ const result = await resolveFn(hostname);
469
+ resolved = Array.isArray(result) ? result : [result];
470
+ } catch {
471
+ throw new Error(`Failed to resolve consent upload URL hostname "${hostname}"`);
472
+ }
473
+ for (const entry of resolved) if (isPrivateOrReservedIP(entry.address)) throw new Error(`Consent upload URL resolves to a private/reserved IP (${entry.address})`);
474
+ }
475
+ /**
476
+ * Build a FileConsentCard attachment for requesting upload permission.
477
+ * Use this for files >= 4MB in personal (1:1) chats.
478
+ */
479
+ function buildFileConsentCard(params) {
480
+ return {
481
+ contentType: "application/vnd.microsoft.teams.card.file.consent",
482
+ name: params.filename,
483
+ content: {
484
+ description: params.description ?? `File: ${params.filename}`,
485
+ sizeInBytes: params.sizeInBytes,
486
+ acceptContext: {
487
+ filename: params.filename,
488
+ ...params.context
489
+ },
490
+ declineContext: {
491
+ filename: params.filename,
492
+ ...params.context
493
+ }
494
+ }
495
+ };
496
+ }
497
+ /**
498
+ * Build a FileInfoCard attachment for confirming upload completion.
499
+ * Send this after successfully uploading the file to the consent URL.
500
+ */
501
+ function buildFileInfoCard(params) {
502
+ return {
503
+ contentType: "application/vnd.microsoft.teams.card.file.info",
504
+ contentUrl: params.contentUrl,
505
+ name: params.filename,
506
+ content: {
507
+ uniqueId: params.uniqueId,
508
+ fileType: params.fileType
509
+ }
510
+ };
511
+ }
512
+ /**
513
+ * Parse a fileConsent/invoke activity.
514
+ * Returns null if the activity is not a file consent invoke.
515
+ */
516
+ function parseFileConsentInvoke(activity) {
517
+ if (activity.name !== "fileConsent/invoke") return null;
518
+ const value = activity.value;
519
+ if (value?.type !== "fileUpload") return null;
520
+ return {
521
+ action: value.action === "accept" ? "accept" : "decline",
522
+ uploadInfo: value.uploadInfo,
523
+ context: value.context
524
+ };
525
+ }
526
+ /**
527
+ * Upload a file to the consent URL provided by Teams.
528
+ * The URL is provided in the fileConsent/invoke response after user accepts.
529
+ *
530
+ * @throws Error if the URL fails SSRF validation (non-HTTPS, disallowed host, private IP)
531
+ */
532
+ async function uploadToConsentUrl(params) {
533
+ await validateConsentUploadUrl(params.url, params.validationOpts);
534
+ const res = await (params.fetchFn ?? fetch)(params.url, {
535
+ method: "PUT",
536
+ headers: {
537
+ "User-Agent": buildUserAgent(),
538
+ "Content-Type": params.contentType ?? "application/octet-stream",
539
+ "Content-Range": `bytes 0-${params.buffer.length - 1}/${params.buffer.length}`
540
+ },
541
+ body: new Uint8Array(params.buffer)
542
+ });
543
+ if (!res.ok) throw new Error(`File upload to consent URL failed: ${res.status} ${res.statusText}`);
544
+ }
545
+ //#endregion
546
+ //#region extensions/msteams/src/pending-uploads-fs.ts
547
+ /**
548
+ * Filesystem-backed pending upload store for the FileConsentCard flow.
549
+ *
550
+ * The CLI `message send --media` path runs in a different process from the
551
+ * gateway's bot monitor that receives the `fileConsent/invoke` callback.
552
+ * An in-memory `pending-uploads.ts` store cannot bridge those processes, so
553
+ * when the user clicks "Allow" the monitor handler's lookup misses and the
554
+ * user sees "card action not supported".
555
+ *
556
+ * This FS store persists pending uploads to a JSON file (with the file buffer
557
+ * base64-encoded) so any process that shares the OpenClaw state dir can read
558
+ * them back. The in-memory store in `pending-uploads.ts` is still the fast
559
+ * path for same-process flows (for example the messenger reply path); this FS
560
+ * store is a cross-process fallback.
561
+ */
562
+ /** TTL for persisted pending uploads (matches in-memory store). */
563
+ const PENDING_UPLOAD_TTL_MS$1 = 300 * 1e3;
564
+ /** Cap to avoid unbounded growth if a process crashes mid-flow. */
565
+ const MAX_PENDING_UPLOADS = 100;
566
+ const STORE_FILENAME = "msteams-pending-uploads.json";
567
+ const empty = {
568
+ version: 1,
569
+ uploads: {}
570
+ };
571
+ function resolveFilePath(options) {
572
+ return resolveMSTeamsStorePath({
573
+ filename: STORE_FILENAME,
574
+ env: options?.env,
575
+ homedir: options?.homedir,
576
+ stateDir: options?.stateDir,
577
+ storePath: options?.storePath
578
+ });
579
+ }
580
+ function pruneExpired(uploads, nowMs, ttlMs) {
581
+ const kept = {};
582
+ for (const [id, record] of Object.entries(uploads)) if (nowMs - record.createdAt <= ttlMs) kept[id] = record;
583
+ return kept;
584
+ }
585
+ function pruneToLimit(uploads) {
586
+ const entries = Object.entries(uploads);
587
+ if (entries.length <= MAX_PENDING_UPLOADS) return uploads;
588
+ entries.sort((a, b) => a[1].createdAt - b[1].createdAt);
589
+ const keep = entries.slice(entries.length - MAX_PENDING_UPLOADS);
590
+ return Object.fromEntries(keep);
591
+ }
592
+ function recordToUpload(record) {
593
+ return {
594
+ id: record.id,
595
+ buffer: Buffer.from(record.bufferBase64, "base64"),
596
+ filename: record.filename,
597
+ contentType: record.contentType,
598
+ conversationId: record.conversationId,
599
+ consentCardActivityId: record.consentCardActivityId,
600
+ createdAt: record.createdAt
601
+ };
602
+ }
603
+ function isValidStore(value) {
604
+ if (!value || typeof value !== "object") return false;
605
+ const candidate = value;
606
+ return candidate.version === 1 && typeof candidate.uploads === "object" && candidate.uploads !== null && !Array.isArray(candidate.uploads);
607
+ }
608
+ async function readStore(filePath, ttlMs) {
609
+ const { value } = await readJsonFile(filePath, empty);
610
+ if (!isValidStore(value)) return {
611
+ version: 1,
612
+ uploads: {}
613
+ };
614
+ return {
615
+ version: 1,
616
+ uploads: pruneToLimit(pruneExpired(value.uploads, Date.now(), ttlMs))
617
+ };
618
+ }
619
+ /**
620
+ * Persist a pending upload record so another process can read it back.
621
+ * Pass in the pre-generated id (same as the one placed in the consent card
622
+ * context) so the in-memory and FS stores share the same key.
623
+ */
624
+ async function storePendingUploadFs(upload, options) {
625
+ const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS$1;
626
+ const filePath = resolveFilePath(options);
627
+ await withFileLock$1(filePath, empty, async () => {
628
+ const store = await readStore(filePath, ttlMs);
629
+ store.uploads[upload.id] = {
630
+ id: upload.id,
631
+ bufferBase64: upload.buffer.toString("base64"),
632
+ filename: upload.filename,
633
+ contentType: upload.contentType,
634
+ conversationId: upload.conversationId,
635
+ consentCardActivityId: upload.consentCardActivityId,
636
+ createdAt: Date.now()
637
+ };
638
+ store.uploads = pruneToLimit(pruneExpired(store.uploads, Date.now(), ttlMs));
639
+ await writeJsonFile(filePath, store);
640
+ });
641
+ }
642
+ /**
643
+ * Retrieve a persisted pending upload. Expired entries are treated as absent.
644
+ */
645
+ async function getPendingUploadFs(id, options) {
646
+ if (!id) return;
647
+ const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS$1;
648
+ const record = (await readStore(resolveFilePath(options), ttlMs)).uploads[id];
649
+ if (!record) return;
650
+ if (Date.now() - record.createdAt > ttlMs) return;
651
+ return recordToUpload(record);
652
+ }
653
+ /**
654
+ * Remove a persisted pending upload (after successful upload or decline).
655
+ * No-op if the entry is already gone.
656
+ */
657
+ async function removePendingUploadFs(id, options) {
658
+ if (!id) return;
659
+ const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS$1;
660
+ const filePath = resolveFilePath(options);
661
+ await withFileLock$1(filePath, empty, async () => {
662
+ const store = await readStore(filePath, ttlMs);
663
+ if (!(id in store.uploads)) return;
664
+ delete store.uploads[id];
665
+ await writeJsonFile(filePath, store);
666
+ });
667
+ }
668
+ /**
669
+ * Set the consent card activity ID on a persisted entry. Called after the
670
+ * FileConsentCard activity is sent and we know its message id.
671
+ */
672
+ async function setPendingUploadActivityIdFs(id, activityId, options) {
673
+ const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS$1;
674
+ const filePath = resolveFilePath(options);
675
+ await withFileLock$1(filePath, empty, async () => {
676
+ const store = await readStore(filePath, ttlMs);
677
+ const record = store.uploads[id];
678
+ if (!record) return;
679
+ record.consentCardActivityId = activityId;
680
+ await writeJsonFile(filePath, store);
681
+ });
682
+ }
683
+ //#endregion
684
+ //#region extensions/msteams/src/pending-uploads.ts
685
+ /**
686
+ * In-memory storage for files awaiting user consent in the FileConsentCard flow.
687
+ *
688
+ * When sending large files (>=4MB) in personal chats, Teams requires user consent
689
+ * before upload. This module stores the file data temporarily until the user
690
+ * accepts or declines, or until the TTL expires.
691
+ */
692
+ const pendingUploads = /* @__PURE__ */ new Map();
693
+ /** Timer handles keyed by upload ID, cleared on explicit removal to prevent ghost cleanup */
694
+ const pendingUploadTimers = /* @__PURE__ */ new Map();
695
+ /** TTL for pending uploads: 5 minutes */
696
+ const PENDING_UPLOAD_TTL_MS = 300 * 1e3;
697
+ /**
698
+ * Store a file pending user consent.
699
+ * Returns the upload ID to include in the FileConsentCard context.
700
+ */
701
+ function storePendingUpload(upload) {
702
+ const id = crypto.randomUUID();
703
+ const entry = {
704
+ ...upload,
705
+ id,
706
+ createdAt: Date.now()
707
+ };
708
+ pendingUploads.set(id, entry);
709
+ const timer = setTimeout(() => {
710
+ pendingUploads.delete(id);
711
+ pendingUploadTimers.delete(id);
712
+ }, PENDING_UPLOAD_TTL_MS);
713
+ pendingUploadTimers.set(id, timer);
714
+ return id;
715
+ }
716
+ /**
717
+ * Retrieve a pending upload by ID.
718
+ * Returns undefined if not found or expired.
719
+ */
720
+ function getPendingUpload(id) {
721
+ if (!id) return;
722
+ const entry = pendingUploads.get(id);
723
+ if (!entry) return;
724
+ if (Date.now() - entry.createdAt > PENDING_UPLOAD_TTL_MS) {
725
+ pendingUploads.delete(id);
726
+ const timer = pendingUploadTimers.get(id);
727
+ if (timer !== void 0) {
728
+ clearTimeout(timer);
729
+ pendingUploadTimers.delete(id);
730
+ }
731
+ return;
732
+ }
733
+ return entry;
734
+ }
735
+ /**
736
+ * Remove a pending upload (after successful upload or user decline).
737
+ * Also clears the TTL timer to prevent ghost Map deletions.
738
+ */
739
+ function removePendingUpload(id) {
740
+ if (id) {
741
+ pendingUploads.delete(id);
742
+ const timer = pendingUploadTimers.get(id);
743
+ if (timer !== void 0) {
744
+ clearTimeout(timer);
745
+ pendingUploadTimers.delete(id);
746
+ }
747
+ }
748
+ }
749
+ /**
750
+ * Set the consent card activity ID on an existing pending upload.
751
+ * Called after the FileConsentCard is sent and we know its activity ID.
752
+ */
753
+ function setPendingUploadActivityId(uploadId, activityId) {
754
+ const entry = pendingUploads.get(uploadId);
755
+ if (entry) entry.consentCardActivityId = activityId;
756
+ }
757
+ //#endregion
758
+ //#region extensions/msteams/src/file-consent-helpers.ts
759
+ /**
760
+ * Shared helpers for FileConsentCard flow in MSTeams.
761
+ *
762
+ * FileConsentCard is required for:
763
+ * - Personal (1:1) chats with large files (>=4MB)
764
+ * - Personal chats with non-image files (PDFs, documents, etc.)
765
+ *
766
+ * This module consolidates the logic used by both send.ts (proactive sends)
767
+ * and messenger.ts (reply path) to avoid duplication.
768
+ */
769
+ function buildConsentActivity(params) {
770
+ const { media, description, uploadId } = params;
771
+ return {
772
+ type: "message",
773
+ attachments: [buildFileConsentCard({
774
+ filename: media.filename,
775
+ description: description || `File: ${media.filename}`,
776
+ sizeInBytes: media.buffer.length,
777
+ context: { uploadId }
778
+ })]
779
+ };
780
+ }
781
+ /**
782
+ * Prepare a FileConsentCard activity for large files or non-images in personal chats.
783
+ * Returns the activity object and uploadId - caller is responsible for sending.
784
+ *
785
+ * This variant only writes to the in-memory store. Use it when the caller and
786
+ * the `fileConsent/invoke` handler share the same process (for example the
787
+ * messenger reply path). For proactive CLI sends where the invoke arrives in
788
+ * a different process, use {@link prepareFileConsentActivityFs} instead.
789
+ */
790
+ function prepareFileConsentActivity(params) {
791
+ const { media, conversationId, description } = params;
792
+ const uploadId = storePendingUpload({
793
+ buffer: media.buffer,
794
+ filename: media.filename,
795
+ contentType: media.contentType,
796
+ conversationId
797
+ });
798
+ return {
799
+ activity: buildConsentActivity({
800
+ media,
801
+ description,
802
+ uploadId
803
+ }),
804
+ uploadId
805
+ };
806
+ }
807
+ /**
808
+ * Prepare a FileConsentCard activity and persist the pending upload to the
809
+ * filesystem so a different process can read it when the user accepts.
810
+ *
811
+ * This is used by the proactive CLI `message send --media` path: the CLI
812
+ * process sends the card and exits, but the `fileConsent/invoke` callback is
813
+ * delivered to the long-lived gateway monitor process. The FS-backed store
814
+ * bridges those two processes. The in-memory store is also populated so
815
+ * same-process flows keep the fast path.
816
+ */
817
+ async function prepareFileConsentActivityFs(params) {
818
+ const { media, conversationId, description } = params;
819
+ const uploadId = storePendingUpload({
820
+ buffer: media.buffer,
821
+ filename: media.filename,
822
+ contentType: media.contentType,
823
+ conversationId
824
+ });
825
+ await storePendingUploadFs({
826
+ id: uploadId,
827
+ buffer: media.buffer,
828
+ filename: media.filename,
829
+ contentType: media.contentType,
830
+ conversationId
831
+ });
832
+ return {
833
+ activity: buildConsentActivity({
834
+ media,
835
+ description,
836
+ uploadId
837
+ }),
838
+ uploadId
839
+ };
840
+ }
841
+ /**
842
+ * Check if a file requires FileConsentCard flow.
843
+ * True for: personal chat AND (large file OR non-image)
844
+ */
845
+ function requiresFileConsent(params) {
846
+ const isPersonal = normalizeOptionalLowercaseString(params.conversationType) === "personal";
847
+ const isImage = params.contentType?.startsWith("image/") ?? false;
848
+ const isLargeFile = params.bufferSize >= params.thresholdBytes;
849
+ return isPersonal && (isLargeFile || !isImage);
850
+ }
851
+ //#endregion
852
+ //#region extensions/msteams/src/graph-chat.ts
853
+ /**
854
+ * Native Teams file card attachments for Bot Framework.
855
+ *
856
+ * The Bot Framework SDK supports `application/vnd.microsoft.teams.card.file.info`
857
+ * content type which produces native Teams file cards.
858
+ *
859
+ * @see https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/bots-filesv4
860
+ */
861
+ /**
862
+ * Build a native Teams file card attachment for Bot Framework.
863
+ *
864
+ * This uses the `application/vnd.microsoft.teams.card.file.info` content type
865
+ * which is supported by Bot Framework and produces native Teams file cards
866
+ * (the same display as when a user manually shares a file).
867
+ *
868
+ * @param file - DriveItem properties from getDriveItemProperties()
869
+ * @returns Attachment object for Bot Framework sendActivity()
870
+ */
871
+ function buildTeamsFileInfoCard(file) {
872
+ const rawETag = file.eTag;
873
+ const uniqueId = rawETag.replace(/^["']|["']$/g, "").replace(/[{}]/g, "").split(",")[0] ?? rawETag;
874
+ const lastDot = file.name.lastIndexOf(".");
875
+ const fileType = lastDot >= 0 ? normalizeLowercaseStringOrEmpty(file.name.slice(lastDot + 1)) : "";
876
+ return {
877
+ contentType: "application/vnd.microsoft.teams.card.file.info",
878
+ contentUrl: file.webDavUrl,
879
+ name: file.name,
880
+ content: {
881
+ uniqueId,
882
+ fileType
883
+ }
884
+ };
885
+ }
886
+ //#endregion
887
+ //#region extensions/msteams/src/graph-upload.ts
888
+ const GRAPH_ROOT = "https://graph.microsoft.com/v1.0";
889
+ const GRAPH_BETA = "https://graph.microsoft.com/beta";
890
+ const GRAPH_SCOPE = "https://graph.microsoft.com";
891
+ /**
892
+ * Upload a file to the user's OneDrive root folder.
893
+ * For larger files, this uses the simple upload endpoint (up to 4MB).
894
+ */
895
+ async function uploadToOneDrive(params) {
896
+ const fetchFn = params.fetchFn ?? fetch;
897
+ const token = await params.tokenProvider.getAccessToken(GRAPH_SCOPE);
898
+ const res = await fetchFn(`${GRAPH_ROOT}/me/drive/root:${`/OpenClawShared/${encodeURIComponent(params.filename)}`}:/content`, {
899
+ method: "PUT",
900
+ headers: {
901
+ "User-Agent": buildUserAgent(),
902
+ Authorization: `Bearer ${token}`,
903
+ "Content-Type": params.contentType ?? "application/octet-stream"
904
+ },
905
+ body: new Uint8Array(params.buffer)
906
+ });
907
+ if (!res.ok) {
908
+ const body = await res.text().catch(() => "");
909
+ throw new Error(`OneDrive upload failed: ${res.status} ${res.statusText} - ${body}`);
910
+ }
911
+ const data = await res.json();
912
+ if (!data.id || !data.webUrl || !data.name) throw new Error("OneDrive upload response missing required fields");
913
+ return {
914
+ id: data.id,
915
+ webUrl: data.webUrl,
916
+ name: data.name
917
+ };
918
+ }
919
+ /**
920
+ * Create a sharing link for a OneDrive file.
921
+ * The link allows organization members to view the file.
922
+ */
923
+ async function createSharingLink(params) {
924
+ const fetchFn = params.fetchFn ?? fetch;
925
+ const token = await params.tokenProvider.getAccessToken(GRAPH_SCOPE);
926
+ const res = await fetchFn(`${GRAPH_ROOT}/me/drive/items/${params.itemId}/createLink`, {
927
+ method: "POST",
928
+ headers: {
929
+ "User-Agent": buildUserAgent(),
930
+ Authorization: `Bearer ${token}`,
931
+ "Content-Type": "application/json"
932
+ },
933
+ body: JSON.stringify({
934
+ type: "view",
935
+ scope: params.scope ?? "organization"
936
+ })
937
+ });
938
+ if (!res.ok) {
939
+ const body = await res.text().catch(() => "");
940
+ throw new Error(`Create sharing link failed: ${res.status} ${res.statusText} - ${body}`);
941
+ }
942
+ const data = await res.json();
943
+ if (!data.link?.webUrl) throw new Error("Create sharing link response missing webUrl");
944
+ return { webUrl: data.link.webUrl };
945
+ }
946
+ /**
947
+ * Upload a file to OneDrive and create a sharing link.
948
+ * Convenience function for the common case.
949
+ */
950
+ async function uploadAndShareOneDrive(params) {
951
+ const uploaded = await uploadToOneDrive({
952
+ buffer: params.buffer,
953
+ filename: params.filename,
954
+ contentType: params.contentType,
955
+ tokenProvider: params.tokenProvider,
956
+ fetchFn: params.fetchFn
957
+ });
958
+ const shareLink = await createSharingLink({
959
+ itemId: uploaded.id,
960
+ tokenProvider: params.tokenProvider,
961
+ scope: params.scope,
962
+ fetchFn: params.fetchFn
963
+ });
964
+ return {
965
+ itemId: uploaded.id,
966
+ webUrl: uploaded.webUrl,
967
+ shareUrl: shareLink.webUrl,
968
+ name: uploaded.name
969
+ };
970
+ }
971
+ /**
972
+ * Upload a file to a SharePoint site.
973
+ * This is used for group chats and channels where /me/drive doesn't work for bots.
974
+ *
975
+ * @param params.siteId - SharePoint site ID (e.g., "contoso.sharepoint.com,guid1,guid2")
976
+ */
977
+ async function uploadToSharePoint(params) {
978
+ const fetchFn = params.fetchFn ?? fetch;
979
+ const token = await params.tokenProvider.getAccessToken(GRAPH_SCOPE);
980
+ const uploadPath = `/OpenClawShared/${encodeURIComponent(params.filename)}`;
981
+ const res = await fetchFn(`${GRAPH_ROOT}/sites/${params.siteId}/drive/root:${uploadPath}:/content`, {
982
+ method: "PUT",
983
+ headers: {
984
+ "User-Agent": buildUserAgent(),
985
+ Authorization: `Bearer ${token}`,
986
+ "Content-Type": params.contentType ?? "application/octet-stream"
987
+ },
988
+ body: new Uint8Array(params.buffer)
989
+ });
990
+ if (!res.ok) {
991
+ const body = await res.text().catch(() => "");
992
+ throw new Error(`SharePoint upload failed: ${res.status} ${res.statusText} - ${body}`);
993
+ }
994
+ const data = await res.json();
995
+ if (!data.id || !data.webUrl || !data.name) throw new Error("SharePoint upload response missing required fields");
996
+ return {
997
+ id: data.id,
998
+ webUrl: data.webUrl,
999
+ name: data.name
1000
+ };
1001
+ }
1002
+ /**
1003
+ * Get driveItem properties needed for native Teams file card attachments.
1004
+ * This fetches the eTag and webDavUrl which are required for "reference" type attachments.
1005
+ *
1006
+ * @param params.siteId - SharePoint site ID
1007
+ * @param params.itemId - The driveItem ID (returned from upload)
1008
+ */
1009
+ async function getDriveItemProperties(params) {
1010
+ const fetchFn = params.fetchFn ?? fetch;
1011
+ const token = await params.tokenProvider.getAccessToken(GRAPH_SCOPE);
1012
+ const res = await fetchFn(`${GRAPH_ROOT}/sites/${params.siteId}/drive/items/${params.itemId}?$select=eTag,webDavUrl,name`, { headers: {
1013
+ "User-Agent": buildUserAgent(),
1014
+ Authorization: `Bearer ${token}`
1015
+ } });
1016
+ if (!res.ok) {
1017
+ const body = await res.text().catch(() => "");
1018
+ throw new Error(`Get driveItem properties failed: ${res.status} ${res.statusText} - ${body}`);
1019
+ }
1020
+ const data = await res.json();
1021
+ if (!data.eTag || !data.webDavUrl || !data.name) throw new Error("DriveItem response missing required properties (eTag, webDavUrl, or name)");
1022
+ return {
1023
+ eTag: data.eTag,
1024
+ webDavUrl: data.webDavUrl,
1025
+ name: data.name
1026
+ };
1027
+ }
1028
+ /**
1029
+ * Resolve the Graph API-native chat ID from a Bot Framework conversation ID.
1030
+ *
1031
+ * Bot Framework personal DM conversation IDs use formats like `a:1xxx@unq.gbl.spaces`
1032
+ * or `8:orgid:xxx` that the Graph API does not accept. Graph API requires the
1033
+ * `19:xxx@thread.tacv2` or `19:xxx@unq.gbl.spaces` format.
1034
+ *
1035
+ * This function looks up the matching Graph chat by querying the bot's chats filtered
1036
+ * by the target user's AAD object ID.
1037
+ */
1038
+ async function resolveGraphChatId(params) {
1039
+ const { botFrameworkConversationId, userAadObjectId, tokenProvider } = params;
1040
+ const fetchFn = params.fetchFn ?? fetch;
1041
+ if (botFrameworkConversationId.startsWith("19:")) return botFrameworkConversationId;
1042
+ const token = await tokenProvider.getAccessToken(GRAPH_SCOPE);
1043
+ let path;
1044
+ if (userAadObjectId) path = `/me/chats?$filter=${encodeURIComponent(`chatType eq 'oneOnOne' and members/any(m:m/microsoft.graph.aadUserConversationMember/userId eq '${userAadObjectId}')`)}&$select=id`;
1045
+ else path = `/me/chats?$filter=${encodeURIComponent("chatType eq 'oneOnOne'")}&$select=id`;
1046
+ const res = await fetchFn(`${GRAPH_ROOT}${path}`, { headers: {
1047
+ "User-Agent": buildUserAgent(),
1048
+ Authorization: `Bearer ${token}`
1049
+ } });
1050
+ if (!res.ok) return null;
1051
+ const chats = (await res.json()).value ?? [];
1052
+ if (userAadObjectId && chats.length > 0 && chats[0]?.id) return chats[0].id;
1053
+ if (!userAadObjectId && chats.length === 1 && chats[0]?.id) return chats[0].id;
1054
+ return null;
1055
+ }
1056
+ /**
1057
+ * Get members of a Teams chat for per-user sharing.
1058
+ * Used to create sharing links scoped to only the chat participants.
1059
+ */
1060
+ async function getChatMembers(params) {
1061
+ const fetchFn = params.fetchFn ?? fetch;
1062
+ const token = await params.tokenProvider.getAccessToken(GRAPH_SCOPE);
1063
+ const res = await fetchFn(`${GRAPH_ROOT}/chats/${params.chatId}/members`, { headers: {
1064
+ "User-Agent": buildUserAgent(),
1065
+ Authorization: `Bearer ${token}`
1066
+ } });
1067
+ if (!res.ok) {
1068
+ const body = await res.text().catch(() => "");
1069
+ throw new Error(`Get chat members failed: ${res.status} ${res.statusText} - ${body}`);
1070
+ }
1071
+ return ((await res.json()).value ?? []).map((m) => ({
1072
+ aadObjectId: m.userId ?? "",
1073
+ displayName: m.displayName
1074
+ })).filter((m) => m.aadObjectId);
1075
+ }
1076
+ /**
1077
+ * Create a sharing link for a SharePoint drive item.
1078
+ * For organization scope (default), uses v1.0 API.
1079
+ * For per-user scope, uses beta API with recipients.
1080
+ */
1081
+ async function createSharePointSharingLink(params) {
1082
+ const fetchFn = params.fetchFn ?? fetch;
1083
+ const token = await params.tokenProvider.getAccessToken(GRAPH_SCOPE);
1084
+ const scope = params.scope ?? "organization";
1085
+ const apiRoot = scope === "users" ? GRAPH_BETA : GRAPH_ROOT;
1086
+ const body = {
1087
+ type: "view",
1088
+ scope: scope === "users" ? "users" : "organization"
1089
+ };
1090
+ if (scope === "users" && params.recipientObjectIds?.length) body.recipients = params.recipientObjectIds.map((id) => ({ objectId: id }));
1091
+ const res = await fetchFn(`${apiRoot}/sites/${params.siteId}/drive/items/${params.itemId}/createLink`, {
1092
+ method: "POST",
1093
+ headers: {
1094
+ "User-Agent": buildUserAgent(),
1095
+ Authorization: `Bearer ${token}`,
1096
+ "Content-Type": "application/json"
1097
+ },
1098
+ body: JSON.stringify(body)
1099
+ });
1100
+ if (!res.ok) {
1101
+ const respBody = await res.text().catch(() => "");
1102
+ throw new Error(`Create SharePoint sharing link failed: ${res.status} ${res.statusText} - ${respBody}`);
1103
+ }
1104
+ const data = await res.json();
1105
+ if (!data.link?.webUrl) throw new Error("Create SharePoint sharing link response missing webUrl");
1106
+ return { webUrl: data.link.webUrl };
1107
+ }
1108
+ /**
1109
+ * Upload a file to SharePoint and create a sharing link.
1110
+ *
1111
+ * For group chats, this creates a per-user sharing link scoped to chat members.
1112
+ * For channels, this creates an organization-wide sharing link.
1113
+ *
1114
+ * @param params.siteId - SharePoint site ID
1115
+ * @param params.chatId - Optional chat ID for per-user sharing (group chats)
1116
+ * @param params.usePerUserSharing - Whether to use per-user sharing (requires beta API + Chat.Read.All)
1117
+ */
1118
+ async function uploadAndShareSharePoint(params) {
1119
+ const uploaded = await uploadToSharePoint({
1120
+ buffer: params.buffer,
1121
+ filename: params.filename,
1122
+ contentType: params.contentType,
1123
+ tokenProvider: params.tokenProvider,
1124
+ siteId: params.siteId,
1125
+ fetchFn: params.fetchFn
1126
+ });
1127
+ let scope = "organization";
1128
+ let recipientObjectIds;
1129
+ if (params.usePerUserSharing && params.chatId) try {
1130
+ const members = await getChatMembers({
1131
+ chatId: params.chatId,
1132
+ tokenProvider: params.tokenProvider,
1133
+ fetchFn: params.fetchFn
1134
+ });
1135
+ if (members.length > 0) {
1136
+ scope = "users";
1137
+ recipientObjectIds = members.map((m) => m.aadObjectId);
1138
+ }
1139
+ } catch {}
1140
+ const shareLink = await createSharePointSharingLink({
1141
+ siteId: params.siteId,
1142
+ itemId: uploaded.id,
1143
+ tokenProvider: params.tokenProvider,
1144
+ scope,
1145
+ recipientObjectIds,
1146
+ fetchFn: params.fetchFn
1147
+ });
1148
+ return {
1149
+ itemId: uploaded.id,
1150
+ webUrl: uploaded.webUrl,
1151
+ shareUrl: shareLink.webUrl,
1152
+ name: uploaded.name
1153
+ };
1154
+ }
1155
+ //#endregion
1156
+ //#region extensions/msteams/src/media-helpers.ts
1157
+ /**
1158
+ * MIME type detection and filename extraction for MSTeams media attachments.
1159
+ */
1160
+ /**
1161
+ * Detect MIME type from URL extension or data URL.
1162
+ * Uses shared MIME detection for consistency with core handling.
1163
+ */
1164
+ async function getMimeType(url) {
1165
+ if (url.startsWith("data:")) {
1166
+ const match = url.match(/^data:([^;,]+)/);
1167
+ if (match?.[1]) return match[1];
1168
+ }
1169
+ return await detectMime({ filePath: url }) ?? "application/octet-stream";
1170
+ }
1171
+ /**
1172
+ * Extract filename from URL or local path.
1173
+ * For local paths, extracts original filename if stored with embedded name pattern.
1174
+ * Falls back to deriving the extension from MIME type when no extension present.
1175
+ */
1176
+ async function extractFilename(url) {
1177
+ if (url.startsWith("data:")) {
1178
+ const mime = await getMimeType(url);
1179
+ const ext = extensionForMime(mime) ?? ".bin";
1180
+ return `${mime.startsWith("image/") ? "image" : "file"}${ext}`;
1181
+ }
1182
+ try {
1183
+ const pathname = new URL(url).pathname;
1184
+ const basename = path.basename(pathname);
1185
+ const existingExt = getFileExtension(pathname);
1186
+ if (basename && existingExt) return basename;
1187
+ const mime = await getMimeType(url);
1188
+ const ext = extensionForMime(mime) ?? ".bin";
1189
+ const prefix = mime.startsWith("image/") ? "image" : "file";
1190
+ return basename ? `${basename}${ext}` : `${prefix}${ext}`;
1191
+ } catch {
1192
+ return extractOriginalFilename(url);
1193
+ }
1194
+ }
1195
+ /**
1196
+ * Check if a URL refers to a local file path.
1197
+ */
1198
+ function isLocalPath(url) {
1199
+ if (url.startsWith("file://") || url.startsWith("/") || url.startsWith("~")) return true;
1200
+ if (url.startsWith("\\") && !url.startsWith("\\\\")) return true;
1201
+ if (/^[a-zA-Z]:[\\/]/.test(url)) return true;
1202
+ if (url.startsWith("\\\\")) return true;
1203
+ return false;
1204
+ }
1205
+ /**
1206
+ * Extract the message ID from a Bot Framework response.
1207
+ */
1208
+ function extractMessageId(response) {
1209
+ if (!response || typeof response !== "object") return null;
1210
+ if (!("id" in response)) return null;
1211
+ const { id } = response;
1212
+ if (typeof id !== "string" || !id) return null;
1213
+ return id;
1214
+ }
1215
+ //#endregion
1216
+ //#region extensions/msteams/src/mentions.ts
1217
+ /**
1218
+ * Check whether an ID looks like a valid Teams user/bot identifier.
1219
+ * Accepts:
1220
+ * - Bot Framework IDs: "28:xxx..." / "29:xxx..." / "8:orgid:..."
1221
+ * - AAD object IDs (UUIDs): "d5318c29-33ac-4e6b-bd42-57b8b793908f"
1222
+ *
1223
+ * Keep this permissive enough for real Teams IDs while still rejecting
1224
+ * documentation placeholders like `@[表示名](ユーザーID)`.
1225
+ */
1226
+ const TEAMS_BOT_ID_PATTERN = /^\d+:[a-z0-9._=-]+(?::[a-z0-9._=-]+)*$/i;
1227
+ const AAD_OBJECT_ID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
1228
+ function isValidTeamsId(id) {
1229
+ return TEAMS_BOT_ID_PATTERN.test(id) || AAD_OBJECT_ID_PATTERN.test(id);
1230
+ }
1231
+ /**
1232
+ * Parse mentions from text in the format @[Name](id).
1233
+ * Example: "Hello @[John Doe](28:xxx-yyy-zzz)!"
1234
+ *
1235
+ * Only matches where the id looks like a real Teams user/bot ID are treated
1236
+ * as mentions. This avoids false positives from documentation or code samples
1237
+ * embedded in the message (e.g. `@[表示名](ユーザーID)` in backticks).
1238
+ *
1239
+ * Returns both the formatted text with <at> tags and the entities array.
1240
+ */
1241
+ function parseMentions(text) {
1242
+ const mentionPattern = /@\[([^\]]+)\]\(([^)]+)\)/g;
1243
+ const entities = [];
1244
+ return {
1245
+ text: text.replace(mentionPattern, (match, name, id) => {
1246
+ const trimmedId = id.trim();
1247
+ if (!isValidTeamsId(trimmedId)) return match;
1248
+ const trimmedName = name.trim();
1249
+ const mentionTag = `<at>${trimmedName}</at>`;
1250
+ entities.push({
1251
+ type: "mention",
1252
+ text: mentionTag,
1253
+ mentioned: {
1254
+ id: trimmedId,
1255
+ name: trimmedName
1256
+ }
1257
+ });
1258
+ return mentionTag;
1259
+ }),
1260
+ entities
1261
+ };
1262
+ }
1263
+ //#endregion
1264
+ //#region extensions/msteams/src/revoked-context.ts
1265
+ async function withRevokedProxyFallback(params) {
1266
+ try {
1267
+ return await params.run();
1268
+ } catch (err) {
1269
+ if (!isRevokedProxyError(err)) throw err;
1270
+ params.onRevokedLog?.();
1271
+ return await params.onRevoked();
1272
+ }
1273
+ }
1274
+ //#endregion
1275
+ //#region extensions/msteams/src/ai-entity.ts
1276
+ /** AI-generated content entity added to every outbound AI message. */
1277
+ const AI_GENERATED_ENTITY = {
1278
+ type: "https://schema.org/Message",
1279
+ "@type": "Message",
1280
+ "@id": "",
1281
+ additionalType: ["AIGeneratedContent"]
1282
+ };
1283
+ //#endregion
1284
+ //#region extensions/msteams/src/messenger.ts
1285
+ /**
1286
+ * MSTeams-specific media size limit (100MB).
1287
+ * Higher than the default because OneDrive upload handles large files well.
1288
+ */
1289
+ const MSTEAMS_MAX_MEDIA_BYTES$1 = 100 * 1024 * 1024;
1290
+ /**
1291
+ * Threshold for large files that require FileConsentCard flow in personal chats.
1292
+ * Files >= 4MB use consent flow; smaller images can use inline base64.
1293
+ */
1294
+ const FILE_CONSENT_THRESHOLD_BYTES$1 = 4 * 1024 * 1024;
1295
+ function normalizeConversationId(rawId) {
1296
+ return rawId.split(";")[0] ?? rawId;
1297
+ }
1298
+ function buildConversationReference(ref) {
1299
+ const conversationId = ref.conversation?.id?.trim();
1300
+ if (!conversationId) throw new Error("Invalid stored reference: missing conversation.id");
1301
+ const agent = ref.agent ?? ref.bot ?? void 0;
1302
+ if (agent == null || !agent.id) throw new Error("Invalid stored reference: missing agent.id");
1303
+ const user = ref.user;
1304
+ if (!user?.id) throw new Error("Invalid stored reference: missing user.id");
1305
+ const tenantId = ref.tenantId ?? ref.conversation?.tenantId;
1306
+ const aadObjectId = ref.aadObjectId ?? user.aadObjectId;
1307
+ return {
1308
+ activityId: ref.activityId,
1309
+ user: aadObjectId ? {
1310
+ ...user,
1311
+ aadObjectId
1312
+ } : user,
1313
+ agent,
1314
+ conversation: {
1315
+ id: normalizeConversationId(conversationId),
1316
+ conversationType: ref.conversation?.conversationType,
1317
+ tenantId
1318
+ },
1319
+ channelId: ref.channelId ?? "msteams",
1320
+ serviceUrl: ref.serviceUrl,
1321
+ locale: ref.locale,
1322
+ ...tenantId ? { tenantId } : {},
1323
+ ...aadObjectId ? { aadObjectId } : {}
1324
+ };
1325
+ }
1326
+ function pushTextMessages(out, text, opts) {
1327
+ if (!text) return;
1328
+ if (opts.chunkText) {
1329
+ for (const chunk of getMSTeamsRuntime().channel.text.chunkMarkdownTextWithMode(text, opts.chunkLimit, opts.chunkMode)) {
1330
+ const trimmed = chunk.trim();
1331
+ if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) continue;
1332
+ out.push({ text: trimmed });
1333
+ }
1334
+ return;
1335
+ }
1336
+ const trimmed = text.trim();
1337
+ if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) return;
1338
+ out.push({ text: trimmed });
1339
+ }
1340
+ function clampMs(value, maxMs) {
1341
+ if (!Number.isFinite(value) || value < 0) return 0;
1342
+ return Math.min(value, maxMs);
1343
+ }
1344
+ function resolveRetryOptions(retry) {
1345
+ if (!retry) return {
1346
+ enabled: false,
1347
+ maxAttempts: 1,
1348
+ baseDelayMs: 0,
1349
+ maxDelayMs: 0
1350
+ };
1351
+ return {
1352
+ enabled: true,
1353
+ maxAttempts: Math.max(1, retry?.maxAttempts ?? 3),
1354
+ baseDelayMs: Math.max(0, retry?.baseDelayMs ?? 250),
1355
+ maxDelayMs: Math.max(0, retry?.maxDelayMs ?? 1e4)
1356
+ };
1357
+ }
1358
+ function computeRetryDelayMs(attempt, classification, opts) {
1359
+ if (classification.retryAfterMs != null) return clampMs(classification.retryAfterMs, opts.maxDelayMs);
1360
+ return clampMs(opts.baseDelayMs * 2 ** Math.max(0, attempt - 1), opts.maxDelayMs);
1361
+ }
1362
+ function shouldRetry(classification) {
1363
+ return classification.kind === "throttled" || classification.kind === "transient";
1364
+ }
1365
+ function renderReplyPayloadsToMessages(replies, options) {
1366
+ const out = [];
1367
+ const chunkLimit = Math.min(options.textChunkLimit, 4e3);
1368
+ const chunkText = options.chunkText !== false;
1369
+ const chunkMode = options.chunkMode ?? "length";
1370
+ const mediaMode = options.mediaMode ?? "split";
1371
+ const tableMode = options.tableMode ?? getMSTeamsRuntime().channel.text.resolveMarkdownTableMode({
1372
+ cfg: getMSTeamsRuntime().config.current(),
1373
+ channel: "msteams"
1374
+ });
1375
+ for (const payload of replies) {
1376
+ const reply = resolveSendableOutboundReplyParts(payload, { text: getMSTeamsRuntime().channel.text.convertMarkdownTables(payload.text ?? "", tableMode) });
1377
+ if (!reply.hasContent) continue;
1378
+ if (!reply.hasMedia) {
1379
+ pushTextMessages(out, reply.text, {
1380
+ chunkText,
1381
+ chunkLimit,
1382
+ chunkMode
1383
+ });
1384
+ continue;
1385
+ }
1386
+ if (mediaMode === "inline") {
1387
+ const firstMedia = reply.mediaUrls[0];
1388
+ if (firstMedia) {
1389
+ out.push({
1390
+ text: reply.text || void 0,
1391
+ mediaUrl: firstMedia
1392
+ });
1393
+ for (let i = 1; i < reply.mediaUrls.length; i++) if (reply.mediaUrls[i]) out.push({ mediaUrl: reply.mediaUrls[i] });
1394
+ } else pushTextMessages(out, reply.text, {
1395
+ chunkText,
1396
+ chunkLimit,
1397
+ chunkMode
1398
+ });
1399
+ continue;
1400
+ }
1401
+ pushTextMessages(out, reply.text, {
1402
+ chunkText,
1403
+ chunkLimit,
1404
+ chunkMode
1405
+ });
1406
+ for (const mediaUrl of reply.mediaUrls) {
1407
+ if (!mediaUrl) continue;
1408
+ out.push({ mediaUrl });
1409
+ }
1410
+ }
1411
+ return out;
1412
+ }
1413
+ async function buildActivity(msg, conversationRef, tokenProvider, sharePointSiteId, mediaMaxBytes, options) {
1414
+ const activity = { type: "message" };
1415
+ activity.channelData = { feedbackLoopEnabled: options?.feedbackLoopEnabled ?? false };
1416
+ if (msg.text) {
1417
+ const { text: formattedText, entities } = parseMentions(msg.text);
1418
+ activity.text = formattedText;
1419
+ activity.entities = [...entities.length > 0 ? entities : [], AI_GENERATED_ENTITY];
1420
+ } else activity.entities = [AI_GENERATED_ENTITY];
1421
+ if (msg.mediaUrl) {
1422
+ let contentUrl = msg.mediaUrl;
1423
+ let contentType = await getMimeType(msg.mediaUrl);
1424
+ let fileName = await extractFilename(msg.mediaUrl);
1425
+ if (isLocalPath(msg.mediaUrl)) {
1426
+ const maxBytes = mediaMaxBytes ?? MSTEAMS_MAX_MEDIA_BYTES$1;
1427
+ const media = await loadWebMedia(msg.mediaUrl, maxBytes);
1428
+ contentType = media.contentType ?? contentType;
1429
+ fileName = media.fileName ?? fileName;
1430
+ const conversationType = normalizeOptionalLowercaseString(conversationRef.conversation?.conversationType);
1431
+ const isPersonal = conversationType === "personal";
1432
+ const isImage = media.kind === "image";
1433
+ if (requiresFileConsent({
1434
+ conversationType,
1435
+ contentType,
1436
+ bufferSize: media.buffer.length,
1437
+ thresholdBytes: FILE_CONSENT_THRESHOLD_BYTES$1
1438
+ })) {
1439
+ const conversationId = conversationRef.conversation?.id ?? "unknown";
1440
+ const { activity: consentActivity, uploadId } = prepareFileConsentActivity({
1441
+ media: {
1442
+ buffer: media.buffer,
1443
+ filename: fileName,
1444
+ contentType
1445
+ },
1446
+ conversationId,
1447
+ description: msg.text || void 0
1448
+ });
1449
+ consentActivity._pendingUploadId = uploadId;
1450
+ return consentActivity;
1451
+ }
1452
+ if (!isPersonal && !isImage && tokenProvider && sharePointSiteId) {
1453
+ const chatId = conversationRef.graphChatId ?? conversationRef.conversation?.id;
1454
+ activity.attachments = [buildTeamsFileInfoCard(await getDriveItemProperties({
1455
+ siteId: sharePointSiteId,
1456
+ itemId: (await uploadAndShareSharePoint({
1457
+ buffer: media.buffer,
1458
+ filename: fileName,
1459
+ contentType,
1460
+ tokenProvider,
1461
+ siteId: sharePointSiteId,
1462
+ chatId: chatId ?? void 0,
1463
+ usePerUserSharing: conversationType === "groupchat"
1464
+ })).itemId,
1465
+ tokenProvider
1466
+ }))];
1467
+ return activity;
1468
+ }
1469
+ if (!isPersonal && media.kind !== "image" && tokenProvider) {
1470
+ const uploaded = await uploadAndShareOneDrive({
1471
+ buffer: media.buffer,
1472
+ filename: fileName,
1473
+ contentType,
1474
+ tokenProvider
1475
+ });
1476
+ const fileLink = `📎 [${uploaded.name}](${uploaded.shareUrl})`;
1477
+ const existingText = typeof activity.text === "string" ? activity.text : void 0;
1478
+ activity.text = existingText ? `${existingText}\n\n${fileLink}` : fileLink;
1479
+ return activity;
1480
+ }
1481
+ const base64 = media.buffer.toString("base64");
1482
+ contentUrl = `data:${media.contentType};base64,${base64}`;
1483
+ }
1484
+ activity.attachments = [{
1485
+ name: fileName,
1486
+ contentType,
1487
+ contentUrl
1488
+ }];
1489
+ }
1490
+ return activity;
1491
+ }
1492
+ async function sendMSTeamsMessages(params) {
1493
+ const messages = params.messages.filter((m) => m.text && m.text.trim().length > 0 || m.mediaUrl);
1494
+ if (messages.length === 0) return [];
1495
+ const retryOptions = resolveRetryOptions(params.retry);
1496
+ const sendWithRetry = async (sendOnce, meta) => {
1497
+ if (!retryOptions.enabled) return await sendOnce();
1498
+ let attempt = 1;
1499
+ while (true) try {
1500
+ return await sendOnce();
1501
+ } catch (err) {
1502
+ const classification = classifyMSTeamsSendError(err);
1503
+ if (!(attempt < retryOptions.maxAttempts && shouldRetry(classification))) throw err;
1504
+ const delayMs = computeRetryDelayMs(attempt, classification, retryOptions);
1505
+ const nextAttempt = attempt + 1;
1506
+ params.onRetry?.({
1507
+ messageIndex: meta.messageIndex,
1508
+ messageCount: meta.messageCount,
1509
+ nextAttempt,
1510
+ maxAttempts: retryOptions.maxAttempts,
1511
+ delayMs,
1512
+ classification
1513
+ });
1514
+ await sleep(delayMs);
1515
+ attempt = nextAttempt;
1516
+ }
1517
+ };
1518
+ const sendMessageInContext = async (ctx, message, messageIndex) => {
1519
+ let pendingUploadId;
1520
+ const messageId = extractMessageId(await sendWithRetry(async () => {
1521
+ const activity = await buildActivity(message, params.conversationRef, params.tokenProvider, params.sharePointSiteId, params.mediaMaxBytes, { feedbackLoopEnabled: params.feedbackLoopEnabled });
1522
+ pendingUploadId = typeof activity._pendingUploadId === "string" ? activity._pendingUploadId : void 0;
1523
+ if (pendingUploadId) delete activity._pendingUploadId;
1524
+ return await ctx.sendActivity(activity);
1525
+ }, {
1526
+ messageIndex,
1527
+ messageCount: messages.length
1528
+ })) ?? "unknown";
1529
+ if (pendingUploadId && messageId !== "unknown") setPendingUploadActivityId(pendingUploadId, messageId);
1530
+ return messageId;
1531
+ };
1532
+ const sendMessageBatchInContext = async (ctx, batch, startIndex) => {
1533
+ const messageIds = [];
1534
+ for (const [idx, message] of batch.entries()) messageIds.push(await sendMessageInContext(ctx, message, startIndex + idx));
1535
+ return messageIds;
1536
+ };
1537
+ const sendProactively = async (batch, startIndex, threadActivityId) => {
1538
+ const baseRef = buildConversationReference(params.conversationRef);
1539
+ const conversationId = params.conversationRef.conversation?.conversationType === "channel" && threadActivityId ? `${baseRef.conversation.id};messageid=${threadActivityId}` : baseRef.conversation.id;
1540
+ const proactiveRef = {
1541
+ ...baseRef,
1542
+ activityId: void 0,
1543
+ conversation: {
1544
+ ...baseRef.conversation,
1545
+ id: conversationId
1546
+ }
1547
+ };
1548
+ const messageIds = [];
1549
+ await params.adapter.continueConversation(params.appId, proactiveRef, async (ctx) => {
1550
+ messageIds.push(...await sendMessageBatchInContext(ctx, batch, startIndex));
1551
+ });
1552
+ return messageIds;
1553
+ };
1554
+ const resolvedThreadId = params.conversationRef.threadId ?? params.conversationRef.activityId;
1555
+ if (params.replyStyle === "thread") {
1556
+ const ctx = params.context;
1557
+ if (!ctx) throw new Error("Missing context for replyStyle=thread");
1558
+ const messageIds = [];
1559
+ for (const [idx, message] of messages.entries()) {
1560
+ const result = await withRevokedProxyFallback({
1561
+ run: async () => ({
1562
+ ids: [await sendMessageInContext(ctx, message, idx)],
1563
+ fellBack: false
1564
+ }),
1565
+ onRevoked: async () => {
1566
+ const remaining = messages.slice(idx);
1567
+ return {
1568
+ ids: remaining.length > 0 ? await sendProactively(remaining, idx, resolvedThreadId) : [],
1569
+ fellBack: true
1570
+ };
1571
+ }
1572
+ });
1573
+ messageIds.push(...result.ids);
1574
+ if (result.fellBack) return messageIds;
1575
+ }
1576
+ return messageIds;
1577
+ }
1578
+ return await sendProactively(messages, 0);
1579
+ }
1580
+ //#endregion
1581
+ //#region extensions/msteams/src/send-context.ts
1582
+ /**
1583
+ * Parse the target value into a conversation reference lookup key.
1584
+ * Supported formats:
1585
+ * - conversation:19:abc@thread.tacv2 → lookup by conversation ID
1586
+ * - user:aad-object-id → lookup by user AAD object ID
1587
+ * - 19:abc@thread.tacv2 → direct conversation ID
1588
+ */
1589
+ function parseRecipient(to) {
1590
+ const trimmed = to.trim();
1591
+ const finalize = (type, id) => {
1592
+ const normalized = id.trim();
1593
+ if (!normalized) throw new Error(`Invalid target value: missing ${type} id`);
1594
+ return {
1595
+ type,
1596
+ id: normalized
1597
+ };
1598
+ };
1599
+ if (trimmed.startsWith("conversation:")) return finalize("conversation", trimmed.slice(13));
1600
+ if (trimmed.startsWith("user:")) return finalize("user", trimmed.slice(5));
1601
+ if (trimmed.startsWith("19:") || trimmed.includes("@thread")) return finalize("conversation", trimmed);
1602
+ return finalize("user", trimmed);
1603
+ }
1604
+ /**
1605
+ * Find a stored conversation reference for the given recipient.
1606
+ */
1607
+ async function findConversationReference(recipient) {
1608
+ if (recipient.type === "conversation") {
1609
+ const ref = await recipient.store.get(recipient.id);
1610
+ if (ref) return {
1611
+ conversationId: recipient.id,
1612
+ ref
1613
+ };
1614
+ return null;
1615
+ }
1616
+ const found = await recipient.store.findPreferredDmByUserId(recipient.id);
1617
+ if (!found) return null;
1618
+ return {
1619
+ conversationId: found.conversationId,
1620
+ ref: found.reference
1621
+ };
1622
+ }
1623
+ async function resolveMSTeamsSendContext(params) {
1624
+ const msteamsCfg = params.cfg.channels?.msteams;
1625
+ if (!msteamsCfg?.enabled) throw new Error("msteams provider is not enabled");
1626
+ const creds = resolveMSTeamsCredentials(msteamsCfg);
1627
+ if (!creds) throw new Error("msteams credentials not configured");
1628
+ const store = createMSTeamsConversationStoreFs();
1629
+ const recipient = parseRecipient(params.to);
1630
+ const found = await findConversationReference({
1631
+ ...recipient,
1632
+ store
1633
+ });
1634
+ if (!found) throw new Error(`No conversation reference found for ${recipient.type}:${recipient.id}. The bot must receive a message from this conversation before it can send proactively.`);
1635
+ const { conversationId, ref } = found;
1636
+ if (recipient.type === "user") {
1637
+ const resolvedType = normalizeLowercaseStringOrEmpty(ref.conversation?.conversationType ?? "");
1638
+ if (resolvedType && resolvedType !== "personal") throw new Error(`Conversation reference for user:${recipient.id} resolved to a ${resolvedType} conversation (${conversationId}) instead of a personal DM. The bot must receive a DM from this user before it can send proactively.`);
1639
+ }
1640
+ const log = getMSTeamsRuntime().logging.getChildLogger({ name: "msteams:send" });
1641
+ const { sdk, app } = await loadMSTeamsSdkWithAuth(creds);
1642
+ const adapter = createMSTeamsAdapter(app, sdk);
1643
+ const tokenProvider = createMSTeamsTokenProvider(app);
1644
+ const storedConversationType = normalizeLowercaseStringOrEmpty(ref.conversation?.conversationType ?? "");
1645
+ let conversationType;
1646
+ if (storedConversationType === "personal") conversationType = "personal";
1647
+ else if (storedConversationType === "channel") conversationType = "channel";
1648
+ else conversationType = "groupChat";
1649
+ const sharePointSiteId = msteamsCfg.sharePointSiteId;
1650
+ const mediaMaxBytes = resolveChannelMediaMaxBytes({
1651
+ cfg: params.cfg,
1652
+ resolveChannelLimitMb: ({ cfg }) => cfg.channels?.msteams?.mediaMaxMb
1653
+ });
1654
+ let graphChatId = ref.graphChatId ?? void 0;
1655
+ if (graphChatId === void 0 && sharePointSiteId) try {
1656
+ const resolved = await resolveGraphChatId({
1657
+ botFrameworkConversationId: conversationId,
1658
+ userAadObjectId: ref.user?.aadObjectId,
1659
+ tokenProvider
1660
+ });
1661
+ graphChatId = resolved;
1662
+ if (resolved) await store.upsert(conversationId, {
1663
+ ...ref,
1664
+ graphChatId: resolved
1665
+ });
1666
+ else log.warn?.("could not resolve Graph chat ID; file uploads may fail for this conversation", { conversationId });
1667
+ } catch (err) {
1668
+ log.warn?.("failed to resolve Graph chat ID; file uploads may fall back to Bot Framework ID", {
1669
+ conversationId,
1670
+ error: formatUnknownError(err)
1671
+ });
1672
+ graphChatId = null;
1673
+ }
1674
+ return {
1675
+ appId: creds.appId,
1676
+ conversationId,
1677
+ ref,
1678
+ adapter,
1679
+ log,
1680
+ conversationType,
1681
+ tokenProvider,
1682
+ sharePointSiteId,
1683
+ mediaMaxBytes,
1684
+ graphChatId
1685
+ };
1686
+ }
1687
+ //#endregion
1688
+ //#region extensions/msteams/src/send.ts
1689
+ /** Threshold for large files that require FileConsentCard flow in personal chats */
1690
+ const FILE_CONSENT_THRESHOLD_BYTES = 4 * 1024 * 1024;
1691
+ /**
1692
+ * MSTeams-specific media size limit (100MB).
1693
+ * Higher than the default because OneDrive upload handles large files well.
1694
+ */
1695
+ const MSTEAMS_MAX_MEDIA_BYTES = 100 * 1024 * 1024;
1696
+ /**
1697
+ * Send a message to a Teams conversation or user.
1698
+ *
1699
+ * Uses the stored ConversationReference from previous interactions.
1700
+ * The bot must have received at least one message from the conversation
1701
+ * before proactive messaging works.
1702
+ *
1703
+ * File handling by conversation type:
1704
+ * - Personal (1:1) chats: small images (<4MB) use base64, large files and non-images use FileConsentCard
1705
+ * - Group chats / channels: files are uploaded to OneDrive and shared via link
1706
+ */
1707
+ async function sendMessageMSTeams(params) {
1708
+ const { cfg, to, text, mediaUrl, filename, mediaLocalRoots, mediaReadFile } = params;
1709
+ const tableMode = resolveMarkdownTableMode({
1710
+ cfg,
1711
+ channel: "msteams"
1712
+ });
1713
+ const messageText = convertMarkdownTables(text ?? "", tableMode);
1714
+ const ctx = await resolveMSTeamsSendContext({
1715
+ cfg,
1716
+ to
1717
+ });
1718
+ const { adapter, appId, conversationId, ref, log, conversationType, tokenProvider, sharePointSiteId } = ctx;
1719
+ log.debug?.("sending proactive message", {
1720
+ conversationId,
1721
+ conversationType,
1722
+ textLength: messageText.length,
1723
+ hasMedia: Boolean(mediaUrl)
1724
+ });
1725
+ if (mediaUrl) {
1726
+ const media = await loadOutboundMediaFromUrl(mediaUrl, {
1727
+ maxBytes: ctx.mediaMaxBytes ?? MSTEAMS_MAX_MEDIA_BYTES,
1728
+ mediaLocalRoots,
1729
+ mediaReadFile
1730
+ });
1731
+ const isLargeFile = media.buffer.length >= FILE_CONSENT_THRESHOLD_BYTES;
1732
+ const isImage = media.contentType?.startsWith("image/") ?? false;
1733
+ const fallbackFileName = await extractFilename(mediaUrl);
1734
+ const fileName = filename?.trim() || media.fileName || fallbackFileName;
1735
+ log.debug?.("processing media", {
1736
+ fileName,
1737
+ contentType: media.contentType,
1738
+ size: media.buffer.length,
1739
+ isLargeFile,
1740
+ isImage,
1741
+ conversationType
1742
+ });
1743
+ if (requiresFileConsent({
1744
+ conversationType,
1745
+ contentType: media.contentType,
1746
+ bufferSize: media.buffer.length,
1747
+ thresholdBytes: FILE_CONSENT_THRESHOLD_BYTES
1748
+ })) {
1749
+ const { activity, uploadId } = await prepareFileConsentActivityFs({
1750
+ media: {
1751
+ buffer: media.buffer,
1752
+ filename: fileName,
1753
+ contentType: media.contentType
1754
+ },
1755
+ conversationId,
1756
+ description: messageText || void 0
1757
+ });
1758
+ log.debug?.("sending file consent card", {
1759
+ uploadId,
1760
+ fileName,
1761
+ size: media.buffer.length
1762
+ });
1763
+ const messageId = await sendProactiveActivity({
1764
+ adapter,
1765
+ appId,
1766
+ ref,
1767
+ activity,
1768
+ errorPrefix: "msteams consent card send"
1769
+ });
1770
+ setPendingUploadActivityId(uploadId, messageId);
1771
+ await setPendingUploadActivityIdFs(uploadId, messageId);
1772
+ log.info("sent file consent card", {
1773
+ conversationId,
1774
+ messageId,
1775
+ uploadId
1776
+ });
1777
+ return {
1778
+ messageId,
1779
+ conversationId,
1780
+ pendingUploadId: uploadId
1781
+ };
1782
+ }
1783
+ if (conversationType === "personal") {
1784
+ const base64 = media.buffer.toString("base64");
1785
+ return sendTextWithMedia(ctx, messageText, `data:${media.contentType};base64,${base64}`);
1786
+ }
1787
+ if (isImage && !sharePointSiteId) {
1788
+ const base64 = media.buffer.toString("base64");
1789
+ return sendTextWithMedia(ctx, messageText, `data:${media.contentType};base64,${base64}`);
1790
+ }
1791
+ try {
1792
+ if (sharePointSiteId) {
1793
+ log.debug?.("uploading to SharePoint for native file card", {
1794
+ fileName,
1795
+ conversationType,
1796
+ siteId: sharePointSiteId
1797
+ });
1798
+ const uploaded = await uploadAndShareSharePoint({
1799
+ buffer: media.buffer,
1800
+ filename: fileName,
1801
+ contentType: media.contentType,
1802
+ tokenProvider,
1803
+ siteId: sharePointSiteId,
1804
+ chatId: ctx.graphChatId ?? conversationId,
1805
+ usePerUserSharing: conversationType === "groupChat"
1806
+ });
1807
+ log.debug?.("SharePoint upload complete", {
1808
+ itemId: uploaded.itemId,
1809
+ shareUrl: uploaded.shareUrl
1810
+ });
1811
+ const driveItem = await getDriveItemProperties({
1812
+ siteId: sharePointSiteId,
1813
+ itemId: uploaded.itemId,
1814
+ tokenProvider
1815
+ });
1816
+ log.debug?.("driveItem properties retrieved", {
1817
+ eTag: driveItem.eTag,
1818
+ webDavUrl: driveItem.webDavUrl
1819
+ });
1820
+ const fileCardAttachment = buildTeamsFileInfoCard(driveItem);
1821
+ const messageId = await sendProactiveActivityRaw({
1822
+ adapter,
1823
+ appId,
1824
+ ref,
1825
+ activity: {
1826
+ type: "message",
1827
+ text: messageText || void 0,
1828
+ attachments: [fileCardAttachment]
1829
+ }
1830
+ });
1831
+ log.info("sent native file card", {
1832
+ conversationId,
1833
+ messageId,
1834
+ fileName: driveItem.name
1835
+ });
1836
+ return {
1837
+ messageId,
1838
+ conversationId
1839
+ };
1840
+ }
1841
+ log.debug?.("uploading to OneDrive (no SharePoint site configured)", {
1842
+ fileName,
1843
+ conversationType
1844
+ });
1845
+ const uploaded = await uploadAndShareOneDrive({
1846
+ buffer: media.buffer,
1847
+ filename: fileName,
1848
+ contentType: media.contentType,
1849
+ tokenProvider
1850
+ });
1851
+ log.debug?.("OneDrive upload complete", {
1852
+ itemId: uploaded.itemId,
1853
+ shareUrl: uploaded.shareUrl
1854
+ });
1855
+ const fileLink = `📎 [${uploaded.name}](${uploaded.shareUrl})`;
1856
+ const messageId = await sendProactiveActivityRaw({
1857
+ adapter,
1858
+ appId,
1859
+ ref,
1860
+ activity: {
1861
+ type: "message",
1862
+ text: messageText ? `${messageText}\n\n${fileLink}` : fileLink
1863
+ }
1864
+ });
1865
+ log.info("sent message with OneDrive file link", {
1866
+ conversationId,
1867
+ messageId,
1868
+ shareUrl: uploaded.shareUrl
1869
+ });
1870
+ return {
1871
+ messageId,
1872
+ conversationId
1873
+ };
1874
+ } catch (err) {
1875
+ const classification = classifyMSTeamsSendError(err);
1876
+ const hint = formatMSTeamsSendErrorHint(classification);
1877
+ const status = classification.statusCode ? ` (HTTP ${classification.statusCode})` : "";
1878
+ throw new Error(`msteams file send failed${status}: ${formatUnknownError(err)}${hint ? ` (${hint})` : ""}`, { cause: err });
1879
+ }
1880
+ }
1881
+ return sendTextWithMedia(ctx, messageText, void 0);
1882
+ }
1883
+ /**
1884
+ * Send a text message with optional base64 media URL.
1885
+ */
1886
+ async function sendTextWithMedia(ctx, text, mediaUrl) {
1887
+ const { adapter, appId, conversationId, ref, log, tokenProvider, sharePointSiteId, mediaMaxBytes } = ctx;
1888
+ let messageIds;
1889
+ try {
1890
+ messageIds = await sendMSTeamsMessages({
1891
+ replyStyle: "top-level",
1892
+ adapter,
1893
+ appId,
1894
+ conversationRef: ref,
1895
+ messages: [{
1896
+ text: text || void 0,
1897
+ mediaUrl
1898
+ }],
1899
+ retry: {},
1900
+ onRetry: (event) => {
1901
+ log.debug?.("retrying send", {
1902
+ conversationId,
1903
+ ...event
1904
+ });
1905
+ },
1906
+ tokenProvider,
1907
+ sharePointSiteId,
1908
+ mediaMaxBytes
1909
+ });
1910
+ } catch (err) {
1911
+ const classification = classifyMSTeamsSendError(err);
1912
+ const hint = formatMSTeamsSendErrorHint(classification);
1913
+ const status = classification.statusCode ? ` (HTTP ${classification.statusCode})` : "";
1914
+ throw new Error(`msteams send failed${status}: ${formatUnknownError(err)}${hint ? ` (${hint})` : ""}`, { cause: err });
1915
+ }
1916
+ const messageId = messageIds[0] ?? "unknown";
1917
+ log.info("sent proactive message", {
1918
+ conversationId,
1919
+ messageId
1920
+ });
1921
+ return {
1922
+ messageId,
1923
+ conversationId
1924
+ };
1925
+ }
1926
+ async function sendProactiveActivityRaw({ adapter, appId, ref, activity }) {
1927
+ const proactiveRef = {
1928
+ ...buildConversationReference(ref),
1929
+ activityId: void 0
1930
+ };
1931
+ let messageId = "unknown";
1932
+ await adapter.continueConversation(appId, proactiveRef, async (ctx) => {
1933
+ messageId = extractMessageId(await ctx.sendActivity(activity)) ?? "unknown";
1934
+ });
1935
+ return messageId;
1936
+ }
1937
+ async function sendProactiveActivity({ adapter, appId, ref, activity, errorPrefix }) {
1938
+ try {
1939
+ return await sendProactiveActivityRaw({
1940
+ adapter,
1941
+ appId,
1942
+ ref,
1943
+ activity
1944
+ });
1945
+ } catch (err) {
1946
+ const classification = classifyMSTeamsSendError(err);
1947
+ const hint = formatMSTeamsSendErrorHint(classification);
1948
+ const status = classification.statusCode ? ` (HTTP ${classification.statusCode})` : "";
1949
+ throw new Error(`${errorPrefix} failed${status}: ${formatUnknownError(err)}${hint ? ` (${hint})` : ""}`, { cause: err });
1950
+ }
1951
+ }
1952
+ /**
1953
+ * Send a poll (Adaptive Card) to a Teams conversation or user.
1954
+ */
1955
+ async function sendPollMSTeams(params) {
1956
+ const { cfg, to, question, options, maxSelections } = params;
1957
+ const { adapter, appId, conversationId, ref, log } = await resolveMSTeamsSendContext({
1958
+ cfg,
1959
+ to
1960
+ });
1961
+ const pollCard = buildMSTeamsPollCard({
1962
+ question,
1963
+ options,
1964
+ maxSelections
1965
+ });
1966
+ log.debug?.("sending poll", {
1967
+ conversationId,
1968
+ pollId: pollCard.pollId,
1969
+ optionCount: pollCard.options.length
1970
+ });
1971
+ const messageId = await sendProactiveActivity({
1972
+ adapter,
1973
+ appId,
1974
+ ref,
1975
+ activity: {
1976
+ type: "message",
1977
+ attachments: [{
1978
+ contentType: "application/vnd.microsoft.card.adaptive",
1979
+ content: pollCard.card
1980
+ }]
1981
+ },
1982
+ errorPrefix: "msteams poll send"
1983
+ });
1984
+ log.info("sent poll", {
1985
+ conversationId,
1986
+ pollId: pollCard.pollId,
1987
+ messageId
1988
+ });
1989
+ return {
1990
+ pollId: pollCard.pollId,
1991
+ messageId,
1992
+ conversationId
1993
+ };
1994
+ }
1995
+ /**
1996
+ * Send an arbitrary Adaptive Card to a Teams conversation or user.
1997
+ */
1998
+ async function sendAdaptiveCardMSTeams(params) {
1999
+ const { cfg, to, card } = params;
2000
+ const { adapter, appId, conversationId, ref, log } = await resolveMSTeamsSendContext({
2001
+ cfg,
2002
+ to
2003
+ });
2004
+ log.debug?.("sending adaptive card", {
2005
+ conversationId,
2006
+ cardType: card.type,
2007
+ cardVersion: card.version
2008
+ });
2009
+ const messageId = await sendProactiveActivity({
2010
+ adapter,
2011
+ appId,
2012
+ ref,
2013
+ activity: {
2014
+ type: "message",
2015
+ attachments: [{
2016
+ contentType: "application/vnd.microsoft.card.adaptive",
2017
+ content: card
2018
+ }]
2019
+ },
2020
+ errorPrefix: "msteams card send"
2021
+ });
2022
+ log.info("sent adaptive card", {
2023
+ conversationId,
2024
+ messageId
2025
+ });
2026
+ return {
2027
+ messageId,
2028
+ conversationId
2029
+ };
2030
+ }
2031
+ /**
2032
+ * Edit (update) a previously sent message in a Teams conversation.
2033
+ *
2034
+ * Uses the Bot Framework `continueConversation` → `updateActivity` flow
2035
+ * for proactive edits outside of the original turn context.
2036
+ */
2037
+ async function editMessageMSTeams(params) {
2038
+ const { cfg, to, activityId, text } = params;
2039
+ const { adapter, appId, conversationId, ref, log } = await resolveMSTeamsSendContext({
2040
+ cfg,
2041
+ to
2042
+ });
2043
+ log.debug?.("editing proactive message", {
2044
+ conversationId,
2045
+ activityId,
2046
+ textLength: text.length
2047
+ });
2048
+ const proactiveRef = {
2049
+ ...buildConversationReference(ref),
2050
+ activityId: void 0
2051
+ };
2052
+ try {
2053
+ await adapter.continueConversation(appId, proactiveRef, async (ctx) => {
2054
+ await ctx.updateActivity({
2055
+ type: "message",
2056
+ id: activityId,
2057
+ text
2058
+ });
2059
+ });
2060
+ } catch (err) {
2061
+ const classification = classifyMSTeamsSendError(err);
2062
+ const hint = formatMSTeamsSendErrorHint(classification);
2063
+ const status = classification.statusCode ? ` (HTTP ${classification.statusCode})` : "";
2064
+ throw new Error(`msteams edit failed${status}: ${formatUnknownError(err)}${hint ? ` (${hint})` : ""}`, { cause: err });
2065
+ }
2066
+ log.info("edited proactive message", {
2067
+ conversationId,
2068
+ activityId
2069
+ });
2070
+ return { conversationId };
2071
+ }
2072
+ /**
2073
+ * Delete a previously sent message in a Teams conversation.
2074
+ *
2075
+ * Uses the Bot Framework `continueConversation` → `deleteActivity` flow
2076
+ * for proactive deletes outside of the original turn context.
2077
+ */
2078
+ async function deleteMessageMSTeams(params) {
2079
+ const { cfg, to, activityId } = params;
2080
+ const { adapter, appId, conversationId, ref, log } = await resolveMSTeamsSendContext({
2081
+ cfg,
2082
+ to
2083
+ });
2084
+ log.debug?.("deleting proactive message", {
2085
+ conversationId,
2086
+ activityId
2087
+ });
2088
+ const proactiveRef = {
2089
+ ...buildConversationReference(ref),
2090
+ activityId: void 0
2091
+ };
2092
+ try {
2093
+ await adapter.continueConversation(appId, proactiveRef, async (ctx) => {
2094
+ await ctx.deleteActivity(activityId);
2095
+ });
2096
+ } catch (err) {
2097
+ const classification = classifyMSTeamsSendError(err);
2098
+ const hint = formatMSTeamsSendErrorHint(classification);
2099
+ const status = classification.statusCode ? ` (HTTP ${classification.statusCode})` : "";
2100
+ throw new Error(`msteams delete failed${status}: ${formatUnknownError(err)}${hint ? ` (${hint})` : ""}`, { cause: err });
2101
+ }
2102
+ log.info("deleted proactive message", {
2103
+ conversationId,
2104
+ activityId
2105
+ });
2106
+ return { conversationId };
2107
+ }
2108
+ //#endregion
2109
+ //#region extensions/msteams/src/probe.ts
2110
+ function decodeJwtPayload(token) {
2111
+ const parts = token.split(".");
2112
+ if (parts.length < 2) return null;
2113
+ const payload = parts[1] ?? "";
2114
+ const normalized = payload.padEnd(payload.length + (4 - payload.length % 4) % 4, "=").replace(/-/g, "+").replace(/_/g, "/");
2115
+ try {
2116
+ const decoded = Buffer.from(normalized, "base64").toString("utf8");
2117
+ const parsed = JSON.parse(decoded);
2118
+ return parsed && typeof parsed === "object" ? parsed : null;
2119
+ } catch {
2120
+ return null;
2121
+ }
2122
+ }
2123
+ function readStringArray(value) {
2124
+ if (!Array.isArray(value)) return;
2125
+ const out = normalizeStringEntries(value);
2126
+ return out.length > 0 ? out : void 0;
2127
+ }
2128
+ function readScopes(value) {
2129
+ if (typeof value !== "string") return;
2130
+ const out = value.split(/\s+/).map((entry) => entry.trim()).filter(Boolean);
2131
+ return out.length > 0 ? out : void 0;
2132
+ }
2133
+ async function probeMSTeams(cfg) {
2134
+ const creds = resolveMSTeamsCredentials(cfg);
2135
+ if (!creds) return {
2136
+ ok: false,
2137
+ error: "missing credentials (appId, appPassword, tenantId)"
2138
+ };
2139
+ try {
2140
+ const { app } = await loadMSTeamsSdkWithAuth(creds);
2141
+ const tokenProvider = createMSTeamsTokenProvider(app);
2142
+ if (!await tokenProvider.getAccessToken("https://api.botframework.com")) throw new Error("Failed to acquire bot token");
2143
+ let graph;
2144
+ try {
2145
+ const accessToken = readAccessToken(await tokenProvider.getAccessToken("https://graph.microsoft.com"));
2146
+ const payload = accessToken ? decodeJwtPayload(accessToken) : null;
2147
+ graph = {
2148
+ ok: true,
2149
+ roles: readStringArray(payload?.roles),
2150
+ scopes: readScopes(payload?.scp)
2151
+ };
2152
+ } catch (err) {
2153
+ graph = {
2154
+ ok: false,
2155
+ error: formatUnknownError(err)
2156
+ };
2157
+ }
2158
+ let delegatedAuth;
2159
+ if (cfg?.delegatedAuth?.enabled) try {
2160
+ const tokens = loadDelegatedTokens();
2161
+ if (tokens) {
2162
+ const isExpired = tokens.expiresAt <= Date.now();
2163
+ delegatedAuth = {
2164
+ ok: !isExpired,
2165
+ scopes: tokens.scopes,
2166
+ userPrincipalName: tokens.userPrincipalName,
2167
+ ...isExpired ? { error: "token expired (will auto-refresh on next use)" } : {}
2168
+ };
2169
+ } else delegatedAuth = {
2170
+ ok: false,
2171
+ error: "no delegated tokens found (run setup wizard)"
2172
+ };
2173
+ } catch {
2174
+ delegatedAuth = {
2175
+ ok: false,
2176
+ error: "failed to load delegated tokens"
2177
+ };
2178
+ }
2179
+ return {
2180
+ ok: true,
2181
+ appId: creds.appId,
2182
+ ...graph ? { graph } : {},
2183
+ ...delegatedAuth ? { delegatedAuth } : {}
2184
+ };
2185
+ } catch (err) {
2186
+ return {
2187
+ ok: false,
2188
+ appId: creds.appId,
2189
+ error: formatUnknownError(err)
2190
+ };
2191
+ }
2192
+ }
2193
+ //#endregion
2194
+ export { readJsonFile as C, createMSTeamsConversationStoreFs as S, writeJsonFile as T, buildFileInfoCard as _, sendMessageMSTeams as a, createMSTeamsPollStoreFs as b, renderReplyPayloadsToMessages as c, withRevokedProxyFallback as d, resolveGraphChatId as f, removePendingUploadFs as g, getPendingUploadFs as h, sendAdaptiveCardMSTeams as i, sendMSTeamsMessages as l, removePendingUpload as m, deleteMessageMSTeams as n, sendPollMSTeams as o, getPendingUpload as p, editMessageMSTeams as r, buildConversationReference as s, probeMSTeams as t, AI_GENERATED_ENTITY as u, parseFileConsentInvoke as v, withFileLock$1 as w, extractMSTeamsPollVote as x, uploadToConsentUrl as y };