@kodelyth/msteams 2026.5.39 → 2026.5.42

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 (208) hide show
  1. package/api.ts +3 -0
  2. package/channel-config-api.ts +1 -0
  3. package/channel-plugin-api.ts +2 -0
  4. package/config-api.ts +4 -0
  5. package/contract-api.ts +4 -0
  6. package/dist/api.js +3 -0
  7. package/dist/channel-BvTXHuGs.js +1161 -0
  8. package/dist/channel-config-api.js +2 -0
  9. package/dist/channel-plugin-api.js +2 -0
  10. package/dist/channel.runtime-NssGKZm5.js +650 -0
  11. package/dist/config-schema-Btk-XCOd.js +43 -0
  12. package/dist/contract-api.js +2 -0
  13. package/dist/graph-users-D-gKCguI.js +1411 -0
  14. package/dist/index.js +22 -0
  15. package/dist/oauth-BUxlphX3.js +114 -0
  16. package/dist/oauth.token-ebId9946.js +116 -0
  17. package/dist/probe-Cj2KsAGF.js +2190 -0
  18. package/dist/runtime-api-BL4DOWXD.js +28 -0
  19. package/dist/runtime-api.js +2 -0
  20. package/dist/secret-contract-Bo7kdUrT.js +35 -0
  21. package/dist/secret-contract-api.js +2 -0
  22. package/dist/setup-entry.js +15 -0
  23. package/dist/setup-plugin-api.js +64 -0
  24. package/dist/setup-surface-COTQDcTQ.js +531 -0
  25. package/dist/src-tvpsGYPV.js +4226 -0
  26. package/dist/test-api.js +2 -0
  27. package/index.ts +20 -0
  28. package/klaw.plugin.json +2 -726
  29. package/package.json +4 -4
  30. package/runtime-api.ts +66 -0
  31. package/secret-contract-api.ts +5 -0
  32. package/setup-entry.ts +13 -0
  33. package/setup-plugin-api.ts +3 -0
  34. package/src/ai-entity.ts +7 -0
  35. package/src/approval-auth.ts +44 -0
  36. package/src/attachments/bot-framework.test.ts +506 -0
  37. package/src/attachments/bot-framework.ts +348 -0
  38. package/src/attachments/download.ts +328 -0
  39. package/src/attachments/graph.test.ts +441 -0
  40. package/src/attachments/graph.ts +489 -0
  41. package/src/attachments/html.ts +122 -0
  42. package/src/attachments/payload.ts +14 -0
  43. package/src/attachments/remote-media.test.ts +187 -0
  44. package/src/attachments/remote-media.ts +86 -0
  45. package/src/attachments/shared.test.ts +547 -0
  46. package/src/attachments/shared.ts +655 -0
  47. package/src/attachments/types.ts +47 -0
  48. package/src/attachments.graph.test.ts +414 -0
  49. package/src/attachments.helpers.test.ts +245 -0
  50. package/src/attachments.test-helpers.ts +17 -0
  51. package/src/attachments.test.ts +754 -0
  52. package/src/attachments.ts +18 -0
  53. package/src/block-streaming-config.test.ts +61 -0
  54. package/src/channel-api.ts +1 -0
  55. package/src/channel.actions.test.ts +797 -0
  56. package/src/channel.directory.test.ts +176 -0
  57. package/src/channel.message-adapter.test.ts +227 -0
  58. package/src/channel.runtime.ts +56 -0
  59. package/src/channel.setup.ts +77 -0
  60. package/src/channel.test.ts +136 -0
  61. package/src/channel.ts +1176 -0
  62. package/src/config-schema.ts +6 -0
  63. package/src/config-ui-hints.ts +40 -0
  64. package/src/conversation-store-fs.test.ts +81 -0
  65. package/src/conversation-store-fs.ts +149 -0
  66. package/src/conversation-store-helpers.test.ts +202 -0
  67. package/src/conversation-store-helpers.ts +105 -0
  68. package/src/conversation-store-memory.ts +51 -0
  69. package/src/conversation-store.shared.test.ts +260 -0
  70. package/src/conversation-store.ts +71 -0
  71. package/src/directory-live.test.ts +156 -0
  72. package/src/directory-live.ts +111 -0
  73. package/src/doctor.ts +27 -0
  74. package/src/errors.test.ts +154 -0
  75. package/src/errors.ts +270 -0
  76. package/src/feedback-reflection-prompt.ts +117 -0
  77. package/src/feedback-reflection-store.ts +113 -0
  78. package/src/feedback-reflection.test.ts +237 -0
  79. package/src/feedback-reflection.ts +268 -0
  80. package/src/file-consent-helpers.test.ts +328 -0
  81. package/src/file-consent-helpers.ts +115 -0
  82. package/src/file-consent-invoke.ts +150 -0
  83. package/src/file-consent.test.ts +378 -0
  84. package/src/file-consent.ts +223 -0
  85. package/src/graph-chat.ts +36 -0
  86. package/src/graph-group-management.test.ts +332 -0
  87. package/src/graph-group-management.ts +168 -0
  88. package/src/graph-members.test.ts +89 -0
  89. package/src/graph-members.ts +48 -0
  90. package/src/graph-messages.actions.test.ts +253 -0
  91. package/src/graph-messages.read.test.ts +391 -0
  92. package/src/graph-messages.search.test.ts +227 -0
  93. package/src/graph-messages.test-helpers.ts +50 -0
  94. package/src/graph-messages.ts +534 -0
  95. package/src/graph-teams.test.ts +222 -0
  96. package/src/graph-teams.ts +114 -0
  97. package/src/graph-thread.test.ts +252 -0
  98. package/src/graph-thread.ts +146 -0
  99. package/src/graph-upload.test.ts +253 -0
  100. package/src/graph-upload.ts +531 -0
  101. package/src/graph-users.ts +29 -0
  102. package/src/graph.test.ts +540 -0
  103. package/src/graph.ts +308 -0
  104. package/src/inbound.test.ts +221 -0
  105. package/src/inbound.ts +148 -0
  106. package/src/index.ts +4 -0
  107. package/src/media-helpers.test.ts +220 -0
  108. package/src/media-helpers.ts +105 -0
  109. package/src/mentions.test.ts +254 -0
  110. package/src/mentions.ts +114 -0
  111. package/src/messenger.test.ts +961 -0
  112. package/src/messenger.ts +608 -0
  113. package/src/monitor-handler/access.ts +136 -0
  114. package/src/monitor-handler/inbound-media.test.ts +314 -0
  115. package/src/monitor-handler/inbound-media.ts +180 -0
  116. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  117. package/src/monitor-handler/message-handler.authz.test.ts +739 -0
  118. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  119. package/src/monitor-handler/message-handler.test-support.ts +99 -0
  120. package/src/monitor-handler/message-handler.thread-parent.test.ts +225 -0
  121. package/src/monitor-handler/message-handler.thread-session.test.ts +132 -0
  122. package/src/monitor-handler/message-handler.ts +1003 -0
  123. package/src/monitor-handler/reaction-handler.test.ts +325 -0
  124. package/src/monitor-handler/reaction-handler.ts +122 -0
  125. package/src/monitor-handler/thread-session.ts +30 -0
  126. package/src/monitor-handler.adaptive-card.test.ts +158 -0
  127. package/src/monitor-handler.feedback-authz.test.ts +357 -0
  128. package/src/monitor-handler.file-consent.test.ts +443 -0
  129. package/src/monitor-handler.sso.test.ts +576 -0
  130. package/src/monitor-handler.test-helpers.ts +181 -0
  131. package/src/monitor-handler.ts +538 -0
  132. package/src/monitor-handler.types.ts +27 -0
  133. package/src/monitor-types.ts +6 -0
  134. package/src/monitor.lifecycle.test.ts +457 -0
  135. package/src/monitor.test.ts +119 -0
  136. package/src/monitor.ts +476 -0
  137. package/src/oauth.flow.ts +77 -0
  138. package/src/oauth.shared.ts +37 -0
  139. package/src/oauth.test.ts +350 -0
  140. package/src/oauth.token.ts +162 -0
  141. package/src/oauth.ts +130 -0
  142. package/src/outbound.test.ts +400 -0
  143. package/src/outbound.ts +198 -0
  144. package/src/pending-uploads-fs.test.ts +261 -0
  145. package/src/pending-uploads-fs.ts +235 -0
  146. package/src/pending-uploads.test.ts +186 -0
  147. package/src/pending-uploads.ts +121 -0
  148. package/src/policy.test.ts +156 -0
  149. package/src/policy.ts +245 -0
  150. package/src/polls-store-memory.ts +32 -0
  151. package/src/polls.test.ts +169 -0
  152. package/src/polls.ts +312 -0
  153. package/src/presentation.ts +93 -0
  154. package/src/probe.test.ts +79 -0
  155. package/src/probe.ts +132 -0
  156. package/src/reply-dispatcher.test.ts +543 -0
  157. package/src/reply-dispatcher.ts +523 -0
  158. package/src/reply-stream-controller.test.ts +424 -0
  159. package/src/reply-stream-controller.ts +334 -0
  160. package/src/resolve-allowlist.test.ts +253 -0
  161. package/src/resolve-allowlist.ts +309 -0
  162. package/src/revoked-context.ts +17 -0
  163. package/src/runtime.ts +12 -0
  164. package/src/sdk-types.ts +59 -0
  165. package/src/sdk.test.ts +727 -0
  166. package/src/sdk.ts +916 -0
  167. package/src/secret-contract.ts +49 -0
  168. package/src/secret-input.ts +7 -0
  169. package/src/send-context.test.ts +93 -0
  170. package/src/send-context.ts +269 -0
  171. package/src/send.test.ts +588 -0
  172. package/src/send.ts +697 -0
  173. package/src/sent-message-cache.test.ts +106 -0
  174. package/src/sent-message-cache.ts +174 -0
  175. package/src/session-route.ts +40 -0
  176. package/src/setup-core.ts +162 -0
  177. package/src/setup-surface.test.ts +175 -0
  178. package/src/setup-surface.ts +319 -0
  179. package/src/sso-token-store.test.ts +74 -0
  180. package/src/sso-token-store.ts +166 -0
  181. package/src/sso.ts +300 -0
  182. package/src/storage.ts +25 -0
  183. package/src/store-fs.ts +42 -0
  184. package/src/streaming-message.test.ts +323 -0
  185. package/src/streaming-message.ts +327 -0
  186. package/src/test-runtime.ts +16 -0
  187. package/src/thread-parent-context.test.ts +224 -0
  188. package/src/thread-parent-context.ts +159 -0
  189. package/src/token-response.ts +11 -0
  190. package/src/token.test.ts +268 -0
  191. package/src/token.ts +194 -0
  192. package/src/user-agent.test.ts +121 -0
  193. package/src/user-agent.ts +53 -0
  194. package/src/webhook-timeouts.ts +27 -0
  195. package/src/welcome-card.test.ts +104 -0
  196. package/src/welcome-card.ts +57 -0
  197. package/test-api.ts +1 -0
  198. package/tsconfig.json +16 -0
  199. package/api.js +0 -7
  200. package/channel-config-api.js +0 -7
  201. package/channel-plugin-api.js +0 -7
  202. package/contract-api.js +0 -7
  203. package/index.js +0 -7
  204. package/runtime-api.js +0 -7
  205. package/secret-contract-api.js +0 -7
  206. package/setup-entry.js +0 -7
  207. package/setup-plugin-api.js +0 -7
  208. package/test-api.js +0 -7
@@ -0,0 +1,4226 @@
1
+ import { A as summarizeMapping, D as resolveDefaultGroupPolicy, E as resolveChannelMediaMaxBytes, M as getMSTeamsRuntime, N as getOptionalMSTeamsRuntime, _ as isDangerousNameMatchingEnabled, a as buildMediaPayload, b as logTypingFailure, c as createChannelMessageReplyPipeline, f as dispatchReplyFromConfigWithSettledDispatcher$1, l as createChannelPairingController, n as DEFAULT_WEBHOOK_MAX_BODY_BYTES, t as DEFAULT_ACCOUNT_ID, v as keepHttpServerTaskAlive, x as mergeAllowlist } from "./runtime-api-BL4DOWXD.js";
2
+ import { A as ATTACHMENT_TAG_RE, B as isLikelyImageAttachment, C as loadMSTeamsSdkWithAuth, D as formatMSTeamsSendErrorHint, E as classifyMSTeamsSendError, F as estimateBase64DecodedBytes, G as resolveAttachmentFetchPolicy, H as isUrlAllowed, I as extractHtmlFromAttachment, J as safeFetchWithPolicy, K as resolveMediaSsrfPolicy, L as extractInlineImageCandidates, M as IMG_SRC_RE, N as applyAuthorizationHeaderForUrl, O as formatUnknownError, P as encodeGraphShareId, R as inferPlaceholder, S as createMSTeamsTokenProvider, T as ensureUserAgentHeader, U as normalizeContentType, V as isRecord$1, W as readNestedString, X as tryBuildGraphSharesUrlForSharedLink, Y as safeHostForUrl, _ as resolveMSTeamsStorePath, a as fetchGraphJson, b as createBotFrameworkJwtValidator, h as resolveMSTeamsCredentials, j as GRAPH_ROOT, q as resolveRequestUrl, w as buildUserAgent, x as createMSTeamsAdapter, z as isDownloadableAttachment } from "./graph-users-D-gKCguI.js";
3
+ import { d as resolveMSTeamsUserAllowlist, u as resolveMSTeamsChannelAllowlist } from "./setup-surface-COTQDcTQ.js";
4
+ import { a as resolveMSTeamsReplyPolicy, i as resolveMSTeamsAllowlistMatch, o as resolveMSTeamsRouteConfig } from "./channel-BvTXHuGs.js";
5
+ import { C as readJsonFile, S as createMSTeamsConversationStoreFs, T as writeJsonFile, _ as buildFileInfoCard, b as createMSTeamsPollStoreFs, c as renderReplyPayloadsToMessages, d as withRevokedProxyFallback, f as resolveGraphChatId, g as removePendingUploadFs, h as getPendingUploadFs, l as sendMSTeamsMessages, m as removePendingUpload, p as getPendingUpload, s as buildConversationReference, u as AI_GENERATED_ENTITY, v as parseFileConsentInvoke, w as withFileLock, x as extractMSTeamsPollVote, y as uploadToConsentUrl } from "./probe-Cj2KsAGF.js";
6
+ import { formatAllowlistMatchMeta } from "klaw/plugin-sdk/allow-from";
7
+ import { createLiveMessageState, createPreviewMessageReceipt, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, markLiveMessageFinalized } from "klaw/plugin-sdk/channel-message";
8
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalLowercaseString, normalizeOptionalString, readStringValue } from "klaw/plugin-sdk/string-coerce-runtime";
9
+ import { createDraftStreamLoop } from "klaw/plugin-sdk/channel-lifecycle";
10
+ import { saveResponseMedia } from "klaw/plugin-sdk/media-runtime";
11
+ import { dispatchReplyFromConfigWithSettledDispatcher, hasFinalInboundReplyDispatch, resolveInboundReplyDispatchCounts } from "klaw/plugin-sdk/inbound-reply-dispatch";
12
+ import { fetchWithSsrFGuard } from "klaw/plugin-sdk/ssrf-runtime";
13
+ import path from "node:path";
14
+ import { appendRegularFile } from "klaw/plugin-sdk/security-runtime";
15
+ import { writeJsonFileAtomically } from "klaw/plugin-sdk/json-store";
16
+ import { resolveThreadSessionKeys } from "klaw/plugin-sdk/routing";
17
+ import fs from "node:fs/promises";
18
+ import { channelIngressRoutes, resolveStableChannelMessageIngress } from "klaw/plugin-sdk/channel-ingress-runtime";
19
+ import { logInboundDrop, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContext } from "klaw/plugin-sdk/channel-inbound";
20
+ import { filterSupplementalContextItems, resolveChannelContextVisibilityMode, shouldIncludeSupplementalContext } from "klaw/plugin-sdk/context-visibility-runtime";
21
+ import { DEFAULT_GROUP_HISTORY_LIMIT, createChannelHistoryWindow } from "klaw/plugin-sdk/reply-history";
22
+ import { buildChannelProgressDraftLine, buildChannelProgressDraftLineForEntry, createChannelProgressDraftGate, formatChannelProgressDraftText, isChannelProgressDraftWorkToolName, mergeChannelProgressDraftLine, normalizeChannelProgressDraftLineIdentity, resolveChannelPreviewStreamMode, resolveChannelProgressDraftMaxLines, resolveChannelStreamingBlockEnabled, resolveChannelStreamingPreviewToolProgress } from "klaw/plugin-sdk/channel-streaming";
23
+ //#region extensions/msteams/src/feedback-reflection-prompt.ts
24
+ /** Max chars of the thumbed-down response to include in the reflection prompt. */
25
+ const MAX_RESPONSE_CHARS = 500;
26
+ function buildReflectionPrompt(params) {
27
+ const parts = ["A user indicated your previous response wasn't helpful."];
28
+ if (params.thumbedDownResponse) {
29
+ const truncated = params.thumbedDownResponse.length > MAX_RESPONSE_CHARS ? `${params.thumbedDownResponse.slice(0, MAX_RESPONSE_CHARS)}...` : params.thumbedDownResponse;
30
+ parts.push(`\nYour response was:\n> ${truncated}`);
31
+ }
32
+ if (params.userComment) parts.push(`\nUser's comment: "${params.userComment}"`);
33
+ parts.push("\nBriefly reflect: what could you improve? Consider tone, length, accuracy, relevance, and specificity. Reply with a single JSON object only, no markdown or prose, using this exact shape:\n{\"learning\":\"...\",\"followUp\":false,\"userMessage\":\"\"}\n- learning: a short internal adjustment note (1-2 sentences) for your future behavior in this conversation.\n- followUp: true only if the user needs a direct follow-up message.\n- userMessage: only the exact user-facing message to send; empty string when followUp is false.");
34
+ return parts.join("\n");
35
+ }
36
+ function parseBooleanLike(value) {
37
+ if (typeof value === "boolean") return value;
38
+ if (typeof value === "string") {
39
+ const normalized = normalizeOptionalLowercaseString(value);
40
+ if (normalized === "true" || normalized === "yes") return true;
41
+ if (normalized === "false" || normalized === "no") return false;
42
+ }
43
+ }
44
+ function parseStructuredReflectionValue(value) {
45
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return null;
46
+ const candidate = value;
47
+ const learning = typeof candidate.learning === "string" ? candidate.learning.trim() : void 0;
48
+ if (!learning) return null;
49
+ return {
50
+ learning,
51
+ followUp: parseBooleanLike(candidate.followUp) ?? false,
52
+ userMessage: typeof candidate.userMessage === "string" && candidate.userMessage.trim() ? candidate.userMessage.trim() : void 0
53
+ };
54
+ }
55
+ function parseReflectionResponse(text) {
56
+ const trimmed = text.trim();
57
+ if (!trimmed) return null;
58
+ const candidates = [trimmed, ...trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i)?.slice(1, 2) ?? []];
59
+ for (const candidateText of candidates) {
60
+ const candidate = candidateText.trim();
61
+ if (!candidate) continue;
62
+ try {
63
+ const parsed = parseStructuredReflectionValue(JSON.parse(candidate));
64
+ if (parsed) return parsed;
65
+ } catch {}
66
+ }
67
+ return {
68
+ learning: trimmed,
69
+ followUp: false
70
+ };
71
+ }
72
+ /** Tracks last reflection time per session to enforce cooldown. */
73
+ const lastReflectionBySession = /* @__PURE__ */ new Map();
74
+ /** Maximum cooldown entries before pruning expired ones. */
75
+ const MAX_COOLDOWN_ENTRIES = 500;
76
+ function legacySanitizeSessionKey(sessionKey) {
77
+ return sessionKey.replace(/[^a-zA-Z0-9_-]/g, "_");
78
+ }
79
+ function encodeSessionKey(sessionKey) {
80
+ return Buffer.from(sessionKey, "utf8").toString("base64url");
81
+ }
82
+ function resolveLearningsFilePath(storePath, sessionKey) {
83
+ return `${storePath}/${encodeSessionKey(sessionKey)}.learnings.json`;
84
+ }
85
+ function resolveLegacyLearningsFilePath(storePath, sessionKey) {
86
+ return `${storePath}/${legacySanitizeSessionKey(sessionKey)}.learnings.json`;
87
+ }
88
+ async function readLearningsFile(filePath) {
89
+ try {
90
+ const content = await fs.readFile(filePath, "utf-8");
91
+ const parsed = JSON.parse(content);
92
+ return {
93
+ exists: true,
94
+ learnings: Array.isArray(parsed) ? parsed : []
95
+ };
96
+ } catch {
97
+ return {
98
+ exists: false,
99
+ learnings: []
100
+ };
101
+ }
102
+ }
103
+ /** Prune expired cooldown entries to prevent unbounded memory growth. */
104
+ function pruneExpiredCooldowns(cooldownMs) {
105
+ if (lastReflectionBySession.size <= MAX_COOLDOWN_ENTRIES) return;
106
+ const now = Date.now();
107
+ for (const [key, time] of lastReflectionBySession) if (now - time >= cooldownMs) lastReflectionBySession.delete(key);
108
+ }
109
+ /** Check if a reflection is allowed (cooldown not active). */
110
+ function isReflectionAllowed(sessionKey, cooldownMs) {
111
+ const cooldown = cooldownMs ?? 3e5;
112
+ const lastTime = lastReflectionBySession.get(sessionKey);
113
+ if (lastTime == null) return true;
114
+ return Date.now() - lastTime >= cooldown;
115
+ }
116
+ /** Record that a reflection was run for a session. */
117
+ function recordReflectionTime(sessionKey, cooldownMs) {
118
+ lastReflectionBySession.set(sessionKey, Date.now());
119
+ pruneExpiredCooldowns(cooldownMs ?? 3e5);
120
+ }
121
+ /** Store a learning derived from feedback reflection in a session companion file. */
122
+ async function storeSessionLearning(params) {
123
+ const learningsFile = resolveLearningsFilePath(params.storePath, params.sessionKey);
124
+ const legacyLearningsFile = resolveLegacyLearningsFilePath(params.storePath, params.sessionKey);
125
+ const { exists, learnings: existingLearnings } = await readLearningsFile(learningsFile);
126
+ const { learnings: legacyLearnings } = exists || legacyLearningsFile === learningsFile ? { learnings: [] } : await readLearningsFile(legacyLearningsFile);
127
+ let learnings = exists ? existingLearnings : legacyLearnings;
128
+ learnings.push(params.learning);
129
+ if (learnings.length > 10) learnings = learnings.slice(-10);
130
+ await writeJsonFileAtomically(learningsFile, learnings);
131
+ if (!exists && legacyLearningsFile !== learningsFile) await fs.rm(legacyLearningsFile, { force: true }).catch(() => void 0);
132
+ }
133
+ //#endregion
134
+ //#region extensions/msteams/src/feedback-reflection.ts
135
+ function buildFeedbackEvent(params) {
136
+ return {
137
+ type: "custom",
138
+ event: "feedback",
139
+ ts: Date.now(),
140
+ messageId: params.messageId,
141
+ value: params.value,
142
+ comment: params.comment,
143
+ sessionKey: params.sessionKey,
144
+ agentId: params.agentId,
145
+ conversationId: params.conversationId
146
+ };
147
+ }
148
+ function buildReflectionContext(params) {
149
+ const core = getMSTeamsRuntime();
150
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(params.cfg);
151
+ const body = core.channel.reply.formatAgentEnvelope({
152
+ channel: "Teams",
153
+ from: "system",
154
+ body: params.reflectionPrompt,
155
+ envelope: envelopeOptions
156
+ });
157
+ return { ctxPayload: core.channel.reply.finalizeInboundContext({
158
+ Body: body,
159
+ BodyForAgent: params.reflectionPrompt,
160
+ RawBody: params.reflectionPrompt,
161
+ CommandBody: params.reflectionPrompt,
162
+ From: `msteams:system:${params.conversationId}`,
163
+ To: `conversation:${params.conversationId}`,
164
+ SessionKey: params.sessionKey,
165
+ ChatType: "direct",
166
+ SenderName: "system",
167
+ SenderId: "system",
168
+ Provider: "msteams",
169
+ Surface: "msteams",
170
+ Timestamp: Date.now(),
171
+ WasMentioned: true,
172
+ CommandAuthorized: false,
173
+ OriginatingChannel: "msteams",
174
+ OriginatingTo: `conversation:${params.conversationId}`
175
+ }) };
176
+ }
177
+ function createReflectionCaptureDispatcher(params) {
178
+ const core = getMSTeamsRuntime();
179
+ let response = "";
180
+ const { dispatcher, replyOptions } = core.channel.reply.createReplyDispatcherWithTyping({
181
+ deliver: async (payload) => {
182
+ if (payload.text) response += (response ? "\n" : "") + payload.text;
183
+ },
184
+ typingCallbacks: {
185
+ onReplyStart: async () => {},
186
+ onIdle: () => {},
187
+ onCleanup: () => {}
188
+ },
189
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(params.cfg, params.agentId),
190
+ onError: (err) => {
191
+ params.log.debug?.("reflection reply error", { error: formatUnknownError(err) });
192
+ }
193
+ });
194
+ return {
195
+ dispatcher,
196
+ replyOptions,
197
+ readResponse: () => response
198
+ };
199
+ }
200
+ async function sendReflectionFollowUp(params) {
201
+ const proactiveRef = {
202
+ ...buildConversationReference(params.conversationRef),
203
+ activityId: void 0
204
+ };
205
+ await params.adapter.continueConversation(params.appId, proactiveRef, async (ctx) => {
206
+ await ctx.sendActivity({
207
+ type: "message",
208
+ text: params.userMessage
209
+ });
210
+ });
211
+ }
212
+ /**
213
+ * Run a background reflection after negative feedback.
214
+ * This is designed to be called fire-and-forget (don't await in the invoke handler).
215
+ */
216
+ async function runFeedbackReflection(params) {
217
+ const { cfg, log, sessionKey } = params;
218
+ const cooldownMs = cfg.channels?.msteams?.feedbackReflectionCooldownMs ?? 3e5;
219
+ if (!isReflectionAllowed(sessionKey, cooldownMs)) {
220
+ log.debug?.("skipping reflection (cooldown active)", { sessionKey });
221
+ return;
222
+ }
223
+ const reflectionPrompt = buildReflectionPrompt({
224
+ thumbedDownResponse: params.thumbedDownResponse,
225
+ userComment: params.userComment
226
+ });
227
+ const storePath = getMSTeamsRuntime().channel.session.resolveStorePath(cfg.session?.store, { agentId: params.agentId });
228
+ const { ctxPayload } = buildReflectionContext({
229
+ cfg,
230
+ conversationId: params.conversationId,
231
+ sessionKey: params.sessionKey,
232
+ reflectionPrompt
233
+ });
234
+ const capture = createReflectionCaptureDispatcher({
235
+ cfg,
236
+ agentId: params.agentId,
237
+ log
238
+ });
239
+ try {
240
+ await dispatchReplyFromConfigWithSettledDispatcher$1({
241
+ ctxPayload,
242
+ cfg,
243
+ dispatcher: capture.dispatcher,
244
+ onSettled: () => {},
245
+ replyOptions: capture.replyOptions
246
+ });
247
+ } catch (err) {
248
+ log.error("reflection dispatch failed", { error: formatUnknownError(err) });
249
+ return;
250
+ }
251
+ const reflectionResponse = capture.readResponse().trim();
252
+ if (!reflectionResponse) {
253
+ log.debug?.("reflection produced no output");
254
+ return;
255
+ }
256
+ const parsedReflection = parseReflectionResponse(reflectionResponse);
257
+ if (!parsedReflection) {
258
+ log.debug?.("reflection produced no structured output");
259
+ return;
260
+ }
261
+ recordReflectionTime(sessionKey, cooldownMs);
262
+ log.info("reflection complete", {
263
+ sessionKey,
264
+ responseLength: reflectionResponse.length,
265
+ followUp: parsedReflection.followUp
266
+ });
267
+ try {
268
+ await storeSessionLearning({
269
+ storePath,
270
+ sessionKey: params.sessionKey,
271
+ learning: parsedReflection.learning
272
+ });
273
+ } catch (err) {
274
+ log.debug?.("failed to store reflection learning", { error: formatUnknownError(err) });
275
+ }
276
+ const conversationType = normalizeOptionalLowercaseString(params.conversationRef.conversation?.conversationType);
277
+ if (!(conversationType === "personal" && parsedReflection.followUp && Boolean(parsedReflection.userMessage))) {
278
+ if (parsedReflection.followUp && conversationType !== "personal") log.debug?.("skipping reflection follow-up outside direct message", {
279
+ sessionKey,
280
+ conversationType
281
+ });
282
+ return;
283
+ }
284
+ try {
285
+ await sendReflectionFollowUp({
286
+ adapter: params.adapter,
287
+ appId: params.appId,
288
+ conversationRef: params.conversationRef,
289
+ userMessage: parsedReflection.userMessage
290
+ });
291
+ log.info("sent reflection follow-up", { sessionKey });
292
+ } catch (err) {
293
+ log.debug?.("failed to send reflection follow-up", { error: formatUnknownError(err) });
294
+ }
295
+ }
296
+ //#endregion
297
+ //#region extensions/msteams/src/inbound.ts
298
+ /**
299
+ * Decode common HTML entities to plain text.
300
+ */
301
+ function decodeHtmlEntities(html) {
302
+ return html.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&#x27;/g, "'").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&");
303
+ }
304
+ /**
305
+ * Strip HTML tags, preserving text content.
306
+ */
307
+ function htmlToPlainText(html) {
308
+ return decodeHtmlEntities(html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim());
309
+ }
310
+ /**
311
+ * Extract quote info from MS Teams HTML reply attachments.
312
+ * Teams wraps quoted content in a blockquote with itemtype="http://schema.skype.com/Reply".
313
+ */
314
+ function extractMSTeamsQuoteInfo(attachments) {
315
+ for (const att of attachments) {
316
+ let content = "";
317
+ if (typeof att.content === "string") content = att.content;
318
+ else if (typeof att.content === "object" && att.content !== null) {
319
+ const record = att.content;
320
+ content = typeof record.text === "string" ? record.text : typeof record.body === "string" ? record.body : "";
321
+ }
322
+ if (!content) continue;
323
+ if (!content.includes("http://schema.skype.com/Reply")) continue;
324
+ const senderMatch = /<strong[^>]*itemprop=["']mri["'][^>]*>(.*?)<\/strong>/i.exec(content);
325
+ const sender = senderMatch?.[1] ? htmlToPlainText(senderMatch[1]) : void 0;
326
+ const bodyMatch = /<p[^>]*itemprop=["']copy["'][^>]*>(.*?)<\/p>/is.exec(content);
327
+ const body = bodyMatch?.[1] ? htmlToPlainText(bodyMatch[1]) : void 0;
328
+ if (body) return {
329
+ sender: sender ?? "unknown",
330
+ body
331
+ };
332
+ }
333
+ }
334
+ function normalizeMSTeamsConversationId(raw) {
335
+ return raw.split(";")[0] ?? raw;
336
+ }
337
+ function extractMSTeamsConversationMessageId(raw) {
338
+ if (!raw) return;
339
+ return (/(?:^|;)messageid=([^;]+)/i.exec(raw)?.[1]?.trim() ?? "") || void 0;
340
+ }
341
+ function parseMSTeamsActivityTimestamp(value) {
342
+ if (!value) return;
343
+ if (value instanceof Date) return value;
344
+ if (typeof value !== "string") return;
345
+ const date = new Date(value);
346
+ return Number.isNaN(date.getTime()) ? void 0 : date;
347
+ }
348
+ function stripMSTeamsMentionTags(text) {
349
+ return text.replace(/<at[^>]*>.*?<\/at>/gi, "").trim();
350
+ }
351
+ /**
352
+ * Bot Framework uses 'a:xxx' conversation IDs for personal chats, but Graph API
353
+ * requires the '19:{userId}_{botAppId}@unq.gbl.spaces' format.
354
+ *
355
+ * This is the documented Graph API format for 1:1 chat thread IDs between a user
356
+ * and a bot/app. See Microsoft docs "Get chat between user and app":
357
+ * https://learn.microsoft.com/en-us/graph/api/userscopeteamsappinstallation-get-chat
358
+ *
359
+ * The format is only synthesized when the Bot Framework conversation ID starts with
360
+ * 'a:' (the opaque format used by BF but not recognized by Graph). If the ID already
361
+ * has the '19:...' Graph format, it is passed through unchanged.
362
+ */
363
+ function translateMSTeamsDmConversationIdForGraph(params) {
364
+ const { isDirectMessage, conversationId, aadObjectId, appId } = params;
365
+ return isDirectMessage && conversationId.startsWith("a:") && aadObjectId && appId ? `19:${aadObjectId}_${appId}@unq.gbl.spaces` : conversationId;
366
+ }
367
+ function wasMSTeamsBotMentioned(activity) {
368
+ const botId = activity.recipient?.id;
369
+ if (!botId) return false;
370
+ return (activity.entities ?? []).some((e) => e.type === "mention" && e.mentioned?.id === botId);
371
+ }
372
+ //#endregion
373
+ //#region extensions/msteams/src/file-consent-invoke.ts
374
+ /**
375
+ * Handle fileConsent/invoke activities for large file uploads.
376
+ */
377
+ async function handleMSTeamsFileConsentInvoke(context, log) {
378
+ const expiredUploadMessage = "The file upload request has expired. Please try sending the file again.";
379
+ const activity = context.activity;
380
+ if (activity.type !== "invoke" || activity.name !== "fileConsent/invoke") return false;
381
+ const consentResponse = parseFileConsentInvoke(activity);
382
+ if (!consentResponse) {
383
+ log.debug?.("invalid file consent invoke", { value: activity.value });
384
+ return false;
385
+ }
386
+ const uploadId = typeof consentResponse.context?.uploadId === "string" ? consentResponse.context.uploadId : void 0;
387
+ const inMemoryFile = getPendingUpload(uploadId);
388
+ const fsFile = inMemoryFile ? void 0 : await getPendingUploadFs(uploadId);
389
+ const pendingFile = inMemoryFile ?? fsFile;
390
+ if (pendingFile) {
391
+ const pendingConversationId = normalizeMSTeamsConversationId(pendingFile.conversationId);
392
+ const invokeConversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "");
393
+ if (!invokeConversationId || pendingConversationId !== invokeConversationId) {
394
+ log.info("file consent conversation mismatch", {
395
+ uploadId,
396
+ expectedConversationId: pendingConversationId,
397
+ receivedConversationId: invokeConversationId || void 0
398
+ });
399
+ if (consentResponse.action === "accept") await context.sendActivity(expiredUploadMessage);
400
+ return true;
401
+ }
402
+ }
403
+ if (consentResponse.action === "accept" && consentResponse.uploadInfo) if (pendingFile) {
404
+ log.debug?.("user accepted file consent, uploading", {
405
+ uploadId,
406
+ filename: pendingFile.filename,
407
+ size: pendingFile.buffer.length
408
+ });
409
+ try {
410
+ await uploadToConsentUrl({
411
+ url: consentResponse.uploadInfo.uploadUrl,
412
+ buffer: pendingFile.buffer,
413
+ contentType: pendingFile.contentType
414
+ });
415
+ const fileInfoCard = buildFileInfoCard({
416
+ filename: consentResponse.uploadInfo.name,
417
+ contentUrl: consentResponse.uploadInfo.contentUrl,
418
+ uniqueId: consentResponse.uploadInfo.uniqueId,
419
+ fileType: consentResponse.uploadInfo.fileType
420
+ });
421
+ if (!pendingFile.consentCardActivityId) await context.sendActivity({
422
+ type: "message",
423
+ attachments: [fileInfoCard]
424
+ });
425
+ if (pendingFile.consentCardActivityId) try {
426
+ await context.updateActivity({
427
+ id: pendingFile.consentCardActivityId,
428
+ type: "message",
429
+ attachments: [fileInfoCard]
430
+ });
431
+ } catch {
432
+ await context.sendActivity({
433
+ type: "message",
434
+ attachments: [fileInfoCard]
435
+ });
436
+ }
437
+ log.info("file upload complete", {
438
+ uploadId,
439
+ filename: consentResponse.uploadInfo.name,
440
+ uniqueId: consentResponse.uploadInfo.uniqueId
441
+ });
442
+ } catch (err) {
443
+ log.error("file upload failed", {
444
+ uploadId,
445
+ error: formatUnknownError(err)
446
+ });
447
+ await context.sendActivity("File upload failed. Please try again.");
448
+ } finally {
449
+ removePendingUpload(uploadId);
450
+ await removePendingUploadFs(uploadId);
451
+ }
452
+ } else {
453
+ log.debug?.("pending file not found for consent", { uploadId });
454
+ await context.sendActivity(expiredUploadMessage);
455
+ }
456
+ else {
457
+ log.debug?.("user declined file consent", { uploadId });
458
+ removePendingUpload(uploadId);
459
+ await removePendingUploadFs(uploadId);
460
+ }
461
+ return true;
462
+ }
463
+ async function respondToMSTeamsFileConsentInvoke(context, log) {
464
+ await context.sendActivity({
465
+ type: "invokeResponse",
466
+ value: { status: 200 }
467
+ });
468
+ try {
469
+ await withRevokedProxyFallback({
470
+ run: async () => await handleMSTeamsFileConsentInvoke(context, log),
471
+ onRevoked: async () => true,
472
+ onRevokedLog: () => {
473
+ log.debug?.("turn context revoked during file consent invoke; skipping delayed response");
474
+ }
475
+ });
476
+ } catch (err) {
477
+ log.debug?.("file consent handler error", { error: formatUnknownError(err) });
478
+ }
479
+ }
480
+ //#endregion
481
+ //#region extensions/msteams/src/monitor-handler/access.ts
482
+ const msteamsIngressIdentity = {
483
+ key: "sender-id",
484
+ normalize: normalizeIngressValue,
485
+ aliases: [{
486
+ key: "sender-name",
487
+ kind: "plugin:msteams-sender-name",
488
+ normalizeEntry: normalizeIngressValue,
489
+ normalizeSubject: normalizeIngressValue,
490
+ dangerous: true
491
+ }],
492
+ isWildcardEntry: (entry) => normalizeIngressValue(entry) === "*",
493
+ resolveEntryId: ({ entryIndex, fieldKey }) => `msteams-entry-${entryIndex + 1}:${fieldKey === "sender-name" ? "name" : "id"}`
494
+ };
495
+ function normalizeIngressValue(value) {
496
+ return normalizeOptionalLowercaseString(value) ?? null;
497
+ }
498
+ async function resolveMSTeamsSenderAccess(params) {
499
+ const activity = params.activity;
500
+ const msteamsCfg = params.cfg.channels?.msteams;
501
+ const conversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "unknown");
502
+ const convType = normalizeOptionalLowercaseString(activity.conversation?.conversationType);
503
+ const isDirectMessage = convType === "personal" || !convType && !activity.conversation?.isGroup;
504
+ const senderId = activity.from?.aadObjectId ?? activity.from?.id ?? "unknown";
505
+ const senderName = activity.from?.name ?? activity.from?.id ?? senderId;
506
+ const pairing = createChannelPairingController({
507
+ core: getMSTeamsRuntime(),
508
+ channel: "msteams",
509
+ accountId: DEFAULT_ACCOUNT_ID
510
+ });
511
+ const dmPolicy = msteamsCfg?.dmPolicy ?? "pairing";
512
+ const configuredDmAllowFrom = msteamsCfg?.allowFrom ?? [];
513
+ const groupAllowFrom = msteamsCfg?.groupAllowFrom;
514
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(params.cfg);
515
+ const groupPolicy = !isDirectMessage && msteamsCfg ? msteamsCfg.groupPolicy ?? defaultGroupPolicy ?? "allowlist" : "disabled";
516
+ const allowNameMatching = isDangerousNameMatchingEnabled(msteamsCfg);
517
+ const channelGate = resolveMSTeamsRouteConfig({
518
+ cfg: msteamsCfg,
519
+ teamId: activity.channelData?.team?.id,
520
+ teamName: activity.channelData?.team?.name,
521
+ conversationId,
522
+ channelName: activity.channelData?.channel?.name,
523
+ allowNameMatching
524
+ });
525
+ return {
526
+ ...await resolveStableChannelMessageIngress({
527
+ channelId: "msteams",
528
+ accountId: pairing.accountId,
529
+ identity: msteamsIngressIdentity,
530
+ cfg: params.cfg,
531
+ readStoreAllowFrom: pairing.readAllowFromStore,
532
+ subject: {
533
+ stableId: senderId,
534
+ aliases: { "sender-name": senderName }
535
+ },
536
+ conversation: {
537
+ kind: isDirectMessage ? "direct" : convType === "channel" ? "channel" : "group",
538
+ id: conversationId,
539
+ parentId: activity.channelData?.team?.id
540
+ },
541
+ route: channelIngressRoutes(!isDirectMessage && channelGate.allowlistConfigured && {
542
+ id: "msteams:team-channel",
543
+ kind: "nestedAllowlist",
544
+ allowed: channelGate.allowed,
545
+ precedence: 0,
546
+ matchId: "msteams-route",
547
+ ...channelGate.allowed && groupPolicy === "allowlist" ? {
548
+ senderPolicy: "deny-when-empty",
549
+ senderAllowFromSource: "effective-group"
550
+ } : {}
551
+ }),
552
+ dmPolicy,
553
+ groupPolicy,
554
+ policy: {
555
+ groupAllowFromFallbackToAllowFrom: true,
556
+ mutableIdentifierMatching: allowNameMatching ? "enabled" : "disabled"
557
+ },
558
+ allowFrom: configuredDmAllowFrom,
559
+ groupAllowFrom,
560
+ command: {
561
+ allowTextCommands: true,
562
+ hasControlCommand: params.hasControlCommand === true,
563
+ directGroupAllowFrom: isDirectMessage ? "effective" : "none"
564
+ }
565
+ }),
566
+ pairing,
567
+ isDirectMessage,
568
+ conversationId,
569
+ senderId,
570
+ senderName,
571
+ msteamsCfg,
572
+ dmPolicy,
573
+ channelGate,
574
+ allowNameMatching,
575
+ groupPolicy
576
+ };
577
+ }
578
+ //#endregion
579
+ //#region extensions/msteams/src/attachments/bot-framework.ts
580
+ /**
581
+ * Bot Framework Service token scope for requesting a token used against
582
+ * the Bot Connector (v3) REST endpoints such as `/v3/attachments/{id}`.
583
+ */
584
+ const BOT_FRAMEWORK_SCOPE = "https://api.botframework.com";
585
+ /**
586
+ * Detect Bot Framework personal chat ("a:") and MSA orgid ("8:orgid:") conversation
587
+ * IDs. These identifiers are not recognized by Graph's `/chats/{id}` endpoint, so we
588
+ * must fetch media via the Bot Framework v3 attachments endpoint instead.
589
+ *
590
+ * Graph-compatible IDs start with `19:` and are left untouched by this detector.
591
+ */
592
+ function isBotFrameworkPersonalChatId(conversationId) {
593
+ if (typeof conversationId !== "string") return false;
594
+ const trimmed = conversationId.trim();
595
+ return trimmed.startsWith("a:") || trimmed.startsWith("8:orgid:");
596
+ }
597
+ function normalizeServiceUrl(serviceUrl) {
598
+ return serviceUrl.replace(/\/+$/, "");
599
+ }
600
+ async function fetchBotFrameworkAttachmentInfo(params) {
601
+ const url = `${normalizeServiceUrl(params.serviceUrl)}/v3/attachments/${encodeURIComponent(params.attachmentId)}`;
602
+ let response;
603
+ try {
604
+ response = await safeFetchWithPolicy({
605
+ url,
606
+ policy: params.policy,
607
+ fetchFn: params.fetchFn,
608
+ resolveFn: params.resolveFn,
609
+ requestInit: { headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }) }
610
+ });
611
+ } catch (err) {
612
+ params.logger?.warn?.("msteams botFramework attachmentInfo fetch failed", { error: err instanceof Error ? err.message : String(err) });
613
+ return;
614
+ }
615
+ if (!response.ok) {
616
+ params.logger?.warn?.("msteams botFramework attachmentInfo non-ok", { status: response.status });
617
+ return;
618
+ }
619
+ try {
620
+ return await response.json();
621
+ } catch (err) {
622
+ params.logger?.warn?.("msteams botFramework attachmentInfo parse failed", { error: err instanceof Error ? err.message : String(err) });
623
+ return;
624
+ }
625
+ }
626
+ async function saveBotFrameworkAttachmentView(params) {
627
+ const url = `${normalizeServiceUrl(params.serviceUrl)}/v3/attachments/${encodeURIComponent(params.attachmentId)}/views/${encodeURIComponent(params.viewId)}`;
628
+ let response;
629
+ try {
630
+ response = await safeFetchWithPolicy({
631
+ url,
632
+ policy: params.policy,
633
+ fetchFn: params.fetchFn,
634
+ resolveFn: params.resolveFn,
635
+ requestInit: { headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }) }
636
+ });
637
+ } catch (err) {
638
+ params.logger?.warn?.("msteams botFramework attachmentView fetch failed", { error: err instanceof Error ? err.message : String(err) });
639
+ return;
640
+ }
641
+ if (!response.ok) {
642
+ params.logger?.warn?.("msteams botFramework attachmentView non-ok", { status: response.status });
643
+ return;
644
+ }
645
+ const contentLength = response.headers.get("content-length");
646
+ if (contentLength && Number(contentLength) > params.maxBytes) return;
647
+ try {
648
+ return await getMSTeamsRuntime().channel.media.saveResponseMedia(response, {
649
+ sourceUrl: url,
650
+ filePathHint: params.fileNameHint,
651
+ maxBytes: params.maxBytes,
652
+ fallbackContentType: params.contentTypeHint,
653
+ subdir: "inbound",
654
+ originalFilename: params.preserveFilenames ? params.fileNameHint : void 0
655
+ });
656
+ } catch (err) {
657
+ params.logger?.warn?.("msteams botFramework attachmentView save failed", { error: err instanceof Error ? err.message : String(err) });
658
+ return;
659
+ }
660
+ }
661
+ /**
662
+ * Download media for a single attachment via the Bot Framework v3 attachments
663
+ * endpoint. Used for personal DM conversations where the Graph `/chats/{id}`
664
+ * path is not usable because the Bot Framework conversation ID (`a:...`) is
665
+ * not a valid Graph chat identifier.
666
+ */
667
+ async function downloadMSTeamsBotFrameworkAttachment(params) {
668
+ if (!params.serviceUrl || !params.attachmentId || !params.tokenProvider) return;
669
+ const policy = resolveAttachmentFetchPolicy({
670
+ allowHosts: params.allowHosts,
671
+ authAllowHosts: params.authAllowHosts
672
+ });
673
+ if (!isUrlAllowed(`${normalizeServiceUrl(params.serviceUrl)}/v3/attachments/${encodeURIComponent(params.attachmentId)}`, policy.allowHosts)) return;
674
+ let accessToken;
675
+ try {
676
+ accessToken = await params.tokenProvider.getAccessToken(BOT_FRAMEWORK_SCOPE);
677
+ } catch (err) {
678
+ params.logger?.warn?.("msteams botFramework token acquisition failed", { error: err instanceof Error ? err.message : String(err) });
679
+ return;
680
+ }
681
+ if (!accessToken) return;
682
+ const info = await fetchBotFrameworkAttachmentInfo({
683
+ serviceUrl: params.serviceUrl,
684
+ attachmentId: params.attachmentId,
685
+ accessToken,
686
+ policy,
687
+ fetchFn: params.fetchFn,
688
+ resolveFn: params.resolveFn,
689
+ logger: params.logger
690
+ });
691
+ if (!info) return;
692
+ const views = Array.isArray(info.views) ? info.views : [];
693
+ const candidateView = views.find((view) => view?.viewId === "original") ?? views.find((view) => typeof view?.viewId === "string");
694
+ const viewId = typeof candidateView?.viewId === "string" && candidateView.viewId ? candidateView.viewId : void 0;
695
+ if (!viewId) return;
696
+ if (typeof candidateView?.size === "number" && candidateView.size > 0 && candidateView.size > params.maxBytes) return;
697
+ const fileNameHint = typeof params.fileNameHint === "string" && params.fileNameHint || typeof info.name === "string" && info.name || void 0;
698
+ const contentTypeHint = typeof params.contentTypeHint === "string" && params.contentTypeHint || typeof info.type === "string" && info.type || void 0;
699
+ const saved = await saveBotFrameworkAttachmentView({
700
+ serviceUrl: params.serviceUrl,
701
+ attachmentId: params.attachmentId,
702
+ viewId,
703
+ accessToken,
704
+ maxBytes: params.maxBytes,
705
+ fileNameHint,
706
+ contentTypeHint,
707
+ preserveFilenames: params.preserveFilenames,
708
+ policy,
709
+ fetchFn: params.fetchFn,
710
+ resolveFn: params.resolveFn,
711
+ logger: params.logger
712
+ });
713
+ if (!saved) return;
714
+ return {
715
+ path: saved.path,
716
+ contentType: saved.contentType,
717
+ placeholder: inferPlaceholder({
718
+ contentType: saved.contentType,
719
+ fileName: fileNameHint
720
+ })
721
+ };
722
+ }
723
+ /**
724
+ * Download media for every attachment referenced by a Bot Framework personal
725
+ * chat activity. Returns all successfully fetched media along with diagnostics
726
+ * compatible with `downloadMSTeamsGraphMedia`'s result shape so callers can
727
+ * reuse the existing logging path.
728
+ */
729
+ async function downloadMSTeamsBotFrameworkAttachments(params) {
730
+ const seen = /* @__PURE__ */ new Set();
731
+ const unique = [];
732
+ for (const id of params.attachmentIds ?? []) {
733
+ if (typeof id !== "string") continue;
734
+ const trimmed = id.trim();
735
+ if (!trimmed || seen.has(trimmed)) continue;
736
+ seen.add(trimmed);
737
+ unique.push(trimmed);
738
+ }
739
+ if (unique.length === 0 || !params.serviceUrl || !params.tokenProvider) return {
740
+ media: [],
741
+ attachmentCount: unique.length
742
+ };
743
+ const media = [];
744
+ for (const attachmentId of unique) try {
745
+ const item = await downloadMSTeamsBotFrameworkAttachment({
746
+ serviceUrl: params.serviceUrl,
747
+ attachmentId,
748
+ tokenProvider: params.tokenProvider,
749
+ maxBytes: params.maxBytes,
750
+ allowHosts: params.allowHosts,
751
+ authAllowHosts: params.authAllowHosts,
752
+ fetchFn: params.fetchFn,
753
+ resolveFn: params.resolveFn,
754
+ fileNameHint: params.fileNameHint,
755
+ contentTypeHint: params.contentTypeHint,
756
+ preserveFilenames: params.preserveFilenames,
757
+ logger: params.logger
758
+ });
759
+ if (item) media.push(item);
760
+ } catch (err) {
761
+ params.logger?.warn?.("msteams botFramework attachment download failed", {
762
+ error: err instanceof Error ? err.message : String(err),
763
+ attachmentId
764
+ });
765
+ }
766
+ return {
767
+ media,
768
+ attachmentCount: unique.length
769
+ };
770
+ }
771
+ //#endregion
772
+ //#region extensions/msteams/src/attachments/remote-media.ts
773
+ /**
774
+ * Direct fetch path used when the caller's `fetchImpl` has already validated
775
+ * the URL against a hostname allowlist (for example `safeFetchWithPolicy`).
776
+ *
777
+ * Bypasses the strict SSRF dispatcher on `readRemoteMediaBuffer` because:
778
+ * 1. The pinned undici dispatcher used by `readRemoteMediaBuffer` is incompatible
779
+ * with Node 24+'s built-in undici v7 (fails with "invalid onRequestStart
780
+ * method"), which silently breaks SharePoint/OneDrive downloads. See
781
+ * issue #63396.
782
+ * 2. SSRF protection is already enforced by the caller's `fetchImpl`
783
+ * (`safeFetch` validates every redirect hop against the hostname
784
+ * allowlist before following).
785
+ */
786
+ async function saveRemoteMediaDirect(params) {
787
+ return await saveResponseMedia(await params.fetchImpl(params.url, { redirect: "follow" }), {
788
+ sourceUrl: params.url,
789
+ filePathHint: params.filePathHint,
790
+ maxBytes: params.maxBytes,
791
+ fallbackContentType: params.contentTypeHint,
792
+ originalFilename: params.originalFilename
793
+ });
794
+ }
795
+ async function downloadAndStoreMSTeamsRemoteMedia(params) {
796
+ const originalFilename = params.preserveFilenames ? params.filePathHint : void 0;
797
+ let saved;
798
+ if (params.useDirectFetch && params.fetchImpl) saved = await saveRemoteMediaDirect({
799
+ url: params.url,
800
+ filePathHint: params.filePathHint,
801
+ fetchImpl: params.fetchImpl,
802
+ maxBytes: params.maxBytes,
803
+ contentTypeHint: params.contentTypeHint,
804
+ originalFilename
805
+ });
806
+ else saved = await getMSTeamsRuntime().channel.media.saveRemoteMedia({
807
+ url: params.url,
808
+ fetchImpl: params.fetchImpl,
809
+ filePathHint: params.filePathHint,
810
+ maxBytes: params.maxBytes,
811
+ ssrfPolicy: params.ssrfPolicy,
812
+ fallbackContentType: params.contentTypeHint,
813
+ originalFilename
814
+ });
815
+ return {
816
+ path: saved.path,
817
+ contentType: saved.contentType,
818
+ placeholder: params.placeholder ?? inferPlaceholder({
819
+ contentType: saved.contentType,
820
+ fileName: params.filePathHint
821
+ })
822
+ };
823
+ }
824
+ //#endregion
825
+ //#region extensions/msteams/src/attachments/download.ts
826
+ function resolveDownloadCandidate(att) {
827
+ const contentType = normalizeContentType(att.contentType);
828
+ const name = normalizeOptionalString(att.name) ?? "";
829
+ if (contentType === "application/vnd.microsoft.teams.file.download.info") {
830
+ if (!isRecord$1(att.content)) return null;
831
+ const downloadUrl = normalizeOptionalString(att.content.downloadUrl) ?? "";
832
+ if (!downloadUrl) return null;
833
+ const fileType = normalizeOptionalString(att.content.fileType) ?? "";
834
+ const uniqueId = normalizeOptionalString(att.content.uniqueId) ?? "";
835
+ const fileName = normalizeOptionalString(att.content.fileName) ?? "";
836
+ const fileHint = name || fileName || (uniqueId && fileType ? `${uniqueId}.${fileType}` : "");
837
+ return {
838
+ url: downloadUrl,
839
+ fileHint: fileHint || void 0,
840
+ contentTypeHint: void 0,
841
+ placeholder: inferPlaceholder({
842
+ contentType,
843
+ fileName: fileHint,
844
+ fileType
845
+ })
846
+ };
847
+ }
848
+ const contentUrl = normalizeOptionalString(att.contentUrl) ?? "";
849
+ if (!contentUrl) return null;
850
+ const sharesUrl = tryBuildGraphSharesUrlForSharedLink(contentUrl);
851
+ return {
852
+ url: sharesUrl ?? contentUrl,
853
+ fileHint: name || void 0,
854
+ contentTypeHint: sharesUrl ? void 0 : contentType,
855
+ placeholder: inferPlaceholder({
856
+ contentType,
857
+ fileName: name
858
+ })
859
+ };
860
+ }
861
+ function scopeCandidatesForUrl(url) {
862
+ try {
863
+ const host = normalizeLowercaseStringOrEmpty(new URL(url).hostname);
864
+ return host.endsWith("graph.microsoft.com") || host.endsWith("sharepoint.com") || host.endsWith("1drv.ms") || host.includes("sharepoint") ? ["https://graph.microsoft.com", "https://api.botframework.com"] : ["https://api.botframework.com", "https://graph.microsoft.com"];
865
+ } catch {
866
+ return ["https://api.botframework.com", "https://graph.microsoft.com"];
867
+ }
868
+ }
869
+ function isRedirectStatus(status) {
870
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
871
+ }
872
+ async function resolveInlineDataImageMime(inline) {
873
+ const mime = normalizeOptionalLowercaseString(await getMSTeamsRuntime().media.detectMime({
874
+ buffer: inline.data,
875
+ headerMime: inline.contentType
876
+ }) ?? inline.contentType);
877
+ return mime?.startsWith("image/") ? mime : void 0;
878
+ }
879
+ async function fetchWithAuthFallback(params) {
880
+ const firstAttempt = await safeFetchWithPolicy({
881
+ url: params.url,
882
+ policy: params.policy,
883
+ fetchFn: params.fetchFn,
884
+ requestInit: params.requestInit,
885
+ resolveFn: params.resolveFn
886
+ });
887
+ if (firstAttempt.ok) return firstAttempt;
888
+ if (!params.tokenProvider) return firstAttempt;
889
+ if (firstAttempt.status !== 401 && firstAttempt.status !== 403) return firstAttempt;
890
+ if (!isUrlAllowed(params.url, params.policy.authAllowHosts)) return firstAttempt;
891
+ const scopes = scopeCandidatesForUrl(params.url);
892
+ const fetchFn = params.fetchFn ?? fetch;
893
+ for (const scope of scopes) try {
894
+ const token = await params.tokenProvider.getAccessToken(scope);
895
+ const authHeaders = new Headers(params.requestInit?.headers);
896
+ authHeaders.set("Authorization", `Bearer ${token}`);
897
+ const authAttempt = await safeFetchWithPolicy({
898
+ url: params.url,
899
+ policy: params.policy,
900
+ fetchFn,
901
+ requestInit: {
902
+ ...params.requestInit,
903
+ headers: authHeaders
904
+ },
905
+ resolveFn: params.resolveFn
906
+ });
907
+ if (authAttempt.ok) return authAttempt;
908
+ if (isRedirectStatus(authAttempt.status)) return authAttempt;
909
+ if (authAttempt.status !== 401 && authAttempt.status !== 403) continue;
910
+ } catch {}
911
+ return firstAttempt;
912
+ }
913
+ /**
914
+ * Download all file attachments from a Teams message (images, documents, etc.).
915
+ * Renamed from downloadMSTeamsImageAttachments to support all file types.
916
+ */
917
+ async function downloadMSTeamsAttachments(params) {
918
+ const list = Array.isArray(params.attachments) ? params.attachments : [];
919
+ if (list.length === 0) return [];
920
+ const policy = resolveAttachmentFetchPolicy({
921
+ allowHosts: params.allowHosts,
922
+ authAllowHosts: params.authAllowHosts
923
+ });
924
+ const allowHosts = policy.allowHosts;
925
+ const ssrfPolicy = resolveMediaSsrfPolicy(allowHosts);
926
+ const candidates = list.filter(isDownloadableAttachment).map(resolveDownloadCandidate).filter(Boolean);
927
+ const inlineCandidates = extractInlineImageCandidates(list, {
928
+ maxInlineBytes: params.maxBytes,
929
+ maxInlineTotalBytes: params.maxBytes
930
+ });
931
+ const seenUrls = /* @__PURE__ */ new Set();
932
+ for (const inline of inlineCandidates) if (inline.kind === "url") {
933
+ if (!isUrlAllowed(inline.url, allowHosts)) continue;
934
+ if (seenUrls.has(inline.url)) continue;
935
+ seenUrls.add(inline.url);
936
+ candidates.push({
937
+ url: inline.url,
938
+ fileHint: inline.fileHint,
939
+ contentTypeHint: inline.contentType,
940
+ placeholder: inline.placeholder
941
+ });
942
+ }
943
+ if (candidates.length === 0 && inlineCandidates.length === 0) return [];
944
+ const out = [];
945
+ for (const inline of inlineCandidates) {
946
+ if (inline.kind !== "data") continue;
947
+ if (inline.data.byteLength > params.maxBytes) continue;
948
+ try {
949
+ const contentType = await resolveInlineDataImageMime(inline);
950
+ if (!contentType) continue;
951
+ const saved = await getMSTeamsRuntime().channel.media.saveMediaBuffer(inline.data, contentType, "inbound", params.maxBytes);
952
+ out.push({
953
+ path: saved.path,
954
+ contentType: saved.contentType,
955
+ placeholder: inferPlaceholder({ contentType: saved.contentType ?? contentType })
956
+ });
957
+ } catch (err) {
958
+ params.logger?.warn?.("msteams inline attachment decode failed", { error: err instanceof Error ? err.message : String(err) });
959
+ }
960
+ }
961
+ for (const candidate of candidates) {
962
+ if (!isUrlAllowed(candidate.url, allowHosts)) continue;
963
+ try {
964
+ const media = await downloadAndStoreMSTeamsRemoteMedia({
965
+ url: candidate.url,
966
+ filePathHint: candidate.fileHint ?? candidate.url,
967
+ maxBytes: params.maxBytes,
968
+ contentTypeHint: candidate.contentTypeHint,
969
+ placeholder: candidate.placeholder,
970
+ preserveFilenames: params.preserveFilenames,
971
+ ssrfPolicy,
972
+ useDirectFetch: true,
973
+ fetchImpl: (input, init) => fetchWithAuthFallback({
974
+ url: resolveRequestUrl(input),
975
+ tokenProvider: params.tokenProvider,
976
+ fetchFn: params.fetchFn,
977
+ requestInit: init,
978
+ resolveFn: params.resolveFn,
979
+ policy
980
+ })
981
+ });
982
+ out.push(media);
983
+ } catch (err) {
984
+ params.logger?.warn?.("msteams attachment download failed", {
985
+ error: err instanceof Error ? err.message : String(err),
986
+ host: safeHostForLog(candidate.url)
987
+ });
988
+ }
989
+ }
990
+ return out;
991
+ }
992
+ function safeHostForLog(url) {
993
+ try {
994
+ return new URL(url).host;
995
+ } catch {
996
+ return "invalid-url";
997
+ }
998
+ }
999
+ //#endregion
1000
+ //#region extensions/msteams/src/attachments/graph.ts
1001
+ function buildMSTeamsGraphMessageUrls(params) {
1002
+ const conversationType = normalizeLowercaseStringOrEmpty(params.conversationType ?? "");
1003
+ const messageIdCandidates = /* @__PURE__ */ new Set();
1004
+ const pushCandidate = (value) => {
1005
+ const trimmed = normalizeOptionalString(value) ?? "";
1006
+ if (trimmed) messageIdCandidates.add(trimmed);
1007
+ };
1008
+ pushCandidate(params.messageId);
1009
+ pushCandidate(params.conversationMessageId);
1010
+ pushCandidate(readNestedString(params.channelData, ["messageId"]));
1011
+ pushCandidate(readNestedString(params.channelData, ["teamsMessageId"]));
1012
+ const replyToId = normalizeOptionalString(params.replyToId) ?? "";
1013
+ if (conversationType === "channel") {
1014
+ const teamId = readNestedString(params.channelData, ["team", "id"]) ?? readNestedString(params.channelData, ["teamId"]);
1015
+ const channelId = readNestedString(params.channelData, ["channel", "id"]) ?? readNestedString(params.channelData, ["channelId"]) ?? readNestedString(params.channelData, ["teamsChannelId"]);
1016
+ if (!teamId || !channelId) return [];
1017
+ const urls = [];
1018
+ if (replyToId) for (const candidate of messageIdCandidates) {
1019
+ if (candidate === replyToId) continue;
1020
+ urls.push(`${GRAPH_ROOT}/teams/${encodeURIComponent(teamId)}/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(replyToId)}/replies/${encodeURIComponent(candidate)}`);
1021
+ }
1022
+ if (messageIdCandidates.size === 0 && replyToId) messageIdCandidates.add(replyToId);
1023
+ for (const candidate of messageIdCandidates) urls.push(`${GRAPH_ROOT}/teams/${encodeURIComponent(teamId)}/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(candidate)}`);
1024
+ return Array.from(new Set(urls));
1025
+ }
1026
+ const chatId = params.conversationId?.trim() || readNestedString(params.channelData, ["chatId"]);
1027
+ if (!chatId) return [];
1028
+ if (messageIdCandidates.size === 0 && replyToId) messageIdCandidates.add(replyToId);
1029
+ const urls = Array.from(messageIdCandidates).map((candidate) => `${GRAPH_ROOT}/chats/${encodeURIComponent(chatId)}/messages/${encodeURIComponent(candidate)}`);
1030
+ return Array.from(new Set(urls));
1031
+ }
1032
+ async function fetchGraphCollection(params) {
1033
+ const fetchFn = params.fetchFn ?? fetch;
1034
+ const { response, release } = await fetchWithSsrFGuard({
1035
+ url: params.url,
1036
+ fetchImpl: fetchFn,
1037
+ init: { headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }) },
1038
+ policy: params.ssrfPolicy,
1039
+ auditContext: "msteams.graph.collection"
1040
+ });
1041
+ try {
1042
+ const status = response.status;
1043
+ if (!response.ok) return {
1044
+ status,
1045
+ items: []
1046
+ };
1047
+ try {
1048
+ const data = await response.json();
1049
+ return {
1050
+ status,
1051
+ items: Array.isArray(data.value) ? data.value : []
1052
+ };
1053
+ } catch {
1054
+ return {
1055
+ status,
1056
+ items: []
1057
+ };
1058
+ }
1059
+ } finally {
1060
+ await release();
1061
+ }
1062
+ }
1063
+ function normalizeGraphAttachment(att) {
1064
+ let content = att.content;
1065
+ if (typeof content === "string") try {
1066
+ content = JSON.parse(content);
1067
+ } catch {}
1068
+ return {
1069
+ contentType: normalizeContentType(att.contentType) ?? void 0,
1070
+ contentUrl: att.contentUrl ?? void 0,
1071
+ name: att.name ?? void 0,
1072
+ thumbnailUrl: att.thumbnailUrl ?? void 0,
1073
+ content
1074
+ };
1075
+ }
1076
+ /**
1077
+ * Download all hosted content from a Teams message (images, documents, etc.).
1078
+ * Renamed from downloadGraphHostedImages to support all file types.
1079
+ */
1080
+ async function downloadGraphHostedContent(params) {
1081
+ const hosted = await fetchGraphCollection({
1082
+ url: `${params.messageUrl}/hostedContents`,
1083
+ accessToken: params.accessToken,
1084
+ fetchFn: params.fetchFn,
1085
+ ssrfPolicy: params.ssrfPolicy
1086
+ });
1087
+ if (hosted.items.length === 0) return {
1088
+ media: [],
1089
+ status: hosted.status,
1090
+ count: 0
1091
+ };
1092
+ const out = [];
1093
+ for (const item of hosted.items) {
1094
+ const contentBytes = typeof item.contentBytes === "string" ? item.contentBytes : "";
1095
+ let buffer;
1096
+ if (contentBytes) {
1097
+ if (estimateBase64DecodedBytes(contentBytes) > params.maxBytes) continue;
1098
+ try {
1099
+ buffer = Buffer.from(contentBytes, "base64");
1100
+ } catch (err) {
1101
+ params.logger?.warn?.("msteams graph hostedContent base64 decode failed", { error: err instanceof Error ? err.message : String(err) });
1102
+ continue;
1103
+ }
1104
+ } else if (item.id) {
1105
+ try {
1106
+ const valueUrl = `${params.messageUrl}/hostedContents/${encodeURIComponent(item.id)}/$value`;
1107
+ const { response: valRes, release } = await fetchWithSsrFGuard({
1108
+ url: valueUrl,
1109
+ fetchImpl: params.fetchFn ?? fetch,
1110
+ init: { headers: ensureUserAgentHeader({ Authorization: `Bearer ${params.accessToken}` }) },
1111
+ policy: params.ssrfPolicy,
1112
+ auditContext: "msteams.graph.hostedContent.value"
1113
+ });
1114
+ try {
1115
+ if (!valRes.ok) continue;
1116
+ const saved = await getMSTeamsRuntime().channel.media.saveResponseMedia(valRes, {
1117
+ sourceUrl: valueUrl,
1118
+ maxBytes: params.maxBytes,
1119
+ fallbackContentType: item.contentType ?? void 0,
1120
+ subdir: "inbound"
1121
+ });
1122
+ out.push({
1123
+ path: saved.path,
1124
+ contentType: saved.contentType,
1125
+ placeholder: inferPlaceholder({ contentType: saved.contentType })
1126
+ });
1127
+ } finally {
1128
+ await release();
1129
+ }
1130
+ } catch (err) {
1131
+ params.logger?.warn?.("msteams graph hostedContent value fetch failed", { error: err instanceof Error ? err.message : String(err) });
1132
+ continue;
1133
+ }
1134
+ continue;
1135
+ } else continue;
1136
+ if (buffer.byteLength > params.maxBytes) continue;
1137
+ const mime = await getMSTeamsRuntime().media.detectMime({
1138
+ buffer,
1139
+ headerMime: item.contentType ?? void 0
1140
+ });
1141
+ try {
1142
+ const saved = await getMSTeamsRuntime().channel.media.saveMediaBuffer(buffer, mime ?? item.contentType ?? void 0, "inbound", params.maxBytes);
1143
+ out.push({
1144
+ path: saved.path,
1145
+ contentType: saved.contentType,
1146
+ placeholder: inferPlaceholder({ contentType: saved.contentType })
1147
+ });
1148
+ } catch (err) {
1149
+ params.logger?.warn?.("msteams graph hostedContent save failed", { error: err instanceof Error ? err.message : String(err) });
1150
+ }
1151
+ }
1152
+ return {
1153
+ media: out,
1154
+ status: hosted.status,
1155
+ count: hosted.items.length
1156
+ };
1157
+ }
1158
+ async function downloadMSTeamsGraphMedia(params) {
1159
+ if (!params.messageUrl || !params.tokenProvider) return { media: [] };
1160
+ const policy = resolveAttachmentFetchPolicy({
1161
+ allowHosts: params.allowHosts,
1162
+ authAllowHosts: params.authAllowHosts
1163
+ });
1164
+ const ssrfPolicy = resolveMediaSsrfPolicy(policy.allowHosts);
1165
+ const messageUrl = params.messageUrl;
1166
+ const debugLog = params.log ?? params.logger ?? void 0;
1167
+ let accessToken;
1168
+ try {
1169
+ accessToken = await params.tokenProvider.getAccessToken("https://graph.microsoft.com");
1170
+ } catch (err) {
1171
+ debugLog?.debug?.("graph media token acquisition failed", {
1172
+ messageUrl,
1173
+ error: err instanceof Error ? err.message : String(err)
1174
+ });
1175
+ params.logger?.warn?.("msteams graph token acquisition failed", { error: err instanceof Error ? err.message : String(err) });
1176
+ return {
1177
+ media: [],
1178
+ messageUrl,
1179
+ tokenError: true
1180
+ };
1181
+ }
1182
+ const fetchFn = params.fetchFn ?? fetch;
1183
+ const sharePointMedia = [];
1184
+ const downloadedReferenceUrls = /* @__PURE__ */ new Set();
1185
+ let messageAttachments = [];
1186
+ let messageStatus;
1187
+ try {
1188
+ const { response: msgRes, release } = await fetchWithSsrFGuard({
1189
+ url: messageUrl,
1190
+ fetchImpl: fetchFn,
1191
+ init: { headers: ensureUserAgentHeader({ Authorization: `Bearer ${accessToken}` }) },
1192
+ policy: ssrfPolicy,
1193
+ auditContext: "msteams.graph.message"
1194
+ });
1195
+ try {
1196
+ messageStatus = msgRes.status;
1197
+ if (msgRes.ok) {
1198
+ let msgData;
1199
+ try {
1200
+ msgData = await msgRes.json();
1201
+ } catch (err) {
1202
+ debugLog?.debug?.("graph media message parse failed", {
1203
+ messageUrl,
1204
+ error: err instanceof Error ? err.message : String(err)
1205
+ });
1206
+ params.logger?.warn?.("msteams graph message parse failed", {
1207
+ error: err instanceof Error ? err.message : String(err),
1208
+ messageUrl
1209
+ });
1210
+ msgData = {};
1211
+ }
1212
+ messageAttachments = Array.isArray(msgData.attachments) ? msgData.attachments : [];
1213
+ const spAttachments = messageAttachments.filter((a) => a.contentType === "reference" && a.contentUrl && a.name);
1214
+ for (const att of spAttachments) {
1215
+ const name = att.name ?? "file";
1216
+ const shareUrl = att.contentUrl ?? "";
1217
+ if (!shareUrl) continue;
1218
+ try {
1219
+ const sharesUrl = `${GRAPH_ROOT}/shares/${encodeGraphShareId(shareUrl)}/driveItem/content`;
1220
+ if (!isUrlAllowed(sharesUrl, policy.allowHosts)) {
1221
+ debugLog?.debug?.("graph media sharepoint url not in allowHosts", {
1222
+ messageUrl,
1223
+ sharesUrl
1224
+ });
1225
+ continue;
1226
+ }
1227
+ const media = await downloadAndStoreMSTeamsRemoteMedia({
1228
+ url: sharesUrl,
1229
+ filePathHint: name,
1230
+ maxBytes: params.maxBytes,
1231
+ contentTypeHint: "application/octet-stream",
1232
+ preserveFilenames: params.preserveFilenames,
1233
+ ssrfPolicy,
1234
+ useDirectFetch: true,
1235
+ fetchImpl: async (input, init) => {
1236
+ const requestUrl = resolveRequestUrl(input);
1237
+ const headers = ensureUserAgentHeader(init?.headers);
1238
+ applyAuthorizationHeaderForUrl({
1239
+ headers,
1240
+ url: requestUrl,
1241
+ authAllowHosts: policy.authAllowHosts,
1242
+ bearerToken: accessToken
1243
+ });
1244
+ return await safeFetchWithPolicy({
1245
+ url: requestUrl,
1246
+ policy,
1247
+ fetchFn,
1248
+ requestInit: {
1249
+ ...init,
1250
+ headers
1251
+ },
1252
+ resolveFn: params.resolveFn
1253
+ });
1254
+ }
1255
+ });
1256
+ sharePointMedia.push(media);
1257
+ downloadedReferenceUrls.add(shareUrl);
1258
+ } catch (err) {
1259
+ params.logger?.warn?.("msteams SharePoint reference download failed", {
1260
+ error: err instanceof Error ? err.message : String(err),
1261
+ name
1262
+ });
1263
+ }
1264
+ }
1265
+ } else debugLog?.debug?.("graph media message fetch not ok", {
1266
+ messageUrl,
1267
+ status: messageStatus
1268
+ });
1269
+ } finally {
1270
+ await release();
1271
+ }
1272
+ } catch (err) {
1273
+ debugLog?.debug?.("graph media message fetch failed", {
1274
+ messageUrl,
1275
+ error: err instanceof Error ? err.message : String(err)
1276
+ });
1277
+ params.logger?.warn?.("msteams graph message fetch failed", { error: err instanceof Error ? err.message : String(err) });
1278
+ }
1279
+ const hosted = await downloadGraphHostedContent({
1280
+ accessToken,
1281
+ messageUrl,
1282
+ maxBytes: params.maxBytes,
1283
+ fetchFn: params.fetchFn,
1284
+ preserveFilenames: params.preserveFilenames,
1285
+ ssrfPolicy,
1286
+ logger: params.logger
1287
+ });
1288
+ const normalizedAttachments = messageAttachments.map(normalizeGraphAttachment);
1289
+ const filteredAttachments = sharePointMedia.length > 0 ? normalizedAttachments.filter((att) => {
1290
+ if (normalizeOptionalLowercaseString(att.contentType) !== "reference") return true;
1291
+ const url = typeof att.contentUrl === "string" ? att.contentUrl : "";
1292
+ if (!url) return true;
1293
+ return !downloadedReferenceUrls.has(url);
1294
+ }) : normalizedAttachments;
1295
+ let attachmentMedia = [];
1296
+ try {
1297
+ attachmentMedia = await downloadMSTeamsAttachments({
1298
+ attachments: filteredAttachments,
1299
+ maxBytes: params.maxBytes,
1300
+ tokenProvider: params.tokenProvider,
1301
+ allowHosts: policy.allowHosts,
1302
+ authAllowHosts: policy.authAllowHosts,
1303
+ fetchFn: params.fetchFn,
1304
+ resolveFn: params.resolveFn,
1305
+ preserveFilenames: params.preserveFilenames,
1306
+ logger: params.logger
1307
+ });
1308
+ } catch (err) {
1309
+ params.logger?.warn?.("msteams graph attachment download failed", {
1310
+ error: err instanceof Error ? err.message : String(err),
1311
+ messageUrl
1312
+ });
1313
+ }
1314
+ return {
1315
+ media: [
1316
+ ...sharePointMedia,
1317
+ ...hosted.media,
1318
+ ...attachmentMedia
1319
+ ],
1320
+ hostedCount: hosted.count,
1321
+ attachmentCount: filteredAttachments.length + sharePointMedia.length,
1322
+ hostedStatus: hosted.status,
1323
+ attachmentStatus: messageStatus,
1324
+ messageUrl
1325
+ };
1326
+ }
1327
+ //#endregion
1328
+ //#region extensions/msteams/src/attachments/html.ts
1329
+ /**
1330
+ * Extract every `<attachment id="...">` reference from the HTML attachments in
1331
+ * the inbound activity. Returns the complete (non-sliced) list; callers that
1332
+ * need a capped diagnostic summary can truncate after calling this helper.
1333
+ */
1334
+ function extractMSTeamsHtmlAttachmentIds(attachments) {
1335
+ const list = Array.isArray(attachments) ? attachments : [];
1336
+ if (list.length === 0) return [];
1337
+ const ids = /* @__PURE__ */ new Set();
1338
+ for (const att of list) {
1339
+ const html = extractHtmlFromAttachment(att);
1340
+ if (!html) continue;
1341
+ ATTACHMENT_TAG_RE.lastIndex = 0;
1342
+ let match = ATTACHMENT_TAG_RE.exec(html);
1343
+ while (match) {
1344
+ const id = match[1]?.trim();
1345
+ if (id) ids.add(id);
1346
+ match = ATTACHMENT_TAG_RE.exec(html);
1347
+ }
1348
+ }
1349
+ return Array.from(ids);
1350
+ }
1351
+ function summarizeMSTeamsHtmlAttachments(attachments) {
1352
+ const list = Array.isArray(attachments) ? attachments : [];
1353
+ if (list.length === 0) return;
1354
+ let htmlAttachments = 0;
1355
+ let imgTags = 0;
1356
+ let dataImages = 0;
1357
+ let cidImages = 0;
1358
+ const srcHosts = /* @__PURE__ */ new Set();
1359
+ let attachmentTags = 0;
1360
+ const attachmentIds = /* @__PURE__ */ new Set();
1361
+ for (const att of list) {
1362
+ const html = extractHtmlFromAttachment(att);
1363
+ if (!html) continue;
1364
+ htmlAttachments += 1;
1365
+ IMG_SRC_RE.lastIndex = 0;
1366
+ let match = IMG_SRC_RE.exec(html);
1367
+ while (match) {
1368
+ imgTags += 1;
1369
+ const src = match[1]?.trim();
1370
+ if (src) if (src.startsWith("data:")) dataImages += 1;
1371
+ else if (src.startsWith("cid:")) cidImages += 1;
1372
+ else srcHosts.add(safeHostForUrl(src));
1373
+ match = IMG_SRC_RE.exec(html);
1374
+ }
1375
+ ATTACHMENT_TAG_RE.lastIndex = 0;
1376
+ let attachmentMatch = ATTACHMENT_TAG_RE.exec(html);
1377
+ while (attachmentMatch) {
1378
+ attachmentTags += 1;
1379
+ const id = attachmentMatch[1]?.trim();
1380
+ if (id) attachmentIds.add(id);
1381
+ attachmentMatch = ATTACHMENT_TAG_RE.exec(html);
1382
+ }
1383
+ }
1384
+ if (htmlAttachments === 0) return;
1385
+ return {
1386
+ htmlAttachments,
1387
+ imgTags,
1388
+ dataImages,
1389
+ cidImages,
1390
+ srcHosts: Array.from(srcHosts).slice(0, 5),
1391
+ attachmentTags,
1392
+ attachmentIds: Array.from(attachmentIds).slice(0, 5)
1393
+ };
1394
+ }
1395
+ function buildMSTeamsAttachmentPlaceholder(attachments, limits) {
1396
+ const list = Array.isArray(attachments) ? attachments : [];
1397
+ if (list.length === 0) return "";
1398
+ const totalImages = list.filter(isLikelyImageAttachment).length + extractInlineImageCandidates(list, limits).length;
1399
+ if (totalImages > 0) return `<media:image>${totalImages > 1 ? ` (${totalImages} images)` : ""}`;
1400
+ const count = list.length;
1401
+ return `<media:document>${count > 1 ? ` (${count} files)` : ""}`;
1402
+ }
1403
+ //#endregion
1404
+ //#region extensions/msteams/src/attachments/payload.ts
1405
+ function buildMSTeamsMediaPayload(mediaList) {
1406
+ return buildMediaPayload(mediaList, { preserveMediaTypeCardinality: true });
1407
+ }
1408
+ //#endregion
1409
+ //#region extensions/msteams/src/graph-thread.ts
1410
+ const teamGroupIdCache = /* @__PURE__ */ new Map();
1411
+ const CACHE_TTL_MS = 600 * 1e3;
1412
+ /**
1413
+ * Strip HTML tags from Teams message content, preserving @mention display names.
1414
+ * Teams wraps mentions in <at>Name</at> tags.
1415
+ */
1416
+ function stripHtmlFromTeamsMessage(html) {
1417
+ let text = html.replace(/<at[^>]*>(.*?)<\/at>/gi, "@$1");
1418
+ text = text.replace(/<[^>]*>/g, " ");
1419
+ text = text.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&nbsp;/g, " ");
1420
+ return text.replace(/\s+/g, " ").trim();
1421
+ }
1422
+ /**
1423
+ * Resolve the Azure AD group GUID for a Teams conversation team ID.
1424
+ * Results are cached with a TTL to avoid repeated Graph API calls.
1425
+ */
1426
+ async function resolveTeamGroupId(token, conversationTeamId) {
1427
+ const cached = teamGroupIdCache.get(conversationTeamId);
1428
+ if (cached && cached.expiresAt > Date.now()) return cached.groupId;
1429
+ try {
1430
+ const groupId = (await fetchGraphJson({
1431
+ token,
1432
+ path: `/teams/${encodeURIComponent(conversationTeamId)}?$select=id`
1433
+ })).id ?? conversationTeamId;
1434
+ teamGroupIdCache.set(conversationTeamId, {
1435
+ groupId,
1436
+ expiresAt: Date.now() + CACHE_TTL_MS
1437
+ });
1438
+ return groupId;
1439
+ } catch {
1440
+ return conversationTeamId;
1441
+ }
1442
+ }
1443
+ /**
1444
+ * Fetch a single channel message (the parent/root of a thread).
1445
+ * Returns undefined on error so callers can degrade gracefully.
1446
+ */
1447
+ async function fetchChannelMessage(token, groupId, channelId, messageId) {
1448
+ const path = `/teams/${encodeURIComponent(groupId)}/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(messageId)}?$select=id,from,body,createdDateTime`;
1449
+ try {
1450
+ return await fetchGraphJson({
1451
+ token,
1452
+ path
1453
+ });
1454
+ } catch {
1455
+ return;
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Fetch thread replies for a channel message, ordered chronologically.
1460
+ *
1461
+ * **Limitation:** The Graph API replies endpoint (`/messages/{id}/replies`) does not
1462
+ * support `$orderby`, so results are always returned in ascending (oldest-first) order.
1463
+ * Combined with the `$top` cap of 50, this means only the **oldest 50 replies** are
1464
+ * returned for long threads — newer replies are silently omitted. There is currently no
1465
+ * Graph API workaround for this; pagination via `@odata.nextLink` can retrieve more
1466
+ * replies but still in ascending order only.
1467
+ */
1468
+ async function fetchThreadReplies(token, groupId, channelId, messageId, limit = 50) {
1469
+ return (await fetchGraphJson({
1470
+ token,
1471
+ path: `/teams/${encodeURIComponent(groupId)}/channels/${encodeURIComponent(channelId)}/messages/${encodeURIComponent(messageId)}/replies?$top=${Math.min(Math.max(limit, 1), 50)}&$select=id,from,body,createdDateTime`
1472
+ })).value ?? [];
1473
+ }
1474
+ /**
1475
+ * Format thread messages into a context string for the agent.
1476
+ * Skips the current message (by id) and blank messages.
1477
+ */
1478
+ function formatThreadContext(messages, currentMessageId) {
1479
+ const lines = [];
1480
+ for (const msg of messages) {
1481
+ if (msg.id && msg.id === currentMessageId) continue;
1482
+ const sender = msg.from?.user?.displayName ?? msg.from?.application?.displayName ?? "unknown";
1483
+ const contentType = msg.body?.contentType ?? "text";
1484
+ const rawContent = msg.body?.content ?? "";
1485
+ const content = contentType === "html" ? stripHtmlFromTeamsMessage(rawContent) : rawContent.trim();
1486
+ if (!content) continue;
1487
+ lines.push(`${sender}: ${content}`);
1488
+ }
1489
+ return lines.join("\n");
1490
+ }
1491
+ //#endregion
1492
+ //#region extensions/msteams/src/thread-parent-context.ts
1493
+ const PARENT_CACHE_TTL_MS = 300 * 1e3;
1494
+ const PARENT_CACHE_MAX = 100;
1495
+ const parentCache = /* @__PURE__ */ new Map();
1496
+ const INJECTED_MAX = 200;
1497
+ const injectedParents = /* @__PURE__ */ new Map();
1498
+ function touchLru(map, key, value, max) {
1499
+ if (map.has(key)) map.delete(key);
1500
+ else if (map.size >= max) {
1501
+ const firstKey = map.keys().next().value;
1502
+ if (firstKey !== void 0) map.delete(firstKey);
1503
+ }
1504
+ map.set(key, value);
1505
+ }
1506
+ function buildParentCacheKey(groupId, channelId, parentId) {
1507
+ return `${groupId}\u0000${channelId}\u0000${parentId}`;
1508
+ }
1509
+ /**
1510
+ * Fetch a channel parent message with an LRU+TTL cache.
1511
+ *
1512
+ * Uses the injected `fetchParent` (defaults to `fetchChannelMessage`) so
1513
+ * tests can swap in a stub without mocking the Graph transport.
1514
+ */
1515
+ async function fetchParentMessageCached(token, groupId, channelId, parentId, fetchParent = fetchChannelMessage) {
1516
+ const key = buildParentCacheKey(groupId, channelId, parentId);
1517
+ const now = Date.now();
1518
+ const cached = parentCache.get(key);
1519
+ if (cached && cached.expiresAt > now) {
1520
+ parentCache.delete(key);
1521
+ parentCache.set(key, cached);
1522
+ return cached.message;
1523
+ }
1524
+ const message = await fetchParent(token, groupId, channelId, parentId);
1525
+ touchLru(parentCache, key, {
1526
+ message,
1527
+ expiresAt: now + PARENT_CACHE_TTL_MS
1528
+ }, PARENT_CACHE_MAX);
1529
+ return message;
1530
+ }
1531
+ const PARENT_TEXT_MAX_CHARS = 400;
1532
+ /**
1533
+ * Extract a compact summary (sender + plain-text body) from a Graph parent
1534
+ * message. Returns undefined when the parent cannot be summarized (missing
1535
+ * or blank body).
1536
+ */
1537
+ function summarizeParentMessage(message) {
1538
+ if (!message) return;
1539
+ const sender = message.from?.user?.displayName ?? message.from?.application?.displayName ?? "unknown";
1540
+ const contentType = message.body?.contentType ?? "text";
1541
+ const raw = message.body?.content ?? "";
1542
+ const text = contentType === "html" ? stripHtmlFromTeamsMessage(raw) : raw.replace(/\s+/g, " ").trim();
1543
+ if (!text) return;
1544
+ return {
1545
+ sender,
1546
+ text: text.length > PARENT_TEXT_MAX_CHARS ? `${text.slice(0, PARENT_TEXT_MAX_CHARS - 1)}…` : text
1547
+ };
1548
+ }
1549
+ /**
1550
+ * Build the single-line `Replying to @sender: body` system event text.
1551
+ * Callers should pass this text to `enqueueSystemEvent` together with a
1552
+ * stable contextKey derived from the parent id.
1553
+ */
1554
+ function formatParentContextEvent(summary) {
1555
+ return `Replying to @${summary.sender}: ${summary.text}`;
1556
+ }
1557
+ /**
1558
+ * Decide whether a parent context event should be enqueued for the current
1559
+ * session. Returns `false` when we already injected the same parent for this
1560
+ * session recently (prevents re-prepending identical context on every reply
1561
+ * in the thread).
1562
+ */
1563
+ function shouldInjectParentContext(sessionKey, parentId) {
1564
+ const key = sessionKey;
1565
+ return injectedParents.get(key) !== parentId;
1566
+ }
1567
+ /**
1568
+ * Record that `parentId` was just injected for `sessionKey` so subsequent
1569
+ * replies with the same parent can short-circuit via `shouldInjectParentContext`.
1570
+ */
1571
+ function markParentContextInjected(sessionKey, parentId) {
1572
+ touchLru(injectedParents, sessionKey, parentId, INJECTED_MAX);
1573
+ }
1574
+ //#endregion
1575
+ //#region extensions/msteams/src/streaming-message.ts
1576
+ /**
1577
+ * Teams streaming message using the streaminfo entity protocol.
1578
+ *
1579
+ * Follows the official Teams SDK pattern:
1580
+ * 1. First chunk → POST a typing activity with streaminfo entity (streamType: "streaming")
1581
+ * 2. Subsequent chunks → POST typing activities with streaminfo + incrementing streamSequence
1582
+ * 3. Finalize → POST a message activity with streaminfo (streamType: "final")
1583
+ *
1584
+ * Uses the shared draft-stream-loop for throttling (avoids rate limits).
1585
+ */
1586
+ /** Default throttle interval between stream updates (ms).
1587
+ * Teams docs recommend buffering tokens for 1.5-2s; limit is 1 req/s. */
1588
+ const DEFAULT_THROTTLE_MS = 1500;
1589
+ /** Minimum chars before sending the first streaming message. */
1590
+ const MIN_INITIAL_CHARS = 20;
1591
+ /** Teams message text limit. */
1592
+ const TEAMS_MAX_CHARS = 4e3;
1593
+ /**
1594
+ * Stop streaming before Teams expires the content stream server-side.
1595
+ * The exact service limit is opaque, so stay comfortably under it.
1596
+ */
1597
+ const MAX_STREAM_AGE_MS = 45e3;
1598
+ function extractId(response) {
1599
+ if (response && typeof response === "object" && "id" in response) return readStringValue(response.id);
1600
+ }
1601
+ function buildStreamInfoEntity(streamId, streamType, streamSequence) {
1602
+ const entity = {
1603
+ type: "streaminfo",
1604
+ streamType
1605
+ };
1606
+ if (streamId) entity.streamId = streamId;
1607
+ if (streamSequence != null) entity.streamSequence = streamSequence;
1608
+ return entity;
1609
+ }
1610
+ var TeamsHttpStream = class {
1611
+ constructor(options) {
1612
+ this.accumulatedText = "";
1613
+ this.streamId = void 0;
1614
+ this.sequenceNumber = 0;
1615
+ this.stopped = false;
1616
+ this.finalized = false;
1617
+ this.streamFailed = false;
1618
+ this.lastStreamedText = "";
1619
+ this.finalMessageId = void 0;
1620
+ this.streamStartedAt = void 0;
1621
+ this.sendActivity = options.sendActivity;
1622
+ this.feedbackLoopEnabled = options.feedbackLoopEnabled ?? false;
1623
+ this.onError = options.onError;
1624
+ this.loop = createDraftStreamLoop({
1625
+ throttleMs: options.throttleMs ?? DEFAULT_THROTTLE_MS,
1626
+ isStopped: () => this.stopped,
1627
+ sendOrEditStreamMessage: (text) => this.pushStreamChunk(text)
1628
+ });
1629
+ }
1630
+ /**
1631
+ * Send an informative status update (blue progress bar in Teams).
1632
+ * Call this immediately when a message is received, before LLM starts generating.
1633
+ * Establishes the stream so subsequent chunks continue from this stream ID.
1634
+ */
1635
+ async sendInformativeUpdate(text) {
1636
+ if (this.stopped || this.finalized) return;
1637
+ this.sequenceNumber++;
1638
+ const activity = {
1639
+ type: "typing",
1640
+ text,
1641
+ entities: [buildStreamInfoEntity(this.streamId, "informative", this.sequenceNumber)]
1642
+ };
1643
+ try {
1644
+ const response = await this.sendActivity(activity);
1645
+ if (!this.streamId) this.streamId = extractId(response);
1646
+ } catch (err) {
1647
+ this.onError?.(err);
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Ingest partial text from the LLM token stream.
1652
+ * Called by onPartialReply — accumulates text and throttles updates.
1653
+ */
1654
+ update(text) {
1655
+ if (this.stopped || this.finalized) return;
1656
+ this.accumulatedText = text;
1657
+ if (!this.streamId && this.accumulatedText.length < MIN_INITIAL_CHARS) return;
1658
+ if (this.accumulatedText.length > TEAMS_MAX_CHARS) {
1659
+ this.streamFailed = true;
1660
+ this.finalize();
1661
+ return;
1662
+ }
1663
+ if (this.streamStartedAt && Date.now() - this.streamStartedAt >= MAX_STREAM_AGE_MS) {
1664
+ this.streamFailed = true;
1665
+ this.finalize();
1666
+ return;
1667
+ }
1668
+ this.loop.update(this.accumulatedText);
1669
+ }
1670
+ /**
1671
+ * Replace an informative progress update with final answer text.
1672
+ * Returns false when the stream could not safely carry the final text, so
1673
+ * callers can deliver the answer through the normal Teams message path.
1674
+ */
1675
+ async replaceInformativeWithFinal(text) {
1676
+ if (this.stopped || this.finalized) return false;
1677
+ this.update(text);
1678
+ await this.loop.flush();
1679
+ await this.finalize();
1680
+ return !this.streamFailed && this.hasContent;
1681
+ }
1682
+ /**
1683
+ * Finalize the stream — send the final message activity.
1684
+ */
1685
+ async finalize() {
1686
+ if (this.finalized) return this.finalMessageId;
1687
+ this.finalized = true;
1688
+ this.stopped = true;
1689
+ this.loop.stop();
1690
+ await this.loop.waitForInFlight();
1691
+ if (!this.accumulatedText.trim()) return this.finalMessageId;
1692
+ if (this.streamFailed) {
1693
+ if (this.streamId) try {
1694
+ const response = await this.sendActivity({
1695
+ type: "message",
1696
+ text: this.lastStreamedText || "",
1697
+ channelData: { feedbackLoopEnabled: this.feedbackLoopEnabled },
1698
+ entities: [AI_GENERATED_ENTITY, buildStreamInfoEntity(this.streamId, "final")]
1699
+ });
1700
+ this.finalMessageId = extractId(response);
1701
+ } catch {}
1702
+ return this.finalMessageId;
1703
+ }
1704
+ try {
1705
+ const entities = [AI_GENERATED_ENTITY];
1706
+ if (this.streamId) entities.push(buildStreamInfoEntity(this.streamId, "final"));
1707
+ const finalActivity = {
1708
+ type: "message",
1709
+ text: this.accumulatedText,
1710
+ channelData: { feedbackLoopEnabled: this.feedbackLoopEnabled },
1711
+ entities
1712
+ };
1713
+ const response = await this.sendActivity(finalActivity);
1714
+ this.finalMessageId = extractId(response);
1715
+ } catch (err) {
1716
+ this.streamFailed = true;
1717
+ this.onError?.(err);
1718
+ }
1719
+ return this.finalMessageId;
1720
+ }
1721
+ /** Whether streaming successfully delivered content (at least one chunk sent, not failed). */
1722
+ get hasContent() {
1723
+ return this.accumulatedText.length > 0 && !this.streamFailed;
1724
+ }
1725
+ /** Whether streaming failed and fallback delivery is needed. */
1726
+ get isFailed() {
1727
+ return this.streamFailed;
1728
+ }
1729
+ /** Number of characters successfully streamed before failure. */
1730
+ get streamedLength() {
1731
+ return this.lastStreamedText.length;
1732
+ }
1733
+ /** Whether the stream has been finalized. */
1734
+ get isFinalized() {
1735
+ return this.finalized;
1736
+ }
1737
+ /** Platform id returned by the final message activity, when available. */
1738
+ get messageId() {
1739
+ return this.finalMessageId;
1740
+ }
1741
+ /** Stream id returned by the first streaminfo activity, when available. */
1742
+ get previewStreamId() {
1743
+ return this.streamId;
1744
+ }
1745
+ /** Whether streaming fell back (not used in this implementation). */
1746
+ get isFallback() {
1747
+ return false;
1748
+ }
1749
+ /**
1750
+ * Send a single streaming chunk as a typing activity with streaminfo.
1751
+ * Per the Teams REST API spec:
1752
+ * - First chunk: no streamId, streamSequence=1 → returns 201 with { id: streamId }
1753
+ * - Subsequent chunks: include streamId, increment streamSequence → returns 202
1754
+ */
1755
+ async pushStreamChunk(text) {
1756
+ if (this.stopped && !this.finalized) return false;
1757
+ this.sequenceNumber++;
1758
+ const activity = {
1759
+ type: "typing",
1760
+ text,
1761
+ entities: [buildStreamInfoEntity(this.streamId, "streaming", this.sequenceNumber)]
1762
+ };
1763
+ try {
1764
+ const response = await this.sendActivity(activity);
1765
+ if (!this.streamStartedAt) this.streamStartedAt = Date.now();
1766
+ if (!this.streamId) this.streamId = extractId(response);
1767
+ this.lastStreamedText = text;
1768
+ return true;
1769
+ } catch (err) {
1770
+ const axiosData = err?.response;
1771
+ const statusCode = axiosData?.status ?? err?.statusCode;
1772
+ const responseBody = axiosData?.data ? JSON.stringify(axiosData.data).slice(0, 300) : "";
1773
+ const msg = formatUnknownError(err);
1774
+ this.onError?.(/* @__PURE__ */ new Error(`stream POST failed (HTTP ${statusCode ?? "?"}): ${msg}${responseBody ? ` body=${responseBody}` : ""}`));
1775
+ this.streamFailed = true;
1776
+ return false;
1777
+ }
1778
+ }
1779
+ };
1780
+ //#endregion
1781
+ //#region extensions/msteams/src/reply-stream-controller.ts
1782
+ function createTeamsReplyStreamController(params) {
1783
+ const isPersonal = normalizeOptionalLowercaseString(params.conversationType) === "personal";
1784
+ const streamMode = resolveChannelPreviewStreamMode(params.msteamsConfig, "partial");
1785
+ const shouldUseNativeStream = isPersonal && (streamMode === "partial" || streamMode === "progress");
1786
+ const shouldSuppressDefaultToolProgressMessages = shouldUseNativeStream && streamMode === "progress";
1787
+ const shouldStreamPreviewToolProgress = shouldSuppressDefaultToolProgressMessages && resolveChannelStreamingPreviewToolProgress(params.msteamsConfig);
1788
+ const stream = shouldUseNativeStream ? new TeamsHttpStream({
1789
+ sendActivity: (activity) => params.context.sendActivity(activity),
1790
+ feedbackLoopEnabled: params.feedbackLoopEnabled,
1791
+ onError: (err) => {
1792
+ params.log.debug?.(`stream error: ${formatUnknownError(err)}`);
1793
+ }
1794
+ }) : void 0;
1795
+ let streamReceivedTokens = false;
1796
+ let informativeUpdateSent = false;
1797
+ let progressLines = [];
1798
+ let lastInformativeText = "";
1799
+ let pendingFinalize;
1800
+ let liveState = createLiveMessageState({ canFinalizeInPlace: Boolean(stream) });
1801
+ const markStreamFinalized = () => {
1802
+ if (!stream || stream.isFailed) return;
1803
+ const messageId = stream.messageId ?? stream.previewStreamId;
1804
+ if (!messageId) return;
1805
+ liveState = markLiveMessageFinalized(liveState, createPreviewMessageReceipt({ id: messageId }));
1806
+ };
1807
+ const renderInformativeUpdate = async () => {
1808
+ if (!stream) return;
1809
+ const informativeText = formatChannelProgressDraftText({
1810
+ entry: params.msteamsConfig,
1811
+ lines: shouldStreamPreviewToolProgress ? progressLines : [],
1812
+ seed: params.progressSeed,
1813
+ bullet: "-"
1814
+ });
1815
+ if (!informativeText || informativeText === lastInformativeText) return;
1816
+ lastInformativeText = informativeText;
1817
+ informativeUpdateSent = true;
1818
+ await stream.sendInformativeUpdate(informativeText);
1819
+ };
1820
+ const progressDraftGate = createChannelProgressDraftGate({ onStart: renderInformativeUpdate });
1821
+ const noteProgressWork = async (options) => {
1822
+ if (!stream || streamMode !== "progress") return;
1823
+ if (options?.toolName !== void 0 && !isChannelProgressDraftWorkToolName(options.toolName)) return;
1824
+ const hadStarted = progressDraftGate.hasStarted;
1825
+ await progressDraftGate.noteWork();
1826
+ if (hadStarted && progressDraftGate.hasStarted) await renderInformativeUpdate();
1827
+ };
1828
+ const pushProgressLine = async (line, options) => {
1829
+ if (!stream || streamMode !== "progress") return;
1830
+ if (options?.toolName !== void 0 && !isChannelProgressDraftWorkToolName(options.toolName)) return;
1831
+ if (shouldStreamPreviewToolProgress) {
1832
+ const normalized = normalizeChannelProgressDraftLineIdentity(line);
1833
+ if (normalized) progressLines = mergeChannelProgressDraftLine(progressLines, typeof line === "object" && line !== void 0 ? line : normalized, { maxLines: resolveChannelProgressDraftMaxLines(params.msteamsConfig) });
1834
+ }
1835
+ await noteProgressWork();
1836
+ };
1837
+ const fallbackAfterStreamFailure = (payload, hasMedia) => {
1838
+ if (!payload.text) return payload;
1839
+ const streamedLength = stream?.streamedLength ?? 0;
1840
+ if (streamedLength <= 0) return payload;
1841
+ const remainingText = payload.text.slice(streamedLength);
1842
+ if (!remainingText) return hasMedia ? {
1843
+ ...payload,
1844
+ text: void 0
1845
+ } : void 0;
1846
+ return {
1847
+ ...payload,
1848
+ text: remainingText
1849
+ };
1850
+ };
1851
+ const finalizeProgressPayload = async (payload, hasMedia) => {
1852
+ if (!stream || !payload.text) return payload;
1853
+ return (await deliverWithFinalizableLivePreviewAdapter({
1854
+ kind: "final",
1855
+ payload,
1856
+ liveState,
1857
+ adapter: defineFinalizableLivePreviewAdapter({
1858
+ draft: {
1859
+ flush: async () => {},
1860
+ clear: async () => {},
1861
+ id: () => stream.previewStreamId
1862
+ },
1863
+ buildFinalEdit: (candidate) => candidate.text ? { text: candidate.text } : void 0,
1864
+ editFinal: async (_previewId, edit) => {
1865
+ const finalized = await stream.replaceInformativeWithFinal(edit.text);
1866
+ informativeUpdateSent = false;
1867
+ if (!finalized || stream.isFailed) throw new Error("Teams progress stream finalization failed");
1868
+ },
1869
+ resolveFinalizedId: (previewId) => stream.messageId ?? stream.previewStreamId ?? previewId,
1870
+ createPreviewReceipt: (id) => createPreviewMessageReceipt({ id }),
1871
+ onPreviewFinalized: (_id, _receipt, state) => {
1872
+ liveState = state;
1873
+ },
1874
+ logPreviewEditFailure: (err) => {
1875
+ params.log.debug?.(`stream finalization failed: ${formatUnknownError(err)}`);
1876
+ }
1877
+ }),
1878
+ deliverNormally: async () => false
1879
+ })).kind === "preview-finalized" ? hasMedia ? {
1880
+ ...payload,
1881
+ text: void 0
1882
+ } : void 0 : payload;
1883
+ };
1884
+ return {
1885
+ async onReplyStart() {},
1886
+ async noteProgressWork(options) {
1887
+ await noteProgressWork(options);
1888
+ },
1889
+ onPartialReply(payload) {
1890
+ if (!stream || !payload.text) return;
1891
+ if (streamMode === "progress") return;
1892
+ streamReceivedTokens = true;
1893
+ stream.update(payload.text);
1894
+ },
1895
+ async pushProgressLine(line, options) {
1896
+ await pushProgressLine(line, options);
1897
+ },
1898
+ shouldSuppressDefaultToolProgressMessages() {
1899
+ return shouldSuppressDefaultToolProgressMessages;
1900
+ },
1901
+ shouldStreamPreviewToolProgress() {
1902
+ return shouldStreamPreviewToolProgress;
1903
+ },
1904
+ async preparePayload(payload) {
1905
+ const hasMedia = Boolean(payload.mediaUrl || payload.mediaUrls?.length);
1906
+ if (stream && streamMode === "progress" && informativeUpdateSent && !stream.isFinalized) {
1907
+ if (!payload.text) return payload;
1908
+ return await finalizeProgressPayload(payload, hasMedia);
1909
+ }
1910
+ if (!stream || !streamReceivedTokens) return payload;
1911
+ if (stream.isFailed) {
1912
+ streamReceivedTokens = false;
1913
+ return fallbackAfterStreamFailure(payload, hasMedia);
1914
+ }
1915
+ if (!stream.hasContent || stream.isFinalized) return payload;
1916
+ streamReceivedTokens = false;
1917
+ pendingFinalize = stream.finalize().then(() => {
1918
+ markStreamFinalized();
1919
+ });
1920
+ if (!hasMedia) return;
1921
+ return {
1922
+ ...payload,
1923
+ text: void 0
1924
+ };
1925
+ },
1926
+ async finalize() {
1927
+ progressDraftGate.cancel();
1928
+ await pendingFinalize;
1929
+ if (!pendingFinalize) {
1930
+ await stream?.finalize();
1931
+ markStreamFinalized();
1932
+ }
1933
+ },
1934
+ hasStream() {
1935
+ return Boolean(stream);
1936
+ },
1937
+ liveState() {
1938
+ return liveState;
1939
+ },
1940
+ /**
1941
+ * Whether the Teams streaming card is currently receiving LLM tokens.
1942
+ * Used to gate side-channel keepalive activity so we don't overlay plain
1943
+ * "typing" indicators on top of a live streaming card.
1944
+ *
1945
+ * Returns true only while the stream is actively chunking text into the
1946
+ * streaming card. The informative update (blue progress bar) is short
1947
+ * lived so we intentionally do not count it as "active"; this way the
1948
+ * typing keepalive can still fire during the informative window and
1949
+ * during tool chains between text segments.
1950
+ *
1951
+ * Returns false when:
1952
+ * - No stream exists (non-personal conversation).
1953
+ * - Stream has not yet received any text tokens.
1954
+ * - Stream has been finalized (e.g. after the first text segment, while
1955
+ * tools run before the next segment).
1956
+ */
1957
+ isStreamActive() {
1958
+ if (!stream) return false;
1959
+ if (stream.isFinalized || stream.isFailed) return false;
1960
+ return streamReceivedTokens;
1961
+ }
1962
+ };
1963
+ }
1964
+ //#endregion
1965
+ //#region extensions/msteams/src/reply-dispatcher.ts
1966
+ function createMSTeamsReplyDispatcher(params) {
1967
+ const core = getMSTeamsRuntime();
1968
+ const msteamsCfg = params.cfg.channels?.msteams;
1969
+ const conversationType = normalizeOptionalLowercaseString(params.conversationRef.conversation?.conversationType);
1970
+ const isTypingSupported = conversationType === "personal" || conversationType === "groupchat";
1971
+ /**
1972
+ * Keepalive cadence for the typing indicator while the bot is running
1973
+ * (including long tool chains). Bot Framework 1:1 TurnContext proxies
1974
+ * expire after ~30s of inactivity; sending a typing activity every 8s
1975
+ * keeps the proxy alive so the post-tool reply can still land via the
1976
+ * turn context. Sits in the middle of the 5-10s range recommended in
1977
+ * #59731.
1978
+ */
1979
+ const TYPING_KEEPALIVE_INTERVAL_MS = 8e3;
1980
+ /**
1981
+ * TTL ceiling for the typing keepalive loop. The default in
1982
+ * createTypingCallbacks is 60s, which is too short for the Teams long tool
1983
+ * chains described in #59731 (60s+ total runs are common). Give tool
1984
+ * chains up to 10 minutes before auto-stopping the keepalive.
1985
+ */
1986
+ const TYPING_KEEPALIVE_MAX_DURATION_MS = 10 * 6e4;
1987
+ const streamActiveRef = { current: () => false };
1988
+ const rawSendTypingIndicator = async () => {
1989
+ await withRevokedProxyFallback({
1990
+ run: async () => {
1991
+ await params.context.sendActivity({ type: "typing" });
1992
+ },
1993
+ onRevoked: async () => {
1994
+ const baseRef = buildConversationReference(params.conversationRef);
1995
+ await params.adapter.continueConversation(params.appId, {
1996
+ ...baseRef,
1997
+ activityId: void 0
1998
+ }, async (ctx) => {
1999
+ await ctx.sendActivity({ type: "typing" });
2000
+ });
2001
+ },
2002
+ onRevokedLog: () => {
2003
+ params.log.debug?.("turn context revoked, sending typing via proactive messaging");
2004
+ }
2005
+ });
2006
+ };
2007
+ const sendTypingIndicator = isTypingSupported ? async () => {
2008
+ if (streamActiveRef.current()) return;
2009
+ await rawSendTypingIndicator();
2010
+ } : async () => {};
2011
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
2012
+ cfg: params.cfg,
2013
+ agentId: params.agentId,
2014
+ channel: "msteams",
2015
+ accountId: params.accountId,
2016
+ typing: {
2017
+ start: sendTypingIndicator,
2018
+ keepaliveIntervalMs: TYPING_KEEPALIVE_INTERVAL_MS,
2019
+ maxDurationMs: TYPING_KEEPALIVE_MAX_DURATION_MS,
2020
+ onStartError: (err) => {
2021
+ logTypingFailure({
2022
+ log: (message) => params.log.debug?.(message),
2023
+ channel: "msteams",
2024
+ action: "start",
2025
+ error: err
2026
+ });
2027
+ }
2028
+ }
2029
+ });
2030
+ const chunkMode = core.channel.text.resolveChunkMode(params.cfg, "msteams");
2031
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2032
+ cfg: params.cfg,
2033
+ channel: "msteams"
2034
+ });
2035
+ const mediaMaxBytes = resolveChannelMediaMaxBytes({
2036
+ cfg: params.cfg,
2037
+ resolveChannelLimitMb: ({ cfg }) => cfg.channels?.msteams?.mediaMaxMb
2038
+ });
2039
+ const feedbackLoopEnabled = params.cfg.channels?.msteams?.feedbackEnabled !== false;
2040
+ const streamController = createTeamsReplyStreamController({
2041
+ conversationType,
2042
+ context: params.context,
2043
+ feedbackLoopEnabled,
2044
+ log: params.log,
2045
+ msteamsConfig: msteamsCfg,
2046
+ progressSeed: `${params.accountId ?? "default"}:${params.conversationRef.conversation?.id ?? ""}`
2047
+ });
2048
+ streamActiveRef.current = () => streamController.isStreamActive();
2049
+ const resolvedBlockStreamingEnabled = resolveChannelPreviewStreamMode(msteamsCfg, "partial") === "block" ? true : resolveChannelStreamingBlockEnabled(msteamsCfg);
2050
+ const blockStreamingEnabled = resolvedBlockStreamingEnabled ?? false;
2051
+ const typingIndicatorEnabled = typeof msteamsCfg?.typingIndicator === "boolean" ? msteamsCfg.typingIndicator : true;
2052
+ const pendingMessages = [];
2053
+ const sendMessages = async (messages) => {
2054
+ return sendMSTeamsMessages({
2055
+ replyStyle: params.replyStyle,
2056
+ adapter: params.adapter,
2057
+ appId: params.appId,
2058
+ conversationRef: params.conversationRef,
2059
+ context: params.context,
2060
+ messages,
2061
+ retry: {},
2062
+ onRetry: (event) => {
2063
+ params.log.debug?.("retrying send", {
2064
+ replyStyle: params.replyStyle,
2065
+ ...event
2066
+ });
2067
+ },
2068
+ tokenProvider: params.tokenProvider,
2069
+ sharePointSiteId: params.sharePointSiteId,
2070
+ mediaMaxBytes,
2071
+ feedbackLoopEnabled
2072
+ });
2073
+ };
2074
+ const queueDeliveryFailureSystemEvent = (failure) => {
2075
+ const classification = classifyMSTeamsSendError(failure.error);
2076
+ const errorText = formatUnknownError(failure.error);
2077
+ const failedAll = failure.failed >= failure.total;
2078
+ const sentences = [
2079
+ `Microsoft Teams delivery failed: ${failedAll ? "the previous reply was not delivered" : `${failure.failed} of ${failure.total} message blocks were not delivered`}.`,
2080
+ `The user may not have received ${failedAll ? "that reply" : "the full reply"}.`,
2081
+ `Error: ${errorText}.`,
2082
+ classification.statusCode != null ? `Status: ${classification.statusCode}.` : void 0,
2083
+ classification.kind === "transient" || classification.kind === "throttled" ? "Retrying later may succeed." : void 0
2084
+ ].filter(Boolean);
2085
+ core.system.enqueueSystemEvent(sentences.join(" "), {
2086
+ sessionKey: params.sessionKey,
2087
+ contextKey: `msteams:delivery-failure:${params.conversationRef.conversation?.id ?? "unknown"}`
2088
+ });
2089
+ };
2090
+ const flushPendingMessages = async () => {
2091
+ if (pendingMessages.length === 0) return;
2092
+ const toSend = pendingMessages.splice(0);
2093
+ const total = toSend.length;
2094
+ let ids;
2095
+ try {
2096
+ ids = await sendMessages(toSend);
2097
+ } catch (batchError) {
2098
+ ids = [];
2099
+ let failed = 0;
2100
+ let lastFailedError = batchError;
2101
+ for (const msg of toSend) try {
2102
+ const msgIds = await sendMessages([msg]);
2103
+ ids.push(...msgIds);
2104
+ } catch (msgError) {
2105
+ failed += 1;
2106
+ lastFailedError = msgError;
2107
+ params.log.debug?.("individual message send failed, continuing with remaining blocks");
2108
+ }
2109
+ if (failed > 0) {
2110
+ params.log.warn?.(`failed to deliver ${failed} of ${total} message blocks`, {
2111
+ failed,
2112
+ total
2113
+ });
2114
+ queueDeliveryFailureSystemEvent({
2115
+ failed,
2116
+ total,
2117
+ error: lastFailedError
2118
+ });
2119
+ }
2120
+ }
2121
+ if (ids.length > 0) params.onSentMessageIds?.(ids);
2122
+ };
2123
+ const { dispatcher, replyOptions, markDispatchIdle: baseMarkDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
2124
+ ...replyPipeline,
2125
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(params.cfg, params.agentId),
2126
+ onReplyStart: async () => {
2127
+ await streamController.onReplyStart();
2128
+ if (typingIndicatorEnabled) await typingCallbacks?.onReplyStart?.();
2129
+ },
2130
+ typingCallbacks,
2131
+ deliver: async (payload) => {
2132
+ const preparedPayload = await streamController.preparePayload(payload);
2133
+ if (!preparedPayload) return;
2134
+ const messages = renderReplyPayloadsToMessages([preparedPayload], {
2135
+ textChunkLimit: params.textLimit,
2136
+ chunkText: true,
2137
+ mediaMode: "split",
2138
+ tableMode,
2139
+ chunkMode
2140
+ });
2141
+ pendingMessages.push(...messages);
2142
+ if (blockStreamingEnabled) await flushPendingMessages();
2143
+ },
2144
+ onError: (err, info) => {
2145
+ const errMsg = formatUnknownError(err);
2146
+ const classification = classifyMSTeamsSendError(err);
2147
+ const hint = formatMSTeamsSendErrorHint(classification);
2148
+ params.runtime.error?.(`msteams ${info.kind} reply failed: ${errMsg}${hint ? ` (${hint})` : ""}`);
2149
+ params.log.error("reply failed", {
2150
+ kind: info.kind,
2151
+ error: errMsg,
2152
+ classification,
2153
+ hint
2154
+ });
2155
+ }
2156
+ });
2157
+ const markDispatchIdle = () => {
2158
+ return flushPendingMessages().catch((err) => {
2159
+ const errMsg = formatUnknownError(err);
2160
+ const classification = classifyMSTeamsSendError(err);
2161
+ const hint = formatMSTeamsSendErrorHint(classification);
2162
+ params.runtime.error?.(`msteams flush reply failed: ${errMsg}${hint ? ` (${hint})` : ""}`);
2163
+ params.log.error("flush reply failed", {
2164
+ error: errMsg,
2165
+ classification,
2166
+ hint
2167
+ });
2168
+ }).then(() => {
2169
+ return streamController.finalize().catch((err) => {
2170
+ params.log.debug?.("stream finalize failed", { error: formatUnknownError(err) });
2171
+ });
2172
+ }).finally(() => {
2173
+ baseMarkDispatchIdle();
2174
+ });
2175
+ };
2176
+ return {
2177
+ dispatcher,
2178
+ replyOptions: {
2179
+ ...replyOptions,
2180
+ ...streamController.hasStream() ? {
2181
+ onPartialReply: (payload) => streamController.onPartialReply(payload),
2182
+ onToolStart: async (payload) => {
2183
+ await streamController.noteProgressWork({ toolName: payload.name });
2184
+ },
2185
+ onItemEvent: async () => {
2186
+ await streamController.noteProgressWork();
2187
+ },
2188
+ onPlanUpdate: async (payload) => {
2189
+ if (payload.phase === "update") await streamController.noteProgressWork();
2190
+ },
2191
+ onApprovalEvent: async (payload) => {
2192
+ if (payload.phase === "requested") await streamController.noteProgressWork();
2193
+ },
2194
+ onCommandOutput: async (payload) => {
2195
+ if (payload.phase === "end") await streamController.noteProgressWork();
2196
+ },
2197
+ onPatchSummary: async (payload) => {
2198
+ if (payload.phase === "end") await streamController.noteProgressWork();
2199
+ }
2200
+ } : {},
2201
+ ...streamController.shouldSuppressDefaultToolProgressMessages() ? { suppressDefaultToolProgressMessages: true } : {},
2202
+ ...streamController.shouldStreamPreviewToolProgress() ? {
2203
+ onToolStart: async (payload) => {
2204
+ await streamController.pushProgressLine(buildChannelProgressDraftLineForEntry(msteamsCfg, {
2205
+ event: "tool",
2206
+ name: payload.name,
2207
+ phase: payload.phase,
2208
+ args: payload.args
2209
+ }, payload.detailMode ? { detailMode: payload.detailMode } : void 0), { toolName: payload.name });
2210
+ },
2211
+ onItemEvent: async (payload) => {
2212
+ await streamController.pushProgressLine(buildChannelProgressDraftLineForEntry(msteamsCfg, {
2213
+ event: "item",
2214
+ itemId: payload.itemId,
2215
+ itemKind: payload.kind,
2216
+ title: payload.title,
2217
+ name: payload.name,
2218
+ phase: payload.phase,
2219
+ status: payload.status,
2220
+ summary: payload.summary,
2221
+ progressText: payload.progressText,
2222
+ meta: payload.meta
2223
+ }));
2224
+ },
2225
+ onPlanUpdate: async (payload) => {
2226
+ if (payload.phase !== "update") return;
2227
+ await streamController.pushProgressLine(buildChannelProgressDraftLine({
2228
+ event: "plan",
2229
+ phase: payload.phase,
2230
+ title: payload.title,
2231
+ explanation: payload.explanation,
2232
+ steps: payload.steps
2233
+ }));
2234
+ },
2235
+ onApprovalEvent: async (payload) => {
2236
+ if (payload.phase !== "requested") return;
2237
+ await streamController.pushProgressLine(buildChannelProgressDraftLine({
2238
+ event: "approval",
2239
+ phase: payload.phase,
2240
+ title: payload.title,
2241
+ command: payload.command,
2242
+ reason: payload.reason,
2243
+ message: payload.message
2244
+ }));
2245
+ },
2246
+ onCommandOutput: async (payload) => {
2247
+ if (payload.phase !== "end") return;
2248
+ await streamController.pushProgressLine(buildChannelProgressDraftLine({
2249
+ event: "command-output",
2250
+ phase: payload.phase,
2251
+ title: payload.title,
2252
+ name: payload.name,
2253
+ status: payload.status,
2254
+ exitCode: payload.exitCode
2255
+ }));
2256
+ },
2257
+ onPatchSummary: async (payload) => {
2258
+ if (payload.phase !== "end") return;
2259
+ await streamController.pushProgressLine(buildChannelProgressDraftLine({
2260
+ event: "patch",
2261
+ phase: payload.phase,
2262
+ title: payload.title,
2263
+ name: payload.name,
2264
+ added: payload.added,
2265
+ modified: payload.modified,
2266
+ deleted: payload.deleted,
2267
+ summary: payload.summary
2268
+ }));
2269
+ }
2270
+ } : {},
2271
+ disableBlockStreaming: typeof resolvedBlockStreamingEnabled === "boolean" ? !resolvedBlockStreamingEnabled : void 0,
2272
+ onModelSelected
2273
+ },
2274
+ markDispatchIdle
2275
+ };
2276
+ }
2277
+ //#endregion
2278
+ //#region extensions/msteams/src/sent-message-cache.ts
2279
+ const TTL_MS = 1440 * 60 * 1e3;
2280
+ const PERSISTENT_MAX_ENTRIES = 1e3;
2281
+ const PERSISTENT_NAMESPACE = "msteams.sent-messages";
2282
+ const MSTEAMS_SENT_MESSAGES_KEY = Symbol.for("klaw.msteamsSentMessages");
2283
+ let sentMessageCache;
2284
+ let persistentStore;
2285
+ let persistentStoreDisabled = false;
2286
+ function getSentMessageCache() {
2287
+ if (!sentMessageCache) {
2288
+ const globalStore = globalThis;
2289
+ sentMessageCache = globalStore[MSTEAMS_SENT_MESSAGES_KEY] ?? /* @__PURE__ */ new Map();
2290
+ globalStore[MSTEAMS_SENT_MESSAGES_KEY] = sentMessageCache;
2291
+ }
2292
+ return sentMessageCache;
2293
+ }
2294
+ function makePersistentKey(conversationId, messageId) {
2295
+ return `${conversationId}:${messageId}`;
2296
+ }
2297
+ function reportPersistentSentMessageError(error) {
2298
+ try {
2299
+ getOptionalMSTeamsRuntime()?.logging.getChildLogger({
2300
+ plugin: "msteams",
2301
+ feature: "sent-message-state"
2302
+ }).warn("Microsoft Teams persistent sent-message state failed", { error: String(error) });
2303
+ } catch {}
2304
+ }
2305
+ function disablePersistentSentMessageStore(error) {
2306
+ persistentStoreDisabled = true;
2307
+ persistentStore = void 0;
2308
+ reportPersistentSentMessageError(error);
2309
+ }
2310
+ function getPersistentSentMessageStore() {
2311
+ if (persistentStoreDisabled) return;
2312
+ if (persistentStore) return persistentStore;
2313
+ const runtime = getOptionalMSTeamsRuntime();
2314
+ if (!runtime) return;
2315
+ try {
2316
+ persistentStore = runtime.state.openKeyedStore({
2317
+ namespace: PERSISTENT_NAMESPACE,
2318
+ maxEntries: PERSISTENT_MAX_ENTRIES,
2319
+ defaultTtlMs: TTL_MS
2320
+ });
2321
+ return persistentStore;
2322
+ } catch (error) {
2323
+ disablePersistentSentMessageStore(error);
2324
+ return;
2325
+ }
2326
+ }
2327
+ function cleanupExpired(scopeKey, entry, now) {
2328
+ for (const [id, timestamp] of entry) if (now - timestamp > TTL_MS) entry.delete(id);
2329
+ if (entry.size === 0) getSentMessageCache().delete(scopeKey);
2330
+ }
2331
+ function rememberSentMessageInMemory(conversationId, messageId, sentAt) {
2332
+ const store = getSentMessageCache();
2333
+ let entry = store.get(conversationId);
2334
+ if (!entry) {
2335
+ entry = /* @__PURE__ */ new Map();
2336
+ store.set(conversationId, entry);
2337
+ }
2338
+ entry.set(messageId, sentAt);
2339
+ if (entry.size > 200) cleanupExpired(conversationId, entry, sentAt);
2340
+ }
2341
+ function rememberPersistentSentMessage(params) {
2342
+ const store = getPersistentSentMessageStore();
2343
+ if (!store) return;
2344
+ store.register(makePersistentKey(params.conversationId, params.messageId), { sentAt: params.sentAt }).catch(disablePersistentSentMessageStore);
2345
+ }
2346
+ async function lookupPersistentSentMessage(params) {
2347
+ const store = getPersistentSentMessageStore();
2348
+ if (!store) return;
2349
+ try {
2350
+ return (await store.lookup(makePersistentKey(params.conversationId, params.messageId)))?.sentAt;
2351
+ } catch (error) {
2352
+ disablePersistentSentMessageStore(error);
2353
+ return;
2354
+ }
2355
+ }
2356
+ function recordMSTeamsSentMessage(conversationId, messageId) {
2357
+ if (!conversationId || !messageId) return;
2358
+ const now = Date.now();
2359
+ rememberSentMessageInMemory(conversationId, messageId, now);
2360
+ rememberPersistentSentMessage({
2361
+ conversationId,
2362
+ messageId,
2363
+ sentAt: now
2364
+ });
2365
+ }
2366
+ function wasMSTeamsMessageSent(conversationId, messageId) {
2367
+ const entry = getSentMessageCache().get(conversationId);
2368
+ if (!entry) return false;
2369
+ cleanupExpired(conversationId, entry, Date.now());
2370
+ return entry.has(messageId);
2371
+ }
2372
+ async function wasMSTeamsMessageSentWithPersistence(params) {
2373
+ if (!params.conversationId || !params.messageId) return false;
2374
+ if (wasMSTeamsMessageSent(params.conversationId, params.messageId)) return true;
2375
+ const sentAt = await lookupPersistentSentMessage(params);
2376
+ if (sentAt == null) return false;
2377
+ rememberSentMessageInMemory(params.conversationId, params.messageId, sentAt);
2378
+ return wasMSTeamsMessageSent(params.conversationId, params.messageId);
2379
+ }
2380
+ //#endregion
2381
+ //#region extensions/msteams/src/monitor-handler/inbound-media.ts
2382
+ async function resolveMSTeamsInboundMedia(params) {
2383
+ const { attachments, htmlSummary, maxBytes, tokenProvider, allowHosts, conversationType, conversationId, conversationMessageId, serviceUrl, activity, log, preserveFilenames } = params;
2384
+ let mediaList = await downloadMSTeamsAttachments({
2385
+ attachments,
2386
+ maxBytes,
2387
+ tokenProvider,
2388
+ allowHosts,
2389
+ authAllowHosts: params.authAllowHosts,
2390
+ preserveFilenames,
2391
+ logger: log
2392
+ });
2393
+ if (mediaList.length === 0) {
2394
+ const attachmentIds = extractMSTeamsHtmlAttachmentIds(attachments);
2395
+ const hasHtmlFileAttachment = attachmentIds.length > 0;
2396
+ if (hasHtmlFileAttachment && isBotFrameworkPersonalChatId(conversationId)) if (!serviceUrl) log.debug?.("bot framework attachment skipped (missing serviceUrl)", {
2397
+ conversationType,
2398
+ conversationId
2399
+ });
2400
+ else {
2401
+ const bfMedia = await downloadMSTeamsBotFrameworkAttachments({
2402
+ serviceUrl,
2403
+ attachmentIds,
2404
+ tokenProvider,
2405
+ maxBytes,
2406
+ allowHosts,
2407
+ authAllowHosts: params.authAllowHosts,
2408
+ preserveFilenames
2409
+ });
2410
+ if (bfMedia.media.length > 0) mediaList = bfMedia.media;
2411
+ else log.debug?.("bot framework attachments fetch empty", {
2412
+ conversationType,
2413
+ attachmentCount: bfMedia.attachmentCount ?? attachmentIds.length
2414
+ });
2415
+ }
2416
+ if (hasHtmlFileAttachment && mediaList.length === 0 && !isBotFrameworkPersonalChatId(conversationId)) {
2417
+ const messageUrls = buildMSTeamsGraphMessageUrls({
2418
+ conversationType,
2419
+ conversationId,
2420
+ messageId: activity.id ?? void 0,
2421
+ replyToId: activity.replyToId ?? void 0,
2422
+ conversationMessageId,
2423
+ channelData: activity.channelData
2424
+ });
2425
+ if (messageUrls.length === 0) log.debug?.("graph message url unavailable", {
2426
+ conversationType,
2427
+ hasChannelData: Boolean(activity.channelData),
2428
+ messageId: activity.id ?? void 0,
2429
+ replyToId: activity.replyToId ?? void 0
2430
+ });
2431
+ else {
2432
+ const attempts = [];
2433
+ for (const messageUrl of messageUrls) {
2434
+ const graphMedia = await downloadMSTeamsGraphMedia({
2435
+ messageUrl,
2436
+ tokenProvider,
2437
+ maxBytes,
2438
+ allowHosts,
2439
+ authAllowHosts: params.authAllowHosts,
2440
+ preserveFilenames,
2441
+ log,
2442
+ logger: log
2443
+ });
2444
+ attempts.push({
2445
+ url: messageUrl,
2446
+ hostedStatus: graphMedia.hostedStatus,
2447
+ attachmentStatus: graphMedia.attachmentStatus,
2448
+ hostedCount: graphMedia.hostedCount,
2449
+ attachmentCount: graphMedia.attachmentCount,
2450
+ tokenError: graphMedia.tokenError
2451
+ });
2452
+ if (graphMedia.media.length > 0) {
2453
+ mediaList = graphMedia.media;
2454
+ break;
2455
+ }
2456
+ if (graphMedia.tokenError) break;
2457
+ }
2458
+ if (mediaList.length === 0) log.debug?.("graph media fetch empty", {
2459
+ attempts,
2460
+ attachmentIdCount: attachmentIds.length
2461
+ });
2462
+ }
2463
+ }
2464
+ }
2465
+ if (mediaList.length > 0) log.debug?.("downloaded attachments", { count: mediaList.length });
2466
+ else if (htmlSummary?.imgTags) log.debug?.("inline images detected but none downloaded", {
2467
+ imgTags: htmlSummary.imgTags,
2468
+ srcHosts: htmlSummary.srcHosts,
2469
+ dataImages: htmlSummary.dataImages,
2470
+ cidImages: htmlSummary.cidImages
2471
+ });
2472
+ return mediaList;
2473
+ }
2474
+ //#endregion
2475
+ //#region extensions/msteams/src/monitor-handler/thread-session.ts
2476
+ const TRAILING_THREAD_SUFFIX = /(?::thread:[^:]+)+$/;
2477
+ function resolveMSTeamsRouteSessionKey(params) {
2478
+ const channelThreadId = params.isChannel ? params.conversationMessageId ?? params.replyToId ?? void 0 : void 0;
2479
+ const cleanBase = params.baseSessionKey.replace(TRAILING_THREAD_SUFFIX, "");
2480
+ return resolveThreadSessionKeys({
2481
+ baseSessionKey: cleanBase,
2482
+ threadId: channelThreadId,
2483
+ parentSessionKey: channelThreadId ? cleanBase : void 0
2484
+ }).sessionKey;
2485
+ }
2486
+ //#endregion
2487
+ //#region extensions/msteams/src/monitor-handler/message-handler.ts
2488
+ function extractTextFromHtmlAttachments(attachments) {
2489
+ for (const attachment of attachments) {
2490
+ if (attachment.contentType !== "text/html") continue;
2491
+ const content = attachment.content;
2492
+ const raw = typeof content === "string" ? content : isRecord$1(content) && typeof content.text === "string" ? content.text : isRecord$1(content) && typeof content.body === "string" ? content.body : "";
2493
+ if (!raw) continue;
2494
+ const text = raw.replace(/<at[^>]*>.*?<\/at>/gis, " ").replace(/<a\b[^>]*href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gis, "$2 $1").replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/\s+/g, " ").trim();
2495
+ if (text) return text;
2496
+ }
2497
+ return "";
2498
+ }
2499
+ function formatMSTeamsSenderReason(params) {
2500
+ switch (params.reasonCode) {
2501
+ case "dm_policy_open": return "dmPolicy=open";
2502
+ case "dm_policy_disabled": return "dmPolicy=disabled";
2503
+ case "dm_policy_pairing_required": return "dmPolicy=pairing (not allowlisted)";
2504
+ case "dm_policy_allowlisted": return `dmPolicy=${params.dmPolicy ?? "allowlist"} (allowlisted)`;
2505
+ case "dm_policy_not_allowlisted": return `dmPolicy=${params.dmPolicy ?? "allowlist"} (not allowlisted)`;
2506
+ case "group_policy_disabled": return "groupPolicy=disabled";
2507
+ case "group_policy_empty_allowlist":
2508
+ case "route_sender_empty": return "groupPolicy=allowlist (empty allowlist)";
2509
+ case "group_policy_not_allowlisted": return "groupPolicy=allowlist (not allowlisted)";
2510
+ case "group_policy_open": return "groupPolicy=open";
2511
+ case "group_policy_allowed": return `groupPolicy=${params.groupPolicy ?? "allowlist"}`;
2512
+ default: return params.reasonCode;
2513
+ }
2514
+ }
2515
+ function buildStoredConversationReference(params) {
2516
+ const { activity, conversationId, conversationType, teamId, threadId } = params;
2517
+ const from = activity.from;
2518
+ const conversation = activity.conversation;
2519
+ const agent = activity.recipient;
2520
+ const clientInfo = activity.entities?.find((e) => e.type === "clientInfo");
2521
+ const tenantId = activity.channelData?.tenant?.id ?? conversation?.tenantId;
2522
+ const aadObjectId = from?.aadObjectId;
2523
+ return {
2524
+ activityId: activity.id,
2525
+ user: from ? {
2526
+ id: from.id,
2527
+ name: from.name,
2528
+ aadObjectId: from.aadObjectId
2529
+ } : void 0,
2530
+ agent,
2531
+ bot: agent ? {
2532
+ id: agent.id,
2533
+ name: agent.name
2534
+ } : void 0,
2535
+ conversation: {
2536
+ id: conversationId,
2537
+ conversationType,
2538
+ tenantId
2539
+ },
2540
+ ...tenantId ? { tenantId } : {},
2541
+ ...aadObjectId ? { aadObjectId } : {},
2542
+ teamId,
2543
+ channelId: activity.channelId,
2544
+ serviceUrl: activity.serviceUrl,
2545
+ locale: activity.locale,
2546
+ ...clientInfo?.timezone ? { timezone: clientInfo.timezone } : {},
2547
+ ...threadId ? { threadId } : {}
2548
+ };
2549
+ }
2550
+ function createMSTeamsMessageHandler(deps) {
2551
+ const { cfg, runtime, appId, adapter, tokenProvider, textLimit, mediaMaxBytes, conversationStore, pollStore, log } = deps;
2552
+ const core = getMSTeamsRuntime();
2553
+ const logVerboseMessage = (message) => {
2554
+ if (core.logging.shouldLogVerbose()) log.debug?.(message);
2555
+ };
2556
+ const msteamsCfg = cfg.channels?.msteams;
2557
+ const contextVisibilityMode = resolveChannelContextVisibilityMode({
2558
+ cfg,
2559
+ channel: "msteams"
2560
+ });
2561
+ const historyLimit = Math.max(0, msteamsCfg?.historyLimit ?? cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
2562
+ const conversationHistories = /* @__PURE__ */ new Map();
2563
+ const inboundDebounceMs = core.channel.debounce.resolveInboundDebounceMs({
2564
+ cfg,
2565
+ channel: "msteams"
2566
+ });
2567
+ const handleTeamsMessageNow = async (params) => {
2568
+ const context = params.context;
2569
+ const activity = context.activity;
2570
+ const rawText = params.rawText;
2571
+ const text = params.text;
2572
+ const attachments = params.attachments;
2573
+ const attachmentPlaceholder = buildMSTeamsAttachmentPlaceholder(attachments, {
2574
+ maxInlineBytes: mediaMaxBytes,
2575
+ maxInlineTotalBytes: mediaMaxBytes
2576
+ });
2577
+ const rawBody = text || attachmentPlaceholder;
2578
+ const quoteInfo = extractMSTeamsQuoteInfo(attachments);
2579
+ let quoteSenderId;
2580
+ let quoteSenderName;
2581
+ const from = activity.from;
2582
+ const conversation = activity.conversation;
2583
+ const attachmentTypes = attachments.map((att) => typeof att.contentType === "string" ? att.contentType : void 0).filter(Boolean).slice(0, 3);
2584
+ const htmlSummary = summarizeMSTeamsHtmlAttachments(attachments);
2585
+ log.info("received message", {
2586
+ rawText: rawText.slice(0, 50),
2587
+ text: text.slice(0, 50),
2588
+ attachments: attachments.length,
2589
+ attachmentTypes,
2590
+ from: from?.id,
2591
+ conversation: conversation?.id
2592
+ });
2593
+ if (htmlSummary) log.debug?.("html attachment summary", htmlSummary);
2594
+ if (!from?.id) {
2595
+ log.debug?.("skipping message without from.id");
2596
+ return;
2597
+ }
2598
+ const rawConversationId = conversation?.id ?? "";
2599
+ const conversationId = normalizeMSTeamsConversationId(rawConversationId);
2600
+ const conversationMessageId = extractMSTeamsConversationMessageId(rawConversationId);
2601
+ const conversationType = conversation?.conversationType ?? "personal";
2602
+ const teamId = activity.channelData?.team?.id;
2603
+ const conversationRef = buildStoredConversationReference({
2604
+ activity,
2605
+ conversationId,
2606
+ conversationType,
2607
+ teamId,
2608
+ threadId: conversationType === "channel" ? conversationMessageId ?? activity.replyToId ?? void 0 : void 0
2609
+ });
2610
+ const { dmPolicy, senderId, senderName, pairing, isDirectMessage, channelGate, senderAccess, commandAccess, allowNameMatching, groupPolicy } = await resolveMSTeamsSenderAccess({
2611
+ cfg,
2612
+ activity,
2613
+ hasControlCommand: core.channel.text.hasControlCommand(text, cfg)
2614
+ });
2615
+ const commandAuthorized = commandAccess.requested ? commandAccess.authorized : void 0;
2616
+ const effectiveDmAllowFrom = senderAccess.effectiveAllowFrom;
2617
+ const effectiveGroupAllowFrom = senderAccess.effectiveGroupAllowFrom;
2618
+ const isChannel = conversationType === "channel";
2619
+ if (isDirectMessage && msteamsCfg && senderAccess.decision !== "allow") {
2620
+ if (senderAccess.reasonCode === "dm_policy_disabled") {
2621
+ log.info("dropping dm (dms disabled)", {
2622
+ sender: senderId,
2623
+ label: senderName
2624
+ });
2625
+ log.debug?.("dropping dm (dms disabled)");
2626
+ return;
2627
+ }
2628
+ const allowMatch = resolveMSTeamsAllowlistMatch({
2629
+ allowFrom: effectiveDmAllowFrom,
2630
+ senderId,
2631
+ senderName,
2632
+ allowNameMatching
2633
+ });
2634
+ if (senderAccess.decision === "pairing") {
2635
+ conversationStore.upsert(conversationId, conversationRef).catch((err) => {
2636
+ log.debug?.("failed to save conversation reference", { error: formatUnknownError(err) });
2637
+ });
2638
+ if (await pairing.upsertPairingRequest({
2639
+ id: senderId,
2640
+ meta: { name: senderName }
2641
+ })) log.info("msteams pairing request created", {
2642
+ sender: senderId,
2643
+ label: senderName
2644
+ });
2645
+ }
2646
+ log.debug?.("dropping dm (not allowlisted)", {
2647
+ sender: senderId,
2648
+ label: senderName,
2649
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch)
2650
+ });
2651
+ log.info("dropping dm (not allowlisted)", {
2652
+ sender: senderId,
2653
+ label: senderName,
2654
+ dmPolicy,
2655
+ reason: formatMSTeamsSenderReason({
2656
+ reasonCode: senderAccess.reasonCode,
2657
+ dmPolicy,
2658
+ groupPolicy
2659
+ }),
2660
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch)
2661
+ });
2662
+ return;
2663
+ }
2664
+ if (!isDirectMessage && msteamsCfg) {
2665
+ if (channelGate.allowlistConfigured && !channelGate.allowed) {
2666
+ log.info("dropping group message (not in team/channel allowlist)", {
2667
+ conversationId,
2668
+ teamKey: channelGate.teamKey ?? "none",
2669
+ channelKey: channelGate.channelKey ?? "none",
2670
+ channelMatchKey: channelGate.channelMatchKey ?? "none",
2671
+ channelMatchSource: channelGate.channelMatchSource ?? "none"
2672
+ });
2673
+ log.debug?.("dropping group message (not in team/channel allowlist)", {
2674
+ conversationId,
2675
+ teamKey: channelGate.teamKey ?? "none",
2676
+ channelKey: channelGate.channelKey ?? "none",
2677
+ channelMatchKey: channelGate.channelMatchKey ?? "none",
2678
+ channelMatchSource: channelGate.channelMatchSource ?? "none"
2679
+ });
2680
+ return;
2681
+ }
2682
+ if (!senderAccess.allowed && senderAccess.reasonCode === "group_policy_disabled") {
2683
+ log.info("dropping group message (groupPolicy: disabled)", { conversationId });
2684
+ log.debug?.("dropping group message (groupPolicy: disabled)", { conversationId });
2685
+ return;
2686
+ }
2687
+ if (!senderAccess.allowed && (senderAccess.reasonCode === "group_policy_empty_allowlist" || senderAccess.reasonCode === "route_sender_empty")) {
2688
+ log.info("dropping group message (groupPolicy: allowlist, no allowlist)", { conversationId });
2689
+ log.debug?.("dropping group message (groupPolicy: allowlist, no allowlist)", { conversationId });
2690
+ return;
2691
+ }
2692
+ if (!senderAccess.allowed && senderAccess.reasonCode === "group_policy_not_allowlisted") {
2693
+ const allowMatch = resolveMSTeamsAllowlistMatch({
2694
+ allowFrom: effectiveGroupAllowFrom,
2695
+ senderId,
2696
+ senderName,
2697
+ allowNameMatching
2698
+ });
2699
+ log.debug?.("dropping group message (not in groupAllowFrom)", {
2700
+ sender: senderId,
2701
+ label: senderName,
2702
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch)
2703
+ });
2704
+ log.info("dropping group message (not in groupAllowFrom)", {
2705
+ sender: senderId,
2706
+ label: senderName,
2707
+ allowlistMatch: formatAllowlistMatchMeta(allowMatch)
2708
+ });
2709
+ return;
2710
+ }
2711
+ }
2712
+ if (commandAccess.shouldBlockControlCommand) {
2713
+ logInboundDrop({
2714
+ log: logVerboseMessage,
2715
+ channel: "msteams",
2716
+ reason: "control command (unauthorized)",
2717
+ target: senderId
2718
+ });
2719
+ return;
2720
+ }
2721
+ conversationStore.upsert(conversationId, conversationRef).catch((err) => {
2722
+ log.debug?.("failed to save conversation reference", { error: formatUnknownError(err) });
2723
+ });
2724
+ const pollVote = extractMSTeamsPollVote(activity);
2725
+ if (pollVote) {
2726
+ try {
2727
+ if (!await pollStore.recordVote({
2728
+ pollId: pollVote.pollId,
2729
+ voterId: senderId,
2730
+ selections: pollVote.selections
2731
+ })) log.debug?.("poll vote ignored (poll not found)", { pollId: pollVote.pollId });
2732
+ else log.info("recorded poll vote", {
2733
+ pollId: pollVote.pollId,
2734
+ voter: senderId,
2735
+ selections: pollVote.selections
2736
+ });
2737
+ } catch (err) {
2738
+ log.error("failed to record poll vote", {
2739
+ pollId: pollVote.pollId,
2740
+ error: formatUnknownError(err)
2741
+ });
2742
+ }
2743
+ return;
2744
+ }
2745
+ if (!rawBody) {
2746
+ log.debug?.("skipping empty message after stripping mentions");
2747
+ return;
2748
+ }
2749
+ const teamsFrom = isDirectMessage ? `msteams:${senderId}` : isChannel ? `msteams:channel:${conversationId}` : `msteams:group:${conversationId}`;
2750
+ const teamsTo = isDirectMessage ? `user:${senderId}` : `conversation:${conversationId}`;
2751
+ const route = core.channel.routing.resolveAgentRoute({
2752
+ cfg,
2753
+ channel: "msteams",
2754
+ teamId,
2755
+ peer: {
2756
+ kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
2757
+ id: isDirectMessage ? senderId : conversationId
2758
+ }
2759
+ });
2760
+ route.sessionKey = resolveMSTeamsRouteSessionKey({
2761
+ baseSessionKey: route.sessionKey,
2762
+ isChannel,
2763
+ conversationMessageId,
2764
+ replyToId: activity.replyToId
2765
+ });
2766
+ const preview = rawBody.replace(/\s+/g, " ").slice(0, 160);
2767
+ const inboundLabel = isDirectMessage ? `Teams DM from ${senderName}` : `Teams message in ${conversationType} from ${senderName}`;
2768
+ core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, {
2769
+ sessionKey: route.sessionKey,
2770
+ contextKey: `msteams:message:${conversationId}:${activity.id ?? "unknown"}`
2771
+ });
2772
+ const channelId = conversationId;
2773
+ const { teamConfig, channelConfig } = channelGate;
2774
+ const { requireMention, replyStyle } = resolveMSTeamsReplyPolicy({
2775
+ isDirectMessage,
2776
+ globalConfig: msteamsCfg,
2777
+ teamConfig,
2778
+ channelConfig
2779
+ });
2780
+ const timestamp = parseMSTeamsActivityTimestamp(activity.timestamp);
2781
+ const mentionDecision = resolveInboundMentionDecision({
2782
+ facts: {
2783
+ canDetectMention: true,
2784
+ wasMentioned: params.wasMentioned,
2785
+ implicitMentionKinds: params.implicitMentionKinds
2786
+ },
2787
+ policy: {
2788
+ isGroup: !isDirectMessage,
2789
+ requireMention,
2790
+ allowTextCommands: false,
2791
+ hasControlCommand: false,
2792
+ commandAuthorized: false
2793
+ }
2794
+ });
2795
+ if (!isDirectMessage) {
2796
+ const mentioned = mentionDecision.effectiveWasMentioned;
2797
+ if (requireMention && mentionDecision.shouldSkip) {
2798
+ log.debug?.("skipping message (mention required)", {
2799
+ teamId,
2800
+ channelId,
2801
+ requireMention,
2802
+ mentioned
2803
+ });
2804
+ createChannelHistoryWindow({ historyMap: conversationHistories }).record({
2805
+ historyKey: conversationId,
2806
+ limit: historyLimit,
2807
+ entry: {
2808
+ sender: senderName,
2809
+ body: rawBody,
2810
+ timestamp: timestamp?.getTime(),
2811
+ messageId: activity.id ?? void 0
2812
+ }
2813
+ });
2814
+ return;
2815
+ }
2816
+ }
2817
+ let graphConversationId = translateMSTeamsDmConversationIdForGraph({
2818
+ isDirectMessage,
2819
+ conversationId,
2820
+ aadObjectId: from.aadObjectId,
2821
+ appId
2822
+ });
2823
+ if (isDirectMessage && conversationId.startsWith("a:")) {
2824
+ const cached = await conversationStore.get(conversationId);
2825
+ if (cached?.graphChatId) graphConversationId = cached.graphChatId;
2826
+ else try {
2827
+ const resolved = await resolveGraphChatId({
2828
+ botFrameworkConversationId: conversationId,
2829
+ userAadObjectId: from.aadObjectId ?? void 0,
2830
+ tokenProvider
2831
+ });
2832
+ if (resolved) {
2833
+ graphConversationId = resolved;
2834
+ conversationStore.upsert(conversationId, {
2835
+ ...conversationRef,
2836
+ graphChatId: resolved
2837
+ }).catch(() => {});
2838
+ }
2839
+ } catch {
2840
+ log.debug?.("failed to resolve Graph chat ID for inbound media", { conversationId });
2841
+ }
2842
+ }
2843
+ const mediaPayload = buildMSTeamsMediaPayload(await resolveMSTeamsInboundMedia({
2844
+ attachments,
2845
+ htmlSummary: htmlSummary ?? void 0,
2846
+ maxBytes: mediaMaxBytes,
2847
+ tokenProvider,
2848
+ allowHosts: msteamsCfg?.mediaAllowHosts,
2849
+ authAllowHosts: msteamsCfg?.mediaAuthAllowHosts,
2850
+ conversationType,
2851
+ conversationId: graphConversationId,
2852
+ conversationMessageId: conversationMessageId ?? void 0,
2853
+ serviceUrl: activity.serviceUrl,
2854
+ activity: {
2855
+ id: activity.id,
2856
+ replyToId: activity.replyToId,
2857
+ channelData: activity.channelData
2858
+ },
2859
+ log,
2860
+ preserveFilenames: cfg.media?.preserveFilenames
2861
+ }));
2862
+ let threadContext;
2863
+ if (activity.replyToId && isChannel && teamId) try {
2864
+ const graphToken = await tokenProvider.getAccessToken("https://graph.microsoft.com");
2865
+ const groupId = await resolveTeamGroupId(graphToken, teamId);
2866
+ const [parentResult, repliesResult] = await Promise.allSettled([fetchParentMessageCached(graphToken, groupId, conversationId, activity.replyToId), fetchThreadReplies(graphToken, groupId, conversationId, activity.replyToId)]);
2867
+ const parentMsg = parentResult.status === "fulfilled" ? parentResult.value : void 0;
2868
+ const replies = repliesResult.status === "fulfilled" ? repliesResult.value : [];
2869
+ if (parentResult.status === "rejected") log.debug?.("failed to fetch parent message", { error: formatUnknownError(parentResult.reason) });
2870
+ if (repliesResult.status === "rejected") log.debug?.("failed to fetch thread replies", { error: formatUnknownError(repliesResult.reason) });
2871
+ const isThreadSenderAllowed = (msg) => groupPolicy === "allowlist" ? resolveMSTeamsAllowlistMatch({
2872
+ allowFrom: effectiveGroupAllowFrom,
2873
+ senderId: msg.from?.user?.id ?? "",
2874
+ senderName: msg.from?.user?.displayName,
2875
+ allowNameMatching
2876
+ }).allowed : true;
2877
+ const parentSummary = summarizeParentMessage(parentMsg);
2878
+ const visibleParentMessages = parentMsg ? filterSupplementalContextItems({
2879
+ items: [parentMsg],
2880
+ mode: contextVisibilityMode,
2881
+ kind: "thread",
2882
+ isSenderAllowed: isThreadSenderAllowed
2883
+ }).items : [];
2884
+ if (parentSummary && visibleParentMessages.length > 0 && shouldInjectParentContext(route.sessionKey, activity.replyToId)) {
2885
+ core.system.enqueueSystemEvent(formatParentContextEvent(parentSummary), {
2886
+ sessionKey: route.sessionKey,
2887
+ contextKey: `msteams:thread-parent:${conversationId}:${activity.replyToId}`
2888
+ });
2889
+ markParentContextInjected(route.sessionKey, activity.replyToId);
2890
+ }
2891
+ const allMessages = parentMsg ? [parentMsg, ...replies] : replies;
2892
+ quoteSenderId = parentMsg?.from?.user?.id ?? parentMsg?.from?.application?.id ?? void 0;
2893
+ quoteSenderName = parentMsg?.from?.user?.displayName ?? parentMsg?.from?.application?.displayName ?? quoteInfo?.sender;
2894
+ const { items: threadMessages } = filterSupplementalContextItems({
2895
+ items: allMessages,
2896
+ mode: contextVisibilityMode,
2897
+ kind: "thread",
2898
+ isSenderAllowed: isThreadSenderAllowed
2899
+ });
2900
+ const formatted = formatThreadContext(threadMessages, activity.id);
2901
+ if (formatted) threadContext = formatted;
2902
+ } catch (err) {
2903
+ log.debug?.("failed to fetch thread history", { error: formatUnknownError(err) });
2904
+ }
2905
+ quoteSenderName ??= quoteInfo?.sender;
2906
+ const envelopeFrom = isDirectMessage ? senderName : conversationType;
2907
+ const { storePath, envelopeOptions, previousTimestamp } = resolveInboundSessionEnvelopeContext({
2908
+ cfg,
2909
+ agentId: route.agentId,
2910
+ sessionKey: route.sessionKey
2911
+ });
2912
+ let combinedBody = core.channel.reply.formatAgentEnvelope({
2913
+ channel: "Teams",
2914
+ from: envelopeFrom,
2915
+ timestamp,
2916
+ previousTimestamp,
2917
+ envelope: envelopeOptions,
2918
+ body: rawBody
2919
+ });
2920
+ const isRoomish = !isDirectMessage;
2921
+ const historyKey = isRoomish ? conversationId : void 0;
2922
+ if (isRoomish && historyKey) combinedBody = createChannelHistoryWindow({ historyMap: conversationHistories }).buildPendingContext({
2923
+ historyKey,
2924
+ limit: historyLimit,
2925
+ currentMessage: combinedBody,
2926
+ formatEntry: (entry) => core.channel.reply.formatAgentEnvelope({
2927
+ channel: "Teams",
2928
+ from: conversationType,
2929
+ timestamp: entry.timestamp,
2930
+ body: `${entry.sender}: ${entry.body}${entry.messageId ? ` [id:${entry.messageId}]` : ""}`,
2931
+ envelope: envelopeOptions
2932
+ })
2933
+ });
2934
+ const inboundHistory = isRoomish && historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: conversationHistories }).buildInboundHistory({
2935
+ historyKey,
2936
+ limit: historyLimit
2937
+ }) : void 0;
2938
+ const commandBody = text.trim();
2939
+ const quoteSenderAllowed = quoteInfo && quoteInfo.sender ? !isChannel || groupPolicy !== "allowlist" ? true : resolveMSTeamsAllowlistMatch({
2940
+ allowFrom: effectiveGroupAllowFrom,
2941
+ senderId: quoteSenderId ?? "",
2942
+ senderName: quoteSenderName,
2943
+ allowNameMatching
2944
+ }).allowed : true;
2945
+ const includeQuoteContext = quoteInfo && shouldIncludeSupplementalContext({
2946
+ mode: contextVisibilityMode,
2947
+ kind: "quote",
2948
+ senderAllowed: quoteSenderAllowed
2949
+ });
2950
+ const bodyForAgent = threadContext ? `[Thread history]\n${threadContext}\n[/Thread history]\n\n${rawBody}` : rawBody;
2951
+ const nativeChannelId = isChannel && teamId ? `${teamId}/${conversationId}` : void 0;
2952
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
2953
+ Body: combinedBody,
2954
+ BodyForAgent: bodyForAgent,
2955
+ InboundHistory: inboundHistory,
2956
+ RawBody: rawBody,
2957
+ CommandBody: commandBody,
2958
+ BodyForCommands: commandBody,
2959
+ From: teamsFrom,
2960
+ To: teamsTo,
2961
+ SessionKey: route.sessionKey,
2962
+ AccountId: route.accountId,
2963
+ ChatType: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
2964
+ ConversationLabel: envelopeFrom,
2965
+ GroupSubject: !isDirectMessage ? conversationType : void 0,
2966
+ GroupSpace: teamId,
2967
+ SenderName: senderName,
2968
+ SenderId: senderId,
2969
+ Provider: "msteams",
2970
+ Surface: "msteams",
2971
+ MessageSid: activity.id,
2972
+ Timestamp: timestamp?.getTime() ?? Date.now(),
2973
+ WasMentioned: isDirectMessage || mentionDecision.effectiveWasMentioned,
2974
+ CommandAuthorized: commandAuthorized,
2975
+ OriginatingChannel: "msteams",
2976
+ OriginatingTo: teamsTo,
2977
+ NativeChannelId: nativeChannelId,
2978
+ ReplyToId: activity.replyToId ?? void 0,
2979
+ ReplyToBody: includeQuoteContext ? quoteInfo?.body : void 0,
2980
+ ReplyToSender: includeQuoteContext ? quoteInfo?.sender : void 0,
2981
+ ReplyToIsQuote: quoteInfo ? true : void 0,
2982
+ ...mediaPayload
2983
+ });
2984
+ logVerboseMessage(`msteams inbound: from=${ctxPayload.From} preview="${preview}"`);
2985
+ const sharePointSiteId = msteamsCfg?.sharePointSiteId;
2986
+ const { dispatcher, replyOptions, markDispatchIdle } = createMSTeamsReplyDispatcher({
2987
+ cfg,
2988
+ agentId: route.agentId,
2989
+ sessionKey: route.sessionKey,
2990
+ accountId: route.accountId,
2991
+ runtime,
2992
+ log,
2993
+ adapter,
2994
+ appId,
2995
+ conversationRef,
2996
+ context,
2997
+ replyStyle,
2998
+ textLimit,
2999
+ onSentMessageIds: (ids) => {
3000
+ for (const id of ids) recordMSTeamsSentMessage(conversationId, id);
3001
+ },
3002
+ tokenProvider,
3003
+ sharePointSiteId
3004
+ });
3005
+ const senderTimezone = (activity.entities?.find((e) => e.type === "clientInfo"))?.timezone || conversationRef.timezone;
3006
+ const configOverride = senderTimezone && !cfg.agents?.defaults?.userTimezone ? { agents: { defaults: {
3007
+ ...cfg.agents?.defaults,
3008
+ userTimezone: senderTimezone
3009
+ } } } : void 0;
3010
+ log.info("dispatching to agent", { sessionKey: route.sessionKey });
3011
+ try {
3012
+ const turnResult = await core.channel.turn.run({
3013
+ channel: "msteams",
3014
+ accountId: route.accountId,
3015
+ raw: context,
3016
+ adapter: {
3017
+ ingest: () => ({
3018
+ id: activity.id ?? `${teamsFrom}:${Date.now()}`,
3019
+ timestamp: timestamp?.getTime(),
3020
+ rawText: rawBody,
3021
+ textForAgent: bodyForAgent,
3022
+ textForCommands: commandBody,
3023
+ raw: activity
3024
+ }),
3025
+ resolveTurn: () => ({
3026
+ channel: "msteams",
3027
+ accountId: route.accountId,
3028
+ routeSessionKey: route.sessionKey,
3029
+ storePath,
3030
+ ctxPayload,
3031
+ recordInboundSession: core.channel.session.recordInboundSession,
3032
+ record: { onRecordError: (err) => {
3033
+ logVerboseMessage(`msteams: failed updating session meta: ${formatUnknownError(err)}`);
3034
+ } },
3035
+ history: {
3036
+ isGroup: isRoomish,
3037
+ historyKey,
3038
+ historyMap: conversationHistories,
3039
+ limit: historyLimit
3040
+ },
3041
+ onPreDispatchFailure: () => core.channel.reply.settleReplyDispatcher({
3042
+ dispatcher,
3043
+ onSettled: () => markDispatchIdle()
3044
+ }),
3045
+ runDispatch: () => dispatchReplyFromConfigWithSettledDispatcher({
3046
+ cfg,
3047
+ ctxPayload,
3048
+ dispatcher,
3049
+ onSettled: () => markDispatchIdle(),
3050
+ replyOptions,
3051
+ configOverride
3052
+ })
3053
+ })
3054
+ }
3055
+ });
3056
+ const dispatchResult = turnResult.dispatched ? turnResult.dispatchResult : void 0;
3057
+ const queuedFinal = dispatchResult?.queuedFinal ?? false;
3058
+ const counts = resolveInboundReplyDispatchCounts(dispatchResult);
3059
+ const hasFinalResponse = hasFinalInboundReplyDispatch(dispatchResult);
3060
+ log.info("dispatch complete", {
3061
+ queuedFinal,
3062
+ counts
3063
+ });
3064
+ if (!hasFinalResponse) return;
3065
+ const finalCount = counts.final;
3066
+ logVerboseMessage(`msteams: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${teamsTo}`);
3067
+ } catch (err) {
3068
+ log.error("dispatch failed", { error: formatUnknownError(err) });
3069
+ runtime.error(`msteams dispatch failed: ${formatUnknownError(err)}`);
3070
+ try {
3071
+ await context.sendActivity("⚠️ Something went wrong. Please try again.");
3072
+ } catch {}
3073
+ }
3074
+ };
3075
+ const inboundDebouncer = core.channel.debounce.createInboundDebouncer({
3076
+ debounceMs: inboundDebounceMs,
3077
+ buildKey: (entry) => {
3078
+ const conversationId = normalizeMSTeamsConversationId(entry.context.activity.conversation?.id ?? "");
3079
+ const senderId = entry.context.activity.from?.aadObjectId ?? entry.context.activity.from?.id ?? "";
3080
+ if (!senderId || !conversationId) return null;
3081
+ return `msteams:${appId}:${conversationId}:${senderId}`;
3082
+ },
3083
+ shouldDebounce: (entry) => {
3084
+ if (!entry.text.trim()) return false;
3085
+ if (entry.attachments.length > 0) return false;
3086
+ return !core.channel.text.hasControlCommand(entry.text, cfg);
3087
+ },
3088
+ onFlush: async (entries) => {
3089
+ const last = entries.at(-1);
3090
+ if (!last) return;
3091
+ if (entries.length === 1) {
3092
+ await handleTeamsMessageNow(last);
3093
+ return;
3094
+ }
3095
+ const combinedText = entries.map((entry) => entry.text).filter(Boolean).join("\n");
3096
+ if (!combinedText.trim()) return;
3097
+ const combinedRawText = entries.map((entry) => entry.rawText).filter(Boolean).join("\n");
3098
+ const wasMentioned = entries.some((entry) => entry.wasMentioned);
3099
+ const implicitMentionKinds = entries.flatMap((entry) => entry.implicitMentionKinds);
3100
+ await handleTeamsMessageNow({
3101
+ context: last.context,
3102
+ rawText: combinedRawText,
3103
+ text: combinedText,
3104
+ attachments: [],
3105
+ wasMentioned,
3106
+ implicitMentionKinds
3107
+ });
3108
+ },
3109
+ onError: (err) => {
3110
+ runtime.error(`msteams debounce flush failed: ${formatUnknownError(err)}`);
3111
+ }
3112
+ });
3113
+ return async function handleTeamsMessage(context) {
3114
+ const activity = context.activity;
3115
+ const attachments = Array.isArray(activity.attachments) ? activity.attachments : [];
3116
+ const rawText = activity.text?.trim() ?? "";
3117
+ const htmlText = extractTextFromHtmlAttachments(attachments);
3118
+ const text = stripMSTeamsMentionTags(rawText || htmlText);
3119
+ const wasMentioned = wasMSTeamsBotMentioned(activity);
3120
+ const conversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "");
3121
+ const replyToId = activity.replyToId ?? void 0;
3122
+ const implicitMentionKinds = conversationId && replyToId && await wasMSTeamsMessageSentWithPersistence({
3123
+ conversationId,
3124
+ messageId: replyToId
3125
+ }) ? ["reply_to_bot"] : [];
3126
+ await inboundDebouncer.enqueue({
3127
+ context,
3128
+ rawText,
3129
+ text,
3130
+ attachments,
3131
+ wasMentioned,
3132
+ implicitMentionKinds
3133
+ });
3134
+ };
3135
+ }
3136
+ //#endregion
3137
+ //#region extensions/msteams/src/monitor-handler/reaction-handler.ts
3138
+ /** Teams reaction type names → Unicode emoji. */
3139
+ const TEAMS_REACTION_EMOJI = {
3140
+ like: "👍",
3141
+ heart: "❤️",
3142
+ laugh: "😆",
3143
+ surprised: "😮",
3144
+ sad: "😢",
3145
+ angry: "😡"
3146
+ };
3147
+ /**
3148
+ * Map a Teams reaction type string to a Unicode emoji.
3149
+ * Falls back to the raw type if not recognized.
3150
+ */
3151
+ function mapReactionEmoji(reactionType) {
3152
+ return TEAMS_REACTION_EMOJI[reactionType] ?? reactionType;
3153
+ }
3154
+ /**
3155
+ * Create a handler for MS Teams reaction activities (reactionsAdded / reactionsRemoved).
3156
+ * The returned function accepts a turn context and a direction string.
3157
+ */
3158
+ function createMSTeamsReactionHandler(deps) {
3159
+ const { cfg, log } = deps;
3160
+ const core = getMSTeamsRuntime();
3161
+ const msteamsCfg = cfg.channels?.msteams;
3162
+ return async function handleReaction(context, direction) {
3163
+ const activity = context.activity;
3164
+ const reactions = direction === "added" ? activity.reactionsAdded ?? [] : activity.reactionsRemoved ?? [];
3165
+ if (reactions.length === 0) {
3166
+ log.debug?.("reaction activity has no reactions; skipping");
3167
+ return;
3168
+ }
3169
+ const from = activity.from;
3170
+ if (!from?.id) {
3171
+ log.debug?.("reaction activity missing from.id; skipping");
3172
+ return;
3173
+ }
3174
+ const conversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "");
3175
+ const conversationType = activity.conversation?.conversationType ?? "personal";
3176
+ const isGroupChat = conversationType === "groupChat" || activity.conversation?.isGroup === true;
3177
+ const isChannel = conversationType === "channel";
3178
+ const isDirectMessage = !isGroupChat && !isChannel;
3179
+ const senderId = from.aadObjectId ?? from.id;
3180
+ const senderName = from.name ?? from.id;
3181
+ if (msteamsCfg) {
3182
+ const senderAccess = await resolveMSTeamsSenderAccess({
3183
+ cfg,
3184
+ activity
3185
+ });
3186
+ if (senderAccess.senderAccess.decision !== "allow") {
3187
+ log.debug?.("dropping reaction (access denied)", {
3188
+ sender: senderId,
3189
+ reason: senderAccess.senderAccess.reasonCode
3190
+ });
3191
+ return;
3192
+ }
3193
+ }
3194
+ const teamId = isDirectMessage ? void 0 : activity.channelData?.team?.id;
3195
+ const route = core.channel.routing.resolveAgentRoute({
3196
+ cfg,
3197
+ channel: "msteams",
3198
+ peer: {
3199
+ kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
3200
+ id: isDirectMessage ? senderId : conversationId
3201
+ },
3202
+ ...teamId ? { teamId } : {}
3203
+ });
3204
+ const targetMessageId = activity.replyToId ?? "unknown";
3205
+ for (const reaction of reactions) {
3206
+ const reactionType = reaction.type ?? "unknown";
3207
+ const emoji = mapReactionEmoji(reactionType);
3208
+ const label = direction === "added" ? `Teams reaction ${emoji} added by ${senderName} on message ${targetMessageId}` : `Teams reaction ${emoji} removed by ${senderName} from message ${targetMessageId}`;
3209
+ log.info(`reaction ${direction}`, {
3210
+ sender: senderId,
3211
+ reactionType,
3212
+ emoji,
3213
+ targetMessageId,
3214
+ conversationId
3215
+ });
3216
+ core.system.enqueueSystemEvent(label, {
3217
+ sessionKey: route.sessionKey,
3218
+ contextKey: `msteams:reaction:${conversationId}:${targetMessageId}:${senderId}:${reactionType}:${direction}`
3219
+ });
3220
+ }
3221
+ };
3222
+ }
3223
+ //#endregion
3224
+ //#region extensions/msteams/src/sso.ts
3225
+ /** Scope used to obtain a Bot Framework service token. */
3226
+ const BOT_FRAMEWORK_TOKEN_SCOPE = "https://api.botframework.com/.default";
3227
+ /** Bot Framework User Token service base URL. */
3228
+ const BOT_FRAMEWORK_USER_TOKEN_BASE_URL = "https://token.botframework.com";
3229
+ /**
3230
+ * Extract and validate the `signin/tokenExchange` activity value. Teams
3231
+ * delivers `{ id, connectionName, token }`; any field may be missing on
3232
+ * malformed invocations, so callers should check the parsed result.
3233
+ */
3234
+ function parseSigninTokenExchangeValue(value) {
3235
+ if (!value || typeof value !== "object") return null;
3236
+ const obj = value;
3237
+ return {
3238
+ id: typeof obj.id === "string" ? obj.id : void 0,
3239
+ connectionName: typeof obj.connectionName === "string" ? obj.connectionName : void 0,
3240
+ token: typeof obj.token === "string" ? obj.token : void 0
3241
+ };
3242
+ }
3243
+ /** Extract the `signin/verifyState` activity value `{ state }`. */
3244
+ function parseSigninVerifyStateValue(value) {
3245
+ if (!value || typeof value !== "object") return null;
3246
+ const obj = value;
3247
+ return { state: typeof obj.state === "string" ? obj.state : void 0 };
3248
+ }
3249
+ async function callUserTokenService(params) {
3250
+ const qs = new URLSearchParams(params.query).toString();
3251
+ const url = `${params.baseUrl.replace(/\/+$/, "")}${params.path}?${qs}`;
3252
+ const headers = {
3253
+ Accept: "application/json",
3254
+ Authorization: `Bearer ${params.bearerToken}`,
3255
+ "User-Agent": buildUserAgent()
3256
+ };
3257
+ if (params.body !== void 0) headers["Content-Type"] = "application/json";
3258
+ const response = await params.fetchImpl(url, {
3259
+ method: params.method,
3260
+ headers,
3261
+ body: params.body === void 0 ? void 0 : JSON.stringify(params.body)
3262
+ });
3263
+ if (!response.ok) return {
3264
+ error: await response.text().catch(() => "") || `HTTP ${response.status}`,
3265
+ status: response.status
3266
+ };
3267
+ let parsed;
3268
+ try {
3269
+ parsed = await response.json();
3270
+ } catch {
3271
+ return {
3272
+ error: "invalid JSON from User Token service",
3273
+ status: response.status
3274
+ };
3275
+ }
3276
+ if (!parsed || typeof parsed !== "object") return {
3277
+ error: "empty response from User Token service",
3278
+ status: response.status
3279
+ };
3280
+ const obj = parsed;
3281
+ const token = typeof obj.token === "string" ? obj.token : void 0;
3282
+ const connectionName = typeof obj.connectionName === "string" ? obj.connectionName : void 0;
3283
+ const channelId = typeof obj.channelId === "string" ? obj.channelId : void 0;
3284
+ const expiration = typeof obj.expiration === "string" ? obj.expiration : void 0;
3285
+ if (!token || !connectionName) return {
3286
+ error: "User Token service response missing token/connectionName",
3287
+ status: 502
3288
+ };
3289
+ return {
3290
+ channelId,
3291
+ connectionName,
3292
+ token,
3293
+ expiration
3294
+ };
3295
+ }
3296
+ /**
3297
+ * Exchange a Teams SSO token for a delegated user token via Bot
3298
+ * Framework's User Token service, then persist the result.
3299
+ */
3300
+ async function handleSigninTokenExchangeInvoke(params) {
3301
+ const { value, user, deps } = params;
3302
+ if (!user.userId) return {
3303
+ ok: false,
3304
+ code: "missing_user",
3305
+ message: "no user id on invoke activity"
3306
+ };
3307
+ const connectionName = value.connectionName?.trim() || deps.connectionName;
3308
+ if (!connectionName) return {
3309
+ ok: false,
3310
+ code: "missing_connection",
3311
+ message: "no OAuth connection name"
3312
+ };
3313
+ if (!value.token) return {
3314
+ ok: false,
3315
+ code: "missing_token",
3316
+ message: "no exchangeable token on invoke"
3317
+ };
3318
+ const bearer = await deps.tokenProvider.getAccessToken(BOT_FRAMEWORK_TOKEN_SCOPE);
3319
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3320
+ const result = await callUserTokenService({
3321
+ baseUrl: deps.userTokenBaseUrl ?? BOT_FRAMEWORK_USER_TOKEN_BASE_URL,
3322
+ path: "/api/usertoken/exchange",
3323
+ query: {
3324
+ userId: user.userId,
3325
+ connectionName,
3326
+ channelId: user.channelId ?? "msteams"
3327
+ },
3328
+ method: "POST",
3329
+ body: { token: value.token },
3330
+ bearerToken: bearer,
3331
+ fetchImpl
3332
+ });
3333
+ if ("error" in result) return {
3334
+ ok: false,
3335
+ code: result.status >= 500 ? "service_error" : "unexpected_response",
3336
+ message: result.error,
3337
+ status: result.status
3338
+ };
3339
+ await deps.tokenStore.save({
3340
+ connectionName,
3341
+ userId: user.userId,
3342
+ token: result.token,
3343
+ expiresAt: result.expiration,
3344
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3345
+ });
3346
+ return {
3347
+ ok: true,
3348
+ token: result.token,
3349
+ expiresAt: result.expiration
3350
+ };
3351
+ }
3352
+ /**
3353
+ * Finish a magic-code sign-in: look up the user token for the state
3354
+ * code via Bot Framework's User Token service, then persist it.
3355
+ */
3356
+ async function handleSigninVerifyStateInvoke(params) {
3357
+ const { value, user, deps } = params;
3358
+ if (!user.userId) return {
3359
+ ok: false,
3360
+ code: "missing_user",
3361
+ message: "no user id on invoke activity"
3362
+ };
3363
+ if (!deps.connectionName) return {
3364
+ ok: false,
3365
+ code: "missing_connection",
3366
+ message: "no OAuth connection name"
3367
+ };
3368
+ const state = value.state?.trim();
3369
+ if (!state) return {
3370
+ ok: false,
3371
+ code: "missing_state",
3372
+ message: "no state code on invoke"
3373
+ };
3374
+ const bearer = await deps.tokenProvider.getAccessToken(BOT_FRAMEWORK_TOKEN_SCOPE);
3375
+ const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
3376
+ const result = await callUserTokenService({
3377
+ baseUrl: deps.userTokenBaseUrl ?? BOT_FRAMEWORK_USER_TOKEN_BASE_URL,
3378
+ path: "/api/usertoken/GetToken",
3379
+ query: {
3380
+ userId: user.userId,
3381
+ connectionName: deps.connectionName,
3382
+ channelId: user.channelId ?? "msteams",
3383
+ code: state
3384
+ },
3385
+ method: "GET",
3386
+ bearerToken: bearer,
3387
+ fetchImpl
3388
+ });
3389
+ if ("error" in result) return {
3390
+ ok: false,
3391
+ code: result.status >= 500 ? "service_error" : "unexpected_response",
3392
+ message: result.error,
3393
+ status: result.status
3394
+ };
3395
+ await deps.tokenStore.save({
3396
+ connectionName: deps.connectionName,
3397
+ userId: user.userId,
3398
+ token: result.token,
3399
+ expiresAt: result.expiration,
3400
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3401
+ });
3402
+ return {
3403
+ ok: true,
3404
+ token: result.token,
3405
+ expiresAt: result.expiration
3406
+ };
3407
+ }
3408
+ //#endregion
3409
+ //#region extensions/msteams/src/welcome-card.ts
3410
+ /**
3411
+ * Builds an Adaptive Card for welcoming users when the bot is added to a conversation.
3412
+ */
3413
+ const DEFAULT_PROMPT_STARTERS = [
3414
+ "What can you do?",
3415
+ "Summarize my last meeting",
3416
+ "Help me draft an email"
3417
+ ];
3418
+ /**
3419
+ * Build a welcome Adaptive Card for 1:1 personal chats.
3420
+ */
3421
+ function buildWelcomeCard(options) {
3422
+ const botName = options?.botName || "Klaw";
3423
+ const starters = options?.promptStarters?.length ? options.promptStarters : DEFAULT_PROMPT_STARTERS;
3424
+ return {
3425
+ type: "AdaptiveCard",
3426
+ version: "1.5",
3427
+ body: [{
3428
+ type: "TextBlock",
3429
+ text: `Hi! I'm ${botName}.`,
3430
+ weight: "bolder",
3431
+ size: "medium"
3432
+ }, {
3433
+ type: "TextBlock",
3434
+ text: "I can help you with questions, tasks, and more. Here are some things to try:",
3435
+ wrap: true
3436
+ }],
3437
+ actions: starters.map((label) => ({
3438
+ type: "Action.Submit",
3439
+ title: label,
3440
+ data: { msteams: {
3441
+ type: "imBack",
3442
+ value: label
3443
+ } }
3444
+ }))
3445
+ };
3446
+ }
3447
+ /**
3448
+ * Build a brief welcome message for group chats (when the bot is @mentioned).
3449
+ */
3450
+ function buildGroupWelcomeText(botName) {
3451
+ const name = botName || "Klaw";
3452
+ return `Hi! I'm ${name}. Mention me with @${name} to get started.`;
3453
+ }
3454
+ //#endregion
3455
+ //#region extensions/msteams/src/monitor-handler.ts
3456
+ function serializeAdaptiveCardActionValue(value) {
3457
+ if (typeof value === "string") {
3458
+ const trimmed = value.trim();
3459
+ return trimmed ? trimmed : null;
3460
+ }
3461
+ if (value === void 0) return null;
3462
+ try {
3463
+ return JSON.stringify(value);
3464
+ } catch {
3465
+ return null;
3466
+ }
3467
+ }
3468
+ async function isInvokeAuthorized(params) {
3469
+ const { context, deps, deniedLogs, includeInvokeName = false } = params;
3470
+ const resolved = await resolveMSTeamsSenderAccess({
3471
+ cfg: deps.cfg,
3472
+ activity: context.activity
3473
+ });
3474
+ const { msteamsCfg, isDirectMessage, conversationId, senderId } = resolved;
3475
+ if (!msteamsCfg) return true;
3476
+ const maybeInvokeName = includeInvokeName ? { name: context.activity.name } : void 0;
3477
+ if (isDirectMessage && resolved.senderAccess.decision !== "allow") {
3478
+ deps.log.debug?.(deniedLogs.dm, {
3479
+ sender: senderId,
3480
+ conversationId,
3481
+ ...maybeInvokeName
3482
+ });
3483
+ return false;
3484
+ }
3485
+ if (!isDirectMessage && resolved.channelGate.allowlistConfigured && !resolved.channelGate.allowed) {
3486
+ deps.log.debug?.(deniedLogs.channel, {
3487
+ conversationId,
3488
+ teamKey: resolved.channelGate.teamKey ?? "none",
3489
+ channelKey: resolved.channelGate.channelKey ?? "none",
3490
+ ...maybeInvokeName
3491
+ });
3492
+ return false;
3493
+ }
3494
+ if (!isDirectMessage && !resolved.senderAccess.allowed) {
3495
+ deps.log.debug?.(deniedLogs.group, {
3496
+ sender: senderId,
3497
+ conversationId,
3498
+ ...maybeInvokeName
3499
+ });
3500
+ return false;
3501
+ }
3502
+ return true;
3503
+ }
3504
+ async function isFeedbackInvokeAuthorized(context, deps) {
3505
+ return isInvokeAuthorized({
3506
+ context,
3507
+ deps,
3508
+ deniedLogs: {
3509
+ dm: "dropping feedback invoke (dm sender not allowlisted)",
3510
+ channel: "dropping feedback invoke (not in team/channel allowlist)",
3511
+ group: "dropping feedback invoke (group sender not allowlisted)"
3512
+ }
3513
+ });
3514
+ }
3515
+ async function isSigninInvokeAuthorized(context, deps) {
3516
+ return isInvokeAuthorized({
3517
+ context,
3518
+ deps,
3519
+ deniedLogs: {
3520
+ dm: "dropping signin invoke (dm sender not allowlisted)",
3521
+ channel: "dropping signin invoke (not in team/channel allowlist)",
3522
+ group: "dropping signin invoke (group sender not allowlisted)"
3523
+ },
3524
+ includeInvokeName: true
3525
+ });
3526
+ }
3527
+ /**
3528
+ * Parse and handle feedback invoke activities (thumbs up/down).
3529
+ * Returns true if the activity was a feedback invoke, false otherwise.
3530
+ */
3531
+ async function handleFeedbackInvoke(context, deps) {
3532
+ const activity = context.activity;
3533
+ const value = activity.value;
3534
+ if (!value) return false;
3535
+ if (value.actionName !== "feedback") return false;
3536
+ const reaction = value.actionValue?.reaction;
3537
+ if (reaction !== "like" && reaction !== "dislike") {
3538
+ deps.log.debug?.("ignoring feedback with unknown reaction", { reaction });
3539
+ return false;
3540
+ }
3541
+ const msteamsCfg = deps.cfg.channels?.msteams;
3542
+ if (msteamsCfg?.feedbackEnabled === false) {
3543
+ deps.log.debug?.("feedback handling disabled");
3544
+ return true;
3545
+ }
3546
+ if (!await isFeedbackInvokeAuthorized(context, deps)) return true;
3547
+ let userComment;
3548
+ if (value.actionValue?.feedback) try {
3549
+ userComment = JSON.parse(value.actionValue.feedback).feedbackText || void 0;
3550
+ } catch {}
3551
+ const rawConversationId = activity.conversation?.id ?? "unknown";
3552
+ const conversationId = normalizeMSTeamsConversationId(rawConversationId);
3553
+ const senderId = activity.from?.aadObjectId ?? activity.from?.id ?? "unknown";
3554
+ const messageId = value.replyToId ?? activity.replyToId ?? "unknown";
3555
+ const isNegative = reaction === "dislike";
3556
+ const convType = normalizeOptionalLowercaseString(activity.conversation?.conversationType);
3557
+ const isDirectMessage = convType === "personal" || !convType && !activity.conversation?.isGroup;
3558
+ const isChannel = convType === "channel";
3559
+ const core = getMSTeamsRuntime();
3560
+ const route = core.channel.routing.resolveAgentRoute({
3561
+ cfg: deps.cfg,
3562
+ channel: "msteams",
3563
+ peer: {
3564
+ kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
3565
+ id: isDirectMessage ? senderId : conversationId
3566
+ }
3567
+ });
3568
+ const feedbackThreadId = isChannel ? extractMSTeamsConversationMessageId(rawConversationId) ?? activity.replyToId ?? void 0 : void 0;
3569
+ if (feedbackThreadId) route.sessionKey = resolveThreadSessionKeys({
3570
+ baseSessionKey: route.sessionKey,
3571
+ threadId: feedbackThreadId,
3572
+ parentSessionKey: route.sessionKey
3573
+ }).sessionKey;
3574
+ const feedbackEvent = buildFeedbackEvent({
3575
+ messageId,
3576
+ value: isNegative ? "negative" : "positive",
3577
+ comment: userComment,
3578
+ sessionKey: route.sessionKey,
3579
+ agentId: route.agentId,
3580
+ conversationId
3581
+ });
3582
+ deps.log.info("received feedback", {
3583
+ value: feedbackEvent.value,
3584
+ messageId,
3585
+ conversationId,
3586
+ hasComment: Boolean(userComment)
3587
+ });
3588
+ try {
3589
+ const storePath = core.channel.session.resolveStorePath(deps.cfg.session?.store, { agentId: route.agentId });
3590
+ const safeKey = route.sessionKey.replace(/[^a-zA-Z0-9_-]/g, "_");
3591
+ await appendRegularFile({
3592
+ filePath: path.join(storePath, `${safeKey}.jsonl`),
3593
+ content: `${JSON.stringify(feedbackEvent)}\n`,
3594
+ rejectSymlinkParents: true
3595
+ }).catch(() => {});
3596
+ } catch {}
3597
+ const conversationRef = {
3598
+ activityId: activity.id,
3599
+ user: {
3600
+ id: activity.from?.id,
3601
+ name: activity.from?.name,
3602
+ aadObjectId: activity.from?.aadObjectId
3603
+ },
3604
+ agent: activity.recipient ? {
3605
+ id: activity.recipient.id,
3606
+ name: activity.recipient.name
3607
+ } : void 0,
3608
+ bot: activity.recipient ? {
3609
+ id: activity.recipient.id,
3610
+ name: activity.recipient.name
3611
+ } : void 0,
3612
+ conversation: {
3613
+ id: conversationId,
3614
+ conversationType: activity.conversation?.conversationType,
3615
+ tenantId: activity.conversation?.tenantId
3616
+ },
3617
+ channelId: activity.channelId ?? "msteams",
3618
+ serviceUrl: activity.serviceUrl,
3619
+ locale: activity.locale
3620
+ };
3621
+ if (isNegative && msteamsCfg?.feedbackReflection !== false) runFeedbackReflection({
3622
+ cfg: deps.cfg,
3623
+ adapter: deps.adapter,
3624
+ appId: deps.appId,
3625
+ conversationRef,
3626
+ sessionKey: route.sessionKey,
3627
+ agentId: route.agentId,
3628
+ conversationId,
3629
+ feedbackMessageId: messageId,
3630
+ userComment,
3631
+ log: deps.log
3632
+ }).catch((err) => {
3633
+ deps.log.error("feedback reflection failed", { error: formatUnknownError(err) });
3634
+ });
3635
+ return true;
3636
+ }
3637
+ function registerMSTeamsHandlers(handler, deps) {
3638
+ const handleTeamsMessage = createMSTeamsMessageHandler(deps);
3639
+ const handleReaction = createMSTeamsReactionHandler(deps);
3640
+ const originalRun = handler.run;
3641
+ if (originalRun) handler.run = async (context) => {
3642
+ const ctx = context;
3643
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "fileConsent/invoke") {
3644
+ await respondToMSTeamsFileConsentInvoke(ctx, deps.log);
3645
+ return;
3646
+ }
3647
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "message/submitAction") {
3648
+ if (await handleFeedbackInvoke(ctx, deps)) return;
3649
+ }
3650
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "adaptiveCard/action") {
3651
+ const text = serializeAdaptiveCardActionValue(ctx.activity?.value);
3652
+ if (text) {
3653
+ await handleTeamsMessage({
3654
+ ...ctx,
3655
+ activity: {
3656
+ ...ctx.activity,
3657
+ type: "message",
3658
+ text
3659
+ }
3660
+ });
3661
+ return;
3662
+ }
3663
+ deps.log.debug?.("skipping adaptive card action invoke without value payload");
3664
+ }
3665
+ if (ctx.activity?.type === "invoke" && (ctx.activity?.name === "signin/tokenExchange" || ctx.activity?.name === "signin/verifyState")) {
3666
+ await ctx.sendActivity({
3667
+ type: "invokeResponse",
3668
+ value: {
3669
+ status: 200,
3670
+ body: {}
3671
+ }
3672
+ });
3673
+ if (!await isSigninInvokeAuthorized(ctx, deps)) return;
3674
+ if (!deps.sso) {
3675
+ deps.log.debug?.("signin invoke received but msteams.sso is not configured", { name: ctx.activity.name });
3676
+ return;
3677
+ }
3678
+ const user = {
3679
+ userId: ctx.activity.from?.aadObjectId ?? ctx.activity.from?.id ?? "",
3680
+ channelId: ctx.activity.channelId ?? "msteams"
3681
+ };
3682
+ try {
3683
+ if (ctx.activity.name === "signin/tokenExchange") {
3684
+ const parsed = parseSigninTokenExchangeValue(ctx.activity.value);
3685
+ if (!parsed) {
3686
+ deps.log.debug?.("invalid signin/tokenExchange invoke value");
3687
+ return;
3688
+ }
3689
+ const result = await handleSigninTokenExchangeInvoke({
3690
+ value: parsed,
3691
+ user,
3692
+ deps: deps.sso
3693
+ });
3694
+ if (result.ok) deps.log.info("msteams sso token exchanged", {
3695
+ userId: user.userId,
3696
+ hasExpiry: Boolean(result.expiresAt)
3697
+ });
3698
+ else deps.log.error("msteams sso token exchange failed", {
3699
+ code: result.code,
3700
+ status: result.status,
3701
+ message: result.message
3702
+ });
3703
+ return;
3704
+ }
3705
+ const parsed = parseSigninVerifyStateValue(ctx.activity.value);
3706
+ if (!parsed) {
3707
+ deps.log.debug?.("invalid signin/verifyState invoke value");
3708
+ return;
3709
+ }
3710
+ const result = await handleSigninVerifyStateInvoke({
3711
+ value: parsed,
3712
+ user,
3713
+ deps: deps.sso
3714
+ });
3715
+ if (result.ok) deps.log.info("msteams sso verifyState succeeded", {
3716
+ userId: user.userId,
3717
+ hasExpiry: Boolean(result.expiresAt)
3718
+ });
3719
+ else deps.log.error("msteams sso verifyState failed", {
3720
+ code: result.code,
3721
+ status: result.status,
3722
+ message: result.message
3723
+ });
3724
+ } catch (err) {
3725
+ deps.log.error("msteams sso invoke handler error", { error: formatUnknownError(err) });
3726
+ }
3727
+ return;
3728
+ }
3729
+ return originalRun.call(handler, context);
3730
+ };
3731
+ handler.onMessage(async (context, next) => {
3732
+ try {
3733
+ await handleTeamsMessage(context);
3734
+ } catch (err) {
3735
+ deps.runtime.error(`msteams handler failed: ${formatUnknownError(err)}`);
3736
+ }
3737
+ await next();
3738
+ });
3739
+ handler.onMembersAdded(async (context, next) => {
3740
+ const ctx = context;
3741
+ const membersAdded = ctx.activity?.membersAdded ?? [];
3742
+ const botId = ctx.activity?.recipient?.id;
3743
+ const msteamsCfg = deps.cfg.channels?.msteams;
3744
+ for (const member of membersAdded) if (member.id === botId) {
3745
+ const isPersonal = (normalizeOptionalLowercaseString(ctx.activity?.conversation?.conversationType) ?? "personal") === "personal";
3746
+ if (isPersonal && msteamsCfg?.welcomeCard !== false) {
3747
+ const card = buildWelcomeCard({
3748
+ botName: ctx.activity?.recipient?.name ?? void 0,
3749
+ promptStarters: msteamsCfg?.promptStarters
3750
+ });
3751
+ try {
3752
+ await ctx.sendActivity({
3753
+ type: "message",
3754
+ attachments: [{
3755
+ contentType: "application/vnd.microsoft.card.adaptive",
3756
+ content: card
3757
+ }]
3758
+ });
3759
+ deps.log.info("sent welcome card");
3760
+ } catch (err) {
3761
+ deps.log.debug?.("failed to send welcome card", { error: formatUnknownError(err) });
3762
+ }
3763
+ } else if (!isPersonal && msteamsCfg?.groupWelcomeCard === true) {
3764
+ const botName = ctx.activity?.recipient?.name ?? void 0;
3765
+ try {
3766
+ await ctx.sendActivity(buildGroupWelcomeText(botName));
3767
+ deps.log.info("sent group welcome message");
3768
+ } catch (err) {
3769
+ deps.log.debug?.("failed to send group welcome", { error: formatUnknownError(err) });
3770
+ }
3771
+ } else deps.log.debug?.("skipping welcome (disabled by config or conversation type)");
3772
+ } else deps.log.debug?.("member added", { member: member.id });
3773
+ await next();
3774
+ });
3775
+ handler.onReactionsAdded(async (context, next) => {
3776
+ try {
3777
+ await handleReaction(context, "added");
3778
+ } catch (err) {
3779
+ deps.runtime.error(`msteams reaction handler failed: ${String(err)}`);
3780
+ }
3781
+ await next();
3782
+ });
3783
+ handler.onReactionsRemoved(async (context, next) => {
3784
+ try {
3785
+ await handleReaction(context, "removed");
3786
+ } catch (err) {
3787
+ deps.runtime.error(`msteams reaction handler failed: ${String(err)}`);
3788
+ }
3789
+ await next();
3790
+ });
3791
+ return handler;
3792
+ }
3793
+ //#endregion
3794
+ //#region extensions/msteams/src/sso-token-store.ts
3795
+ /**
3796
+ * File-backed store for Bot Framework OAuth SSO tokens.
3797
+ *
3798
+ * Tokens are keyed by (connectionName, userId). `userId` should be the
3799
+ * stable AAD object ID (`activity.from.aadObjectId`) when available,
3800
+ * falling back to the Bot Framework `activity.from.id`.
3801
+ *
3802
+ * The store is intentionally minimal: it persists the exchanged user
3803
+ * token plus its expiration so consumers (for example tool handlers
3804
+ * that call Microsoft Graph with delegated permissions) can fetch a
3805
+ * valid token without reaching back into Bot Framework every turn.
3806
+ */
3807
+ const STORE_FILENAME = "msteams-sso-tokens.json";
3808
+ const STORE_KEY_VERSION_PREFIX = "v2:";
3809
+ function makeKey(connectionName, userId) {
3810
+ return `${STORE_KEY_VERSION_PREFIX}${Buffer.from(JSON.stringify([connectionName, userId]), "utf8").toString("base64url")}`;
3811
+ }
3812
+ function normalizeStoredToken(value) {
3813
+ if (!value || typeof value !== "object") return null;
3814
+ const token = value;
3815
+ if (typeof token.connectionName !== "string" || !token.connectionName || typeof token.userId !== "string" || !token.userId || typeof token.token !== "string" || !token.token || typeof token.updatedAt !== "string" || !token.updatedAt) return null;
3816
+ return {
3817
+ connectionName: token.connectionName,
3818
+ userId: token.userId,
3819
+ token: token.token,
3820
+ ...typeof token.expiresAt === "string" ? { expiresAt: token.expiresAt } : {},
3821
+ updatedAt: token.updatedAt
3822
+ };
3823
+ }
3824
+ function isSsoStoreData(value) {
3825
+ if (!value || typeof value !== "object") return false;
3826
+ const obj = value;
3827
+ return obj.version === 1 && typeof obj.tokens === "object" && obj.tokens !== null;
3828
+ }
3829
+ function createMSTeamsSsoTokenStoreFs(params) {
3830
+ const filePath = resolveMSTeamsStorePath({
3831
+ filename: STORE_FILENAME,
3832
+ env: params?.env,
3833
+ homedir: params?.homedir,
3834
+ stateDir: params?.stateDir,
3835
+ storePath: params?.storePath
3836
+ });
3837
+ const empty = {
3838
+ version: 1,
3839
+ tokens: {}
3840
+ };
3841
+ const readStore = async () => {
3842
+ const { value } = await readJsonFile(filePath, empty);
3843
+ if (!isSsoStoreData(value)) return {
3844
+ version: 1,
3845
+ tokens: {}
3846
+ };
3847
+ const tokens = {};
3848
+ for (const stored of Object.values(value.tokens)) {
3849
+ const normalized = normalizeStoredToken(stored);
3850
+ if (!normalized) continue;
3851
+ tokens[makeKey(normalized.connectionName, normalized.userId)] = normalized;
3852
+ }
3853
+ return {
3854
+ version: 1,
3855
+ tokens
3856
+ };
3857
+ };
3858
+ return {
3859
+ async get({ connectionName, userId }) {
3860
+ return (await readStore()).tokens[makeKey(connectionName, userId)] ?? null;
3861
+ },
3862
+ async save(token) {
3863
+ await withFileLock(filePath, empty, async () => {
3864
+ const store = await readStore();
3865
+ const key = makeKey(token.connectionName, token.userId);
3866
+ store.tokens[key] = { ...token };
3867
+ await writeJsonFile(filePath, store);
3868
+ });
3869
+ },
3870
+ async remove({ connectionName, userId }) {
3871
+ let removed = false;
3872
+ await withFileLock(filePath, empty, async () => {
3873
+ const store = await readStore();
3874
+ const key = makeKey(connectionName, userId);
3875
+ if (store.tokens[key]) {
3876
+ delete store.tokens[key];
3877
+ removed = true;
3878
+ await writeJsonFile(filePath, store);
3879
+ }
3880
+ });
3881
+ return removed;
3882
+ }
3883
+ };
3884
+ }
3885
+ //#endregion
3886
+ //#region extensions/msteams/src/webhook-timeouts.ts
3887
+ const MSTEAMS_WEBHOOK_INACTIVITY_TIMEOUT_MS = 3e4;
3888
+ const MSTEAMS_WEBHOOK_REQUEST_TIMEOUT_MS = 3e4;
3889
+ const MSTEAMS_WEBHOOK_HEADERS_TIMEOUT_MS = 15e3;
3890
+ function applyMSTeamsWebhookTimeouts(httpServer, opts) {
3891
+ const inactivityTimeoutMs = opts?.inactivityTimeoutMs ?? MSTEAMS_WEBHOOK_INACTIVITY_TIMEOUT_MS;
3892
+ const requestTimeoutMs = opts?.requestTimeoutMs ?? MSTEAMS_WEBHOOK_REQUEST_TIMEOUT_MS;
3893
+ const headersTimeoutMs = Math.min(opts?.headersTimeoutMs ?? MSTEAMS_WEBHOOK_HEADERS_TIMEOUT_MS, requestTimeoutMs);
3894
+ httpServer.setTimeout(inactivityTimeoutMs);
3895
+ httpServer.requestTimeout = requestTimeoutMs;
3896
+ httpServer.headersTimeout = headersTimeoutMs;
3897
+ }
3898
+ //#endregion
3899
+ //#region extensions/msteams/src/monitor.ts
3900
+ const MSTEAMS_WEBHOOK_MAX_BODY_BYTES = DEFAULT_WEBHOOK_MAX_BODY_BYTES;
3901
+ async function monitorMSTeamsProvider(opts) {
3902
+ const core = getMSTeamsRuntime();
3903
+ const log = core.logging.getChildLogger({ name: "msteams" });
3904
+ let cfg = opts.cfg;
3905
+ let msteamsCfg = cfg.channels?.msteams;
3906
+ if (!msteamsCfg?.enabled) {
3907
+ log.debug?.("msteams provider disabled");
3908
+ return {
3909
+ app: null,
3910
+ shutdown: async () => {}
3911
+ };
3912
+ }
3913
+ const creds = resolveMSTeamsCredentials(msteamsCfg);
3914
+ if (!creds) {
3915
+ log.error("msteams credentials not configured");
3916
+ return {
3917
+ app: null,
3918
+ shutdown: async () => {}
3919
+ };
3920
+ }
3921
+ const appId = creds.appId;
3922
+ const runtime = opts.runtime ?? {
3923
+ log: console.log,
3924
+ error: console.error,
3925
+ exit: (code) => {
3926
+ throw new Error(`exit ${code}`);
3927
+ }
3928
+ };
3929
+ let allowFrom = msteamsCfg.allowFrom;
3930
+ let groupAllowFrom = msteamsCfg.groupAllowFrom;
3931
+ let teamsConfig = msteamsCfg.teams;
3932
+ const allowNameMatching = isDangerousNameMatchingEnabled(msteamsCfg);
3933
+ const cleanAllowEntry = (entry) => entry.replace(/^(msteams|teams):/i, "").replace(/^user:/i, "").trim();
3934
+ const isStableUserId = (entry) => /^[0-9a-fA-F-]{16,}$/.test(entry);
3935
+ const cleanAllowEntries = (entries) => entries?.map((entry) => cleanAllowEntry(entry)).filter((entry) => entry && entry !== "*") ?? [];
3936
+ const mergeStableUserIds = (entries) => {
3937
+ const additions = cleanAllowEntries(entries).filter((entry) => isStableUserId(entry));
3938
+ return additions.length > 0 ? mergeAllowlist({
3939
+ existing: entries,
3940
+ additions
3941
+ }) : entries;
3942
+ };
3943
+ const resolveAllowlistUsers = async (label, entries) => {
3944
+ if (entries.length === 0) return {
3945
+ additions: [],
3946
+ unresolved: []
3947
+ };
3948
+ const resolved = await resolveMSTeamsUserAllowlist({
3949
+ cfg,
3950
+ entries
3951
+ });
3952
+ const additions = [];
3953
+ const unresolved = [];
3954
+ for (const entry of resolved) if (entry.resolved && entry.id) additions.push(entry.id);
3955
+ else unresolved.push(entry.input);
3956
+ summarizeMapping(label, resolved.filter((entry) => entry.resolved && entry.id).map((entry) => `${entry.input}→${entry.id}`), unresolved, runtime);
3957
+ return {
3958
+ additions,
3959
+ unresolved
3960
+ };
3961
+ };
3962
+ try {
3963
+ allowFrom = mergeStableUserIds(allowFrom);
3964
+ if (Array.isArray(groupAllowFrom) && groupAllowFrom.length > 0) groupAllowFrom = mergeStableUserIds(groupAllowFrom);
3965
+ if (allowNameMatching) {
3966
+ const allowEntries = cleanAllowEntries(allowFrom).filter((entry) => !isStableUserId(entry));
3967
+ if (allowEntries.length > 0) {
3968
+ const { additions } = await resolveAllowlistUsers("msteams users", allowEntries);
3969
+ allowFrom = mergeAllowlist({
3970
+ existing: allowFrom,
3971
+ additions
3972
+ });
3973
+ }
3974
+ if (Array.isArray(groupAllowFrom) && groupAllowFrom.length > 0) {
3975
+ const groupEntries = cleanAllowEntries(groupAllowFrom).filter((entry) => !isStableUserId(entry));
3976
+ if (groupEntries.length > 0) {
3977
+ const { additions } = await resolveAllowlistUsers("msteams group users", groupEntries);
3978
+ groupAllowFrom = mergeAllowlist({
3979
+ existing: groupAllowFrom,
3980
+ additions
3981
+ });
3982
+ }
3983
+ }
3984
+ }
3985
+ if (teamsConfig && Object.keys(teamsConfig).length > 0) {
3986
+ const entries = [];
3987
+ for (const [teamKey, teamCfg] of Object.entries(teamsConfig)) {
3988
+ if (teamKey === "*") continue;
3989
+ const channels = teamCfg?.channels ?? {};
3990
+ const channelKeys = Object.keys(channels).filter((key) => key !== "*");
3991
+ if (channelKeys.length === 0) {
3992
+ entries.push({
3993
+ input: teamKey,
3994
+ teamKey
3995
+ });
3996
+ continue;
3997
+ }
3998
+ for (const channelKey of channelKeys) entries.push({
3999
+ input: `${teamKey}/${channelKey}`,
4000
+ teamKey,
4001
+ channelKey
4002
+ });
4003
+ }
4004
+ if (entries.length > 0) {
4005
+ const resolved = await resolveMSTeamsChannelAllowlist({
4006
+ cfg,
4007
+ entries: entries.map((entry) => entry.input)
4008
+ });
4009
+ const mapping = [];
4010
+ const unresolved = [];
4011
+ const nextTeams = { ...teamsConfig };
4012
+ resolved.forEach((entry, idx) => {
4013
+ const source = entries[idx];
4014
+ if (!source) return;
4015
+ const sourceTeam = teamsConfig?.[source.teamKey] ?? {};
4016
+ if (!entry.resolved || !entry.teamId) {
4017
+ unresolved.push(entry.input);
4018
+ return;
4019
+ }
4020
+ mapping.push(entry.channelId ? `${entry.input}→${entry.teamId}/${entry.channelId}` : `${entry.input}→${entry.teamId}`);
4021
+ const existing = nextTeams[entry.teamId] ?? {};
4022
+ const mergedChannels = {
4023
+ ...sourceTeam.channels,
4024
+ ...existing.channels
4025
+ };
4026
+ const mergedTeam = {
4027
+ ...sourceTeam,
4028
+ ...existing,
4029
+ channels: mergedChannels
4030
+ };
4031
+ nextTeams[entry.teamId] = mergedTeam;
4032
+ if (source.channelKey && entry.channelId) {
4033
+ const sourceChannel = sourceTeam.channels?.[source.channelKey];
4034
+ if (sourceChannel) nextTeams[entry.teamId] = {
4035
+ ...mergedTeam,
4036
+ channels: {
4037
+ ...mergedChannels,
4038
+ [entry.channelId]: {
4039
+ ...sourceChannel,
4040
+ ...mergedChannels?.[entry.channelId]
4041
+ }
4042
+ }
4043
+ };
4044
+ }
4045
+ });
4046
+ teamsConfig = nextTeams;
4047
+ summarizeMapping("msteams channels", mapping, unresolved, runtime);
4048
+ }
4049
+ }
4050
+ } catch (err) {
4051
+ runtime?.error(`msteams resolve failed; falling back to raw config entries — allowlist members resolved via Graph may be missing. ${formatUnknownError(err)}`);
4052
+ }
4053
+ msteamsCfg = {
4054
+ ...msteamsCfg,
4055
+ allowFrom,
4056
+ groupAllowFrom,
4057
+ teams: teamsConfig
4058
+ };
4059
+ cfg = {
4060
+ ...cfg,
4061
+ channels: {
4062
+ ...cfg.channels,
4063
+ msteams: msteamsCfg
4064
+ }
4065
+ };
4066
+ const port = msteamsCfg.webhook?.port ?? 3978;
4067
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "msteams");
4068
+ const MB = 1024 * 1024;
4069
+ const agentDefaults = cfg.agents?.defaults;
4070
+ const mediaMaxBytes = typeof agentDefaults?.mediaMaxMb === "number" && agentDefaults.mediaMaxMb > 0 ? Math.floor(agentDefaults.mediaMaxMb * MB) : 8 * MB;
4071
+ const conversationStore = opts.conversationStore ?? createMSTeamsConversationStoreFs();
4072
+ const pollStore = opts.pollStore ?? createMSTeamsPollStoreFs();
4073
+ log.info(`starting provider (port ${port})`);
4074
+ const express = await import("express");
4075
+ const { sdk, app } = await loadMSTeamsSdkWithAuth(creds);
4076
+ const tokenProvider = createMSTeamsTokenProvider(app);
4077
+ const adapter = createMSTeamsAdapter(app, sdk);
4078
+ let ssoDeps;
4079
+ if (msteamsCfg.sso?.enabled && msteamsCfg.sso.connectionName) {
4080
+ ssoDeps = {
4081
+ tokenProvider,
4082
+ tokenStore: createMSTeamsSsoTokenStoreFs(),
4083
+ connectionName: msteamsCfg.sso.connectionName
4084
+ };
4085
+ log.debug?.("msteams sso enabled", { connectionName: msteamsCfg.sso.connectionName });
4086
+ }
4087
+ const handler = buildActivityHandler();
4088
+ registerMSTeamsHandlers(handler, {
4089
+ cfg,
4090
+ runtime,
4091
+ appId,
4092
+ adapter,
4093
+ tokenProvider,
4094
+ textLimit,
4095
+ mediaMaxBytes,
4096
+ conversationStore,
4097
+ pollStore,
4098
+ log,
4099
+ sso: ssoDeps
4100
+ });
4101
+ const expressApp = express.default();
4102
+ expressApp.use((req, res, next) => {
4103
+ const auth = req.headers.authorization;
4104
+ if (!auth || !auth.startsWith("Bearer ")) {
4105
+ res.status(401).json({ error: "Unauthorized" });
4106
+ return;
4107
+ }
4108
+ next();
4109
+ });
4110
+ const jwtValidator = await createBotFrameworkJwtValidator(creds);
4111
+ expressApp.use((req, res, next) => {
4112
+ const authHeader = req.headers.authorization;
4113
+ jwtValidator.validate(authHeader).then((valid) => {
4114
+ if (!valid) {
4115
+ log.debug?.("JWT validation failed");
4116
+ res.status(401).json({ error: "Unauthorized" });
4117
+ return;
4118
+ }
4119
+ next();
4120
+ }).catch((err) => {
4121
+ if (err instanceof Error && /ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT|ECONNRESET/i.test(err.code ?? err.message)) runtime?.error(`msteams: JWKS key fetch failed — check egress to login.botframework.com:443 (firewall or DNS may be blocking it). Bot will 401 all inbound requests until this is resolved. Error: ${formatUnknownError(err)}`);
4122
+ else log.debug?.(`JWT validation error: ${formatUnknownError(err)}`);
4123
+ res.status(401).json({ error: "Unauthorized" });
4124
+ });
4125
+ });
4126
+ expressApp.use(express.json({ limit: MSTEAMS_WEBHOOK_MAX_BODY_BYTES }));
4127
+ expressApp.use((err, _req, res, next) => {
4128
+ if (err && typeof err === "object" && "status" in err && err.status === 413) {
4129
+ res.status(413).json({ error: "Payload too large" });
4130
+ return;
4131
+ }
4132
+ next(err);
4133
+ });
4134
+ const configuredPath = msteamsCfg.webhook?.path ?? "/api/messages";
4135
+ const messageHandler = (req, res) => {
4136
+ adapter.process(req, res, (context) => handler.run(context)).catch((err) => {
4137
+ log.error("msteams webhook failed", { error: formatUnknownError(err) });
4138
+ });
4139
+ };
4140
+ expressApp.post(configuredPath, messageHandler);
4141
+ if (configuredPath !== "/api/messages") expressApp.post("/api/messages", messageHandler);
4142
+ log.debug?.("listening on paths", {
4143
+ primary: configuredPath,
4144
+ fallback: "/api/messages"
4145
+ });
4146
+ const httpServer = expressApp.listen(port);
4147
+ await new Promise((resolve, reject) => {
4148
+ const onListening = () => {
4149
+ httpServer.off("error", onError);
4150
+ log.info(`msteams provider started on port ${port}`);
4151
+ resolve();
4152
+ };
4153
+ const onError = (err) => {
4154
+ httpServer.off("listening", onListening);
4155
+ log.error("msteams server error", { error: formatUnknownError(err) });
4156
+ reject(err);
4157
+ };
4158
+ httpServer.once("listening", onListening);
4159
+ httpServer.once("error", onError);
4160
+ });
4161
+ applyMSTeamsWebhookTimeouts(httpServer);
4162
+ httpServer.on("error", (err) => {
4163
+ log.error("msteams server error", { error: formatUnknownError(err) });
4164
+ });
4165
+ const shutdown = async () => {
4166
+ log.info("shutting down msteams provider");
4167
+ return new Promise((resolve) => {
4168
+ httpServer.close((err) => {
4169
+ if (err) log.debug?.("msteams server close error", { error: formatUnknownError(err) });
4170
+ resolve();
4171
+ });
4172
+ });
4173
+ };
4174
+ await keepHttpServerTaskAlive({
4175
+ server: httpServer,
4176
+ abortSignal: opts.abortSignal,
4177
+ onAbort: shutdown
4178
+ });
4179
+ return {
4180
+ app: expressApp,
4181
+ shutdown
4182
+ };
4183
+ }
4184
+ /**
4185
+ * Build a minimal ActivityHandler-compatible object that supports
4186
+ * onMessage / onMembersAdded registration and a run() method.
4187
+ */
4188
+ function buildActivityHandler() {
4189
+ const messageHandlers = [];
4190
+ const membersAddedHandlers = [];
4191
+ const reactionsAddedHandlers = [];
4192
+ const reactionsRemovedHandlers = [];
4193
+ const handler = {
4194
+ onMessage(cb) {
4195
+ messageHandlers.push(cb);
4196
+ return handler;
4197
+ },
4198
+ onMembersAdded(cb) {
4199
+ membersAddedHandlers.push(cb);
4200
+ return handler;
4201
+ },
4202
+ onReactionsAdded(cb) {
4203
+ reactionsAddedHandlers.push(cb);
4204
+ return handler;
4205
+ },
4206
+ onReactionsRemoved(cb) {
4207
+ reactionsRemovedHandlers.push(cb);
4208
+ return handler;
4209
+ },
4210
+ async run(context) {
4211
+ const ctx = context;
4212
+ const activityType = ctx?.activity?.type;
4213
+ const noop = async () => {};
4214
+ if (activityType === "message") for (const h of messageHandlers) await h(context, noop);
4215
+ else if (activityType === "conversationUpdate") for (const h of membersAddedHandlers) await h(context, noop);
4216
+ else if (activityType === "messageReaction") {
4217
+ const activity = ctx?.activity;
4218
+ if (activity?.reactionsAdded?.length) for (const h of reactionsAddedHandlers) await h(context, noop);
4219
+ if (activity?.reactionsRemoved?.length) for (const h of reactionsRemovedHandlers) await h(context, noop);
4220
+ }
4221
+ }
4222
+ };
4223
+ return handler;
4224
+ }
4225
+ //#endregion
4226
+ export { monitorMSTeamsProvider };