@kodelyth/msteams 2026.5.42 → 2026.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +16 -4
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
@@ -1,538 +0,0 @@
1
- import path from "node:path";
2
- import { resolveThreadSessionKeys } from "klaw/plugin-sdk/routing";
3
- import { appendRegularFile } from "klaw/plugin-sdk/security-runtime";
4
- import { normalizeOptionalLowercaseString } from "klaw/plugin-sdk/string-coerce-runtime";
5
- import { formatUnknownError } from "./errors.js";
6
- import { buildFeedbackEvent, runFeedbackReflection } from "./feedback-reflection.js";
7
- import { respondToMSTeamsFileConsentInvoke } from "./file-consent-invoke.js";
8
- import { extractMSTeamsConversationMessageId, normalizeMSTeamsConversationId } from "./inbound.js";
9
- import { resolveMSTeamsSenderAccess } from "./monitor-handler/access.js";
10
- import { createMSTeamsMessageHandler } from "./monitor-handler/message-handler.js";
11
- import { createMSTeamsReactionHandler } from "./monitor-handler/reaction-handler.js";
12
- import { getMSTeamsRuntime } from "./runtime.js";
13
- import type { MSTeamsTurnContext } from "./sdk-types.js";
14
- import {
15
- handleSigninTokenExchangeInvoke,
16
- handleSigninVerifyStateInvoke,
17
- parseSigninTokenExchangeValue,
18
- parseSigninVerifyStateValue,
19
- } from "./sso.js";
20
- import { buildGroupWelcomeText, buildWelcomeCard } from "./welcome-card.js";
21
- export type { MSTeamsMessageHandlerDeps } from "./monitor-handler.types.js";
22
- import type { MSTeamsMessageHandlerDeps } from "./monitor-handler.types.js";
23
-
24
- export type MSTeamsActivityHandler = {
25
- onMessage: (
26
- handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
27
- ) => MSTeamsActivityHandler;
28
- onMembersAdded: (
29
- handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
30
- ) => MSTeamsActivityHandler;
31
- onReactionsAdded: (
32
- handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
33
- ) => MSTeamsActivityHandler;
34
- onReactionsRemoved: (
35
- handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
36
- ) => MSTeamsActivityHandler;
37
- run?: (context: unknown) => Promise<void>;
38
- };
39
-
40
- function serializeAdaptiveCardActionValue(value: unknown): string | null {
41
- if (typeof value === "string") {
42
- const trimmed = value.trim();
43
- return trimmed ? trimmed : null;
44
- }
45
- if (value === undefined) {
46
- return null;
47
- }
48
- try {
49
- return JSON.stringify(value);
50
- } catch {
51
- return null;
52
- }
53
- }
54
-
55
- async function isInvokeAuthorized(params: {
56
- context: MSTeamsTurnContext;
57
- deps: MSTeamsMessageHandlerDeps;
58
- deniedLogs: {
59
- dm: string;
60
- channel: string;
61
- group: string;
62
- };
63
- includeInvokeName?: boolean;
64
- }): Promise<boolean> {
65
- const { context, deps, deniedLogs, includeInvokeName = false } = params;
66
- const resolved = await resolveMSTeamsSenderAccess({
67
- cfg: deps.cfg,
68
- activity: context.activity,
69
- });
70
- const { msteamsCfg, isDirectMessage, conversationId, senderId } = resolved;
71
- if (!msteamsCfg) {
72
- return true;
73
- }
74
-
75
- const maybeInvokeName = includeInvokeName ? { name: context.activity.name } : undefined;
76
-
77
- if (isDirectMessage && resolved.senderAccess.decision !== "allow") {
78
- deps.log.debug?.(deniedLogs.dm, {
79
- sender: senderId,
80
- conversationId,
81
- ...maybeInvokeName,
82
- });
83
- return false;
84
- }
85
-
86
- if (
87
- !isDirectMessage &&
88
- resolved.channelGate.allowlistConfigured &&
89
- !resolved.channelGate.allowed
90
- ) {
91
- deps.log.debug?.(deniedLogs.channel, {
92
- conversationId,
93
- teamKey: resolved.channelGate.teamKey ?? "none",
94
- channelKey: resolved.channelGate.channelKey ?? "none",
95
- ...maybeInvokeName,
96
- });
97
- return false;
98
- }
99
-
100
- if (!isDirectMessage && !resolved.senderAccess.allowed) {
101
- deps.log.debug?.(deniedLogs.group, {
102
- sender: senderId,
103
- conversationId,
104
- ...maybeInvokeName,
105
- });
106
- return false;
107
- }
108
-
109
- return true;
110
- }
111
-
112
- async function isFeedbackInvokeAuthorized(
113
- context: MSTeamsTurnContext,
114
- deps: MSTeamsMessageHandlerDeps,
115
- ): Promise<boolean> {
116
- return isInvokeAuthorized({
117
- context,
118
- deps,
119
- deniedLogs: {
120
- dm: "dropping feedback invoke (dm sender not allowlisted)",
121
- channel: "dropping feedback invoke (not in team/channel allowlist)",
122
- group: "dropping feedback invoke (group sender not allowlisted)",
123
- },
124
- });
125
- }
126
-
127
- async function isSigninInvokeAuthorized(
128
- context: MSTeamsTurnContext,
129
- deps: MSTeamsMessageHandlerDeps,
130
- ): Promise<boolean> {
131
- return isInvokeAuthorized({
132
- context,
133
- deps,
134
- deniedLogs: {
135
- dm: "dropping signin invoke (dm sender not allowlisted)",
136
- channel: "dropping signin invoke (not in team/channel allowlist)",
137
- group: "dropping signin invoke (group sender not allowlisted)",
138
- },
139
- includeInvokeName: true,
140
- });
141
- }
142
-
143
- /**
144
- * Parse and handle feedback invoke activities (thumbs up/down).
145
- * Returns true if the activity was a feedback invoke, false otherwise.
146
- */
147
- async function handleFeedbackInvoke(
148
- context: MSTeamsTurnContext,
149
- deps: MSTeamsMessageHandlerDeps,
150
- ): Promise<boolean> {
151
- const activity = context.activity;
152
- const value = activity.value as
153
- | {
154
- actionName?: string;
155
- actionValue?: { reaction?: string; feedback?: string };
156
- replyToId?: string;
157
- }
158
- | undefined;
159
-
160
- if (!value) {
161
- return false;
162
- }
163
-
164
- // Teams feedback invoke format: actionName="feedback", actionValue.reaction="like"|"dislike"
165
- if (value.actionName !== "feedback") {
166
- return false;
167
- }
168
-
169
- const reaction = value.actionValue?.reaction;
170
- if (reaction !== "like" && reaction !== "dislike") {
171
- deps.log.debug?.("ignoring feedback with unknown reaction", { reaction });
172
- return false;
173
- }
174
-
175
- const msteamsCfg = deps.cfg.channels?.msteams;
176
- if (msteamsCfg?.feedbackEnabled === false) {
177
- deps.log.debug?.("feedback handling disabled");
178
- return true; // Still consume the invoke
179
- }
180
-
181
- if (!(await isFeedbackInvokeAuthorized(context, deps))) {
182
- return true;
183
- }
184
-
185
- // Extract user comment from the nested JSON string
186
- let userComment: string | undefined;
187
- if (value.actionValue?.feedback) {
188
- try {
189
- const parsed = JSON.parse(value.actionValue.feedback) as { feedbackText?: string };
190
- userComment = parsed.feedbackText || undefined;
191
- } catch {
192
- // Best effort — feedback text is optional
193
- }
194
- }
195
-
196
- // Strip ;messageid=... suffix to match the normalized ID used by the message handler.
197
- const rawConversationId = activity.conversation?.id ?? "unknown";
198
- const conversationId = normalizeMSTeamsConversationId(rawConversationId);
199
- const senderId = activity.from?.aadObjectId ?? activity.from?.id ?? "unknown";
200
- const messageId = value.replyToId ?? activity.replyToId ?? "unknown";
201
- const isNegative = reaction === "dislike";
202
-
203
- // Route feedback using the same chat-type logic as normal messages
204
- // so session keys, agent IDs, and transcript paths match.
205
- const convType = normalizeOptionalLowercaseString(activity.conversation?.conversationType);
206
- const isDirectMessage = convType === "personal" || (!convType && !activity.conversation?.isGroup);
207
- const isChannel = convType === "channel";
208
-
209
- const core = getMSTeamsRuntime();
210
- const route = core.channel.routing.resolveAgentRoute({
211
- cfg: deps.cfg,
212
- channel: "msteams",
213
- peer: {
214
- kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
215
- id: isDirectMessage ? senderId : conversationId,
216
- },
217
- });
218
-
219
- // Match the thread-aware session key used by the message handler so feedback
220
- // events land in the correct per-thread transcript. For channel threads, the
221
- // thread root ID comes from the ;messageid= suffix on the conversation ID or
222
- // from activity.replyToId.
223
- const feedbackThreadId = isChannel
224
- ? (extractMSTeamsConversationMessageId(rawConversationId) ?? activity.replyToId ?? undefined)
225
- : undefined;
226
- if (feedbackThreadId) {
227
- const threadKeys = resolveThreadSessionKeys({
228
- baseSessionKey: route.sessionKey,
229
- threadId: feedbackThreadId,
230
- parentSessionKey: route.sessionKey,
231
- });
232
- route.sessionKey = threadKeys.sessionKey;
233
- }
234
-
235
- // Log feedback event to session JSONL
236
- const feedbackEvent = buildFeedbackEvent({
237
- messageId,
238
- value: isNegative ? "negative" : "positive",
239
- comment: userComment,
240
- sessionKey: route.sessionKey,
241
- agentId: route.agentId,
242
- conversationId,
243
- });
244
-
245
- deps.log.info("received feedback", {
246
- value: feedbackEvent.value,
247
- messageId,
248
- conversationId,
249
- hasComment: Boolean(userComment),
250
- });
251
-
252
- // Write feedback event to session transcript
253
- try {
254
- const storePath = core.channel.session.resolveStorePath(deps.cfg.session?.store, {
255
- agentId: route.agentId,
256
- });
257
- const safeKey = route.sessionKey.replace(/[^a-zA-Z0-9_-]/g, "_");
258
- const transcriptFile = path.join(storePath, `${safeKey}.jsonl`);
259
- await appendRegularFile({
260
- filePath: transcriptFile,
261
- content: `${JSON.stringify(feedbackEvent)}\n`,
262
- rejectSymlinkParents: true,
263
- }).catch(() => {
264
- // Best effort — transcript dir may not exist yet
265
- });
266
- } catch {
267
- // Best effort
268
- }
269
-
270
- // Build conversation reference for proactive messages (ack + reflection follow-up)
271
- const conversationRef = {
272
- activityId: activity.id,
273
- user: {
274
- id: activity.from?.id,
275
- name: activity.from?.name,
276
- aadObjectId: activity.from?.aadObjectId,
277
- },
278
- agent: activity.recipient
279
- ? { id: activity.recipient.id, name: activity.recipient.name }
280
- : undefined,
281
- bot: activity.recipient
282
- ? { id: activity.recipient.id, name: activity.recipient.name }
283
- : undefined,
284
- conversation: {
285
- id: conversationId,
286
- conversationType: activity.conversation?.conversationType,
287
- tenantId: activity.conversation?.tenantId,
288
- },
289
- channelId: activity.channelId ?? "msteams",
290
- serviceUrl: activity.serviceUrl,
291
- locale: activity.locale,
292
- };
293
-
294
- // For negative feedback, trigger background reflection (fire-and-forget).
295
- // No ack message — the reflection follow-up serves as the acknowledgement.
296
- // Sending anything during the invoke handler causes "unable to reach app" errors.
297
- if (isNegative && msteamsCfg?.feedbackReflection !== false) {
298
- // Note: thumbedDownResponse is not populated here because we don't cache
299
- // sent message text. The agent still has full session context for reflection
300
- // since the reflection runs in the same session. The user comment (if any)
301
- // provides additional signal.
302
- runFeedbackReflection({
303
- cfg: deps.cfg,
304
- adapter: deps.adapter,
305
- appId: deps.appId,
306
- conversationRef,
307
- sessionKey: route.sessionKey,
308
- agentId: route.agentId,
309
- conversationId,
310
- feedbackMessageId: messageId,
311
- userComment,
312
- log: deps.log,
313
- }).catch((err) => {
314
- deps.log.error("feedback reflection failed", { error: formatUnknownError(err) });
315
- });
316
- }
317
-
318
- return true;
319
- }
320
-
321
- export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
322
- handler: T,
323
- deps: MSTeamsMessageHandlerDeps,
324
- ): T {
325
- const handleTeamsMessage = createMSTeamsMessageHandler(deps);
326
- const handleReaction = createMSTeamsReactionHandler(deps);
327
-
328
- // Wrap the original run method to intercept invokes
329
- const originalRun = handler.run;
330
- if (originalRun) {
331
- handler.run = async (context: unknown) => {
332
- const ctx = context as MSTeamsTurnContext;
333
- // Handle file consent invokes before passing to normal flow
334
- if (ctx.activity?.type === "invoke" && ctx.activity?.name === "fileConsent/invoke") {
335
- await respondToMSTeamsFileConsentInvoke(ctx, deps.log);
336
- return;
337
- }
338
-
339
- // Handle feedback invokes (thumbs up/down on AI-generated messages).
340
- // Just return after handling — the process() handler sends HTTP 200 automatically.
341
- // Do NOT call sendActivity with invokeResponse; our custom adapter would POST
342
- // a new activity to Bot Framework instead of responding to the HTTP request.
343
- if (ctx.activity?.type === "invoke" && ctx.activity?.name === "message/submitAction") {
344
- const handled = await handleFeedbackInvoke(ctx, deps);
345
- if (handled) {
346
- return;
347
- }
348
- }
349
-
350
- if (ctx.activity?.type === "invoke" && ctx.activity?.name === "adaptiveCard/action") {
351
- const text = serializeAdaptiveCardActionValue(ctx.activity?.value);
352
- if (text) {
353
- await handleTeamsMessage({
354
- ...ctx,
355
- activity: {
356
- ...ctx.activity,
357
- type: "message",
358
- text,
359
- },
360
- });
361
- return;
362
- }
363
- deps.log.debug?.("skipping adaptive card action invoke without value payload");
364
- }
365
-
366
- // Bot Framework OAuth SSO: Teams sends signin/tokenExchange (with a
367
- // Teams-provided exchangeable token) or signin/verifyState (magic
368
- // code fallback) after an oauthCard is presented. We must ack with
369
- // HTTP 200 and, if configured, exchange the token with the Bot
370
- // Framework User Token service and persist it for downstream tools.
371
- if (
372
- ctx.activity?.type === "invoke" &&
373
- (ctx.activity?.name === "signin/tokenExchange" ||
374
- ctx.activity?.name === "signin/verifyState")
375
- ) {
376
- // Always ack immediately — silently dropping the invoke causes
377
- // the Teams card UI to report "Something went wrong".
378
- await ctx.sendActivity({ type: "invokeResponse", value: { status: 200, body: {} } });
379
-
380
- if (!(await isSigninInvokeAuthorized(ctx, deps))) {
381
- return;
382
- }
383
-
384
- if (!deps.sso) {
385
- deps.log.debug?.("signin invoke received but msteams.sso is not configured", {
386
- name: ctx.activity.name,
387
- });
388
- return;
389
- }
390
-
391
- const user = {
392
- userId: ctx.activity.from?.aadObjectId ?? ctx.activity.from?.id ?? "",
393
- channelId: ctx.activity.channelId ?? "msteams",
394
- };
395
-
396
- try {
397
- if (ctx.activity.name === "signin/tokenExchange") {
398
- const parsed = parseSigninTokenExchangeValue(ctx.activity.value);
399
- if (!parsed) {
400
- deps.log.debug?.("invalid signin/tokenExchange invoke value");
401
- return;
402
- }
403
- const result = await handleSigninTokenExchangeInvoke({
404
- value: parsed,
405
- user,
406
- deps: deps.sso,
407
- });
408
- if (result.ok) {
409
- deps.log.info("msteams sso token exchanged", {
410
- userId: user.userId,
411
- hasExpiry: Boolean(result.expiresAt),
412
- });
413
- } else {
414
- deps.log.error("msteams sso token exchange failed", {
415
- code: result.code,
416
- status: result.status,
417
- message: result.message,
418
- });
419
- }
420
- return;
421
- }
422
-
423
- // signin/verifyState
424
- const parsed = parseSigninVerifyStateValue(ctx.activity.value);
425
- if (!parsed) {
426
- deps.log.debug?.("invalid signin/verifyState invoke value");
427
- return;
428
- }
429
- const result = await handleSigninVerifyStateInvoke({
430
- value: parsed,
431
- user,
432
- deps: deps.sso,
433
- });
434
- if (result.ok) {
435
- deps.log.info("msteams sso verifyState succeeded", {
436
- userId: user.userId,
437
- hasExpiry: Boolean(result.expiresAt),
438
- });
439
- } else {
440
- deps.log.error("msteams sso verifyState failed", {
441
- code: result.code,
442
- status: result.status,
443
- message: result.message,
444
- });
445
- }
446
- } catch (err) {
447
- deps.log.error("msteams sso invoke handler error", {
448
- error: formatUnknownError(err),
449
- });
450
- }
451
- return;
452
- }
453
-
454
- return originalRun.call(handler, context);
455
- };
456
- }
457
-
458
- handler.onMessage(async (context, next) => {
459
- try {
460
- await handleTeamsMessage(context as MSTeamsTurnContext);
461
- } catch (err) {
462
- deps.runtime.error(`msteams handler failed: ${formatUnknownError(err)}`);
463
- }
464
- await next();
465
- });
466
-
467
- handler.onMembersAdded(async (context, next) => {
468
- const ctx = context as MSTeamsTurnContext;
469
- const membersAdded = ctx.activity?.membersAdded ?? [];
470
- const botId = ctx.activity?.recipient?.id;
471
- const msteamsCfg = deps.cfg.channels?.msteams;
472
-
473
- for (const member of membersAdded) {
474
- if (member.id === botId) {
475
- // Bot was added to a conversation — send welcome card if configured.
476
- const conversationType =
477
- normalizeOptionalLowercaseString(ctx.activity?.conversation?.conversationType) ??
478
- "personal";
479
- const isPersonal = conversationType === "personal";
480
-
481
- if (isPersonal && msteamsCfg?.welcomeCard !== false) {
482
- const botName = ctx.activity?.recipient?.name ?? undefined;
483
- const card = buildWelcomeCard({
484
- botName,
485
- promptStarters: msteamsCfg?.promptStarters,
486
- });
487
- try {
488
- await ctx.sendActivity({
489
- type: "message",
490
- attachments: [
491
- {
492
- contentType: "application/vnd.microsoft.card.adaptive",
493
- content: card,
494
- },
495
- ],
496
- });
497
- deps.log.info("sent welcome card");
498
- } catch (err) {
499
- deps.log.debug?.("failed to send welcome card", { error: formatUnknownError(err) });
500
- }
501
- } else if (!isPersonal && msteamsCfg?.groupWelcomeCard === true) {
502
- const botName = ctx.activity?.recipient?.name ?? undefined;
503
- try {
504
- await ctx.sendActivity(buildGroupWelcomeText(botName));
505
- deps.log.info("sent group welcome message");
506
- } catch (err) {
507
- deps.log.debug?.("failed to send group welcome", { error: formatUnknownError(err) });
508
- }
509
- } else {
510
- deps.log.debug?.("skipping welcome (disabled by config or conversation type)");
511
- }
512
- } else {
513
- deps.log.debug?.("member added", { member: member.id });
514
- }
515
- }
516
- await next();
517
- });
518
-
519
- handler.onReactionsAdded(async (context, next) => {
520
- try {
521
- await handleReaction(context as MSTeamsTurnContext, "added");
522
- } catch (err) {
523
- deps.runtime.error(`msteams reaction handler failed: ${String(err)}`);
524
- }
525
- await next();
526
- });
527
-
528
- handler.onReactionsRemoved(async (context, next) => {
529
- try {
530
- await handleReaction(context as MSTeamsTurnContext, "removed");
531
- } catch (err) {
532
- deps.runtime.error(`msteams reaction handler failed: ${String(err)}`);
533
- }
534
- await next();
535
- });
536
-
537
- return handler;
538
- }
@@ -1,27 +0,0 @@
1
- import { type KlawConfig, type RuntimeEnv } from "../runtime-api.js";
2
- import type { MSTeamsConversationStore } from "./conversation-store.js";
3
- import type { MSTeamsAdapter } from "./messenger.js";
4
- import type { MSTeamsMonitorLogger } from "./monitor-types.js";
5
- import type { MSTeamsPollStore } from "./polls.js";
6
- import type { MSTeamsSsoDeps } from "./sso.js";
7
-
8
- export type MSTeamsMessageHandlerDeps = {
9
- cfg: KlawConfig;
10
- runtime: RuntimeEnv;
11
- appId: string;
12
- adapter: MSTeamsAdapter;
13
- tokenProvider: {
14
- getAccessToken: (scope: string) => Promise<string>;
15
- };
16
- textLimit: number;
17
- mediaMaxBytes: number;
18
- conversationStore: MSTeamsConversationStore;
19
- pollStore: MSTeamsPollStore;
20
- log: MSTeamsMonitorLogger;
21
- /**
22
- * Optional Bot Framework OAuth SSO deps. When omitted the plugin
23
- * does not handle `signin/tokenExchange` or `signin/verifyState`
24
- * invokes, matching the pre-SSO behavior.
25
- */
26
- sso?: MSTeamsSsoDeps;
27
- };
@@ -1,6 +0,0 @@
1
- export type MSTeamsMonitorLogger = {
2
- debug?: (message: string, meta?: Record<string, unknown>) => void;
3
- info: (message: string, meta?: Record<string, unknown>) => void;
4
- warn?: (message: string, meta?: Record<string, unknown>) => void;
5
- error: (message: string, meta?: Record<string, unknown>) => void;
6
- };