@openclaw/msteams 2026.3.13 → 2026.5.2-beta.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 (175) 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/index.ts +15 -12
  7. package/openclaw.plugin.json +553 -1
  8. package/package.json +46 -12
  9. package/runtime-api.ts +73 -0
  10. package/secret-contract-api.ts +5 -0
  11. package/setup-entry.ts +13 -0
  12. package/setup-plugin-api.ts +3 -0
  13. package/src/ai-entity.ts +7 -0
  14. package/src/approval-auth.ts +44 -0
  15. package/src/attachments/bot-framework.test.ts +461 -0
  16. package/src/attachments/bot-framework.ts +362 -0
  17. package/src/attachments/download.ts +63 -19
  18. package/src/attachments/graph.test.ts +416 -0
  19. package/src/attachments/graph.ts +163 -72
  20. package/src/attachments/html.ts +33 -1
  21. package/src/attachments/payload.ts +1 -1
  22. package/src/attachments/remote-media.test.ts +137 -0
  23. package/src/attachments/remote-media.ts +75 -8
  24. package/src/attachments/shared.test.ts +138 -1
  25. package/src/attachments/shared.ts +193 -26
  26. package/src/attachments/types.ts +10 -0
  27. package/src/attachments.graph.test.ts +342 -0
  28. package/src/attachments.helpers.test.ts +246 -0
  29. package/src/attachments.test-helpers.ts +17 -0
  30. package/src/attachments.test.ts +163 -418
  31. package/src/attachments.ts +5 -5
  32. package/src/block-streaming-config.test.ts +61 -0
  33. package/src/channel-api.ts +1 -0
  34. package/src/channel.actions.test.ts +742 -0
  35. package/src/channel.directory.test.ts +145 -4
  36. package/src/channel.runtime.ts +56 -0
  37. package/src/channel.setup.ts +77 -0
  38. package/src/channel.test.ts +128 -0
  39. package/src/channel.ts +1077 -395
  40. package/src/config-schema.ts +6 -0
  41. package/src/config-ui-hints.ts +12 -0
  42. package/src/conversation-store-fs.test.ts +4 -5
  43. package/src/conversation-store-fs.ts +35 -51
  44. package/src/conversation-store-helpers.test.ts +202 -0
  45. package/src/conversation-store-helpers.ts +105 -0
  46. package/src/conversation-store-memory.ts +27 -23
  47. package/src/conversation-store.shared.test.ts +225 -0
  48. package/src/conversation-store.ts +30 -0
  49. package/src/directory-live.test.ts +156 -0
  50. package/src/directory-live.ts +7 -4
  51. package/src/doctor.ts +27 -0
  52. package/src/errors.test.ts +64 -1
  53. package/src/errors.ts +50 -9
  54. package/src/feedback-reflection-prompt.ts +117 -0
  55. package/src/feedback-reflection-store.ts +114 -0
  56. package/src/feedback-reflection.test.ts +237 -0
  57. package/src/feedback-reflection.ts +283 -0
  58. package/src/file-consent-helpers.test.ts +83 -0
  59. package/src/file-consent-helpers.ts +64 -11
  60. package/src/file-consent-invoke.ts +150 -0
  61. package/src/file-consent.test.ts +363 -0
  62. package/src/file-consent.ts +165 -4
  63. package/src/graph-chat.ts +5 -3
  64. package/src/graph-group-management.test.ts +318 -0
  65. package/src/graph-group-management.ts +168 -0
  66. package/src/graph-members.test.ts +89 -0
  67. package/src/graph-members.ts +48 -0
  68. package/src/graph-messages.actions.test.ts +243 -0
  69. package/src/graph-messages.read.test.ts +391 -0
  70. package/src/graph-messages.search.test.ts +213 -0
  71. package/src/graph-messages.test-helpers.ts +50 -0
  72. package/src/graph-messages.ts +534 -0
  73. package/src/graph-teams.test.ts +215 -0
  74. package/src/graph-teams.ts +114 -0
  75. package/src/graph-thread.test.ts +246 -0
  76. package/src/graph-thread.ts +146 -0
  77. package/src/graph-upload.test.ts +161 -4
  78. package/src/graph-upload.ts +147 -56
  79. package/src/graph.test.ts +516 -0
  80. package/src/graph.ts +233 -21
  81. package/src/inbound.test.ts +156 -1
  82. package/src/inbound.ts +101 -1
  83. package/src/media-helpers.ts +1 -1
  84. package/src/mentions.test.ts +27 -18
  85. package/src/mentions.ts +2 -2
  86. package/src/messenger.test.ts +504 -23
  87. package/src/messenger.ts +133 -52
  88. package/src/monitor-handler/access.ts +125 -0
  89. package/src/monitor-handler/inbound-media.test.ts +289 -0
  90. package/src/monitor-handler/inbound-media.ts +57 -5
  91. package/src/monitor-handler/message-handler-mock-support.test-support.ts +28 -0
  92. package/src/monitor-handler/message-handler.authz.test.ts +588 -74
  93. package/src/monitor-handler/message-handler.dm-media.test.ts +54 -0
  94. package/src/monitor-handler/message-handler.test-support.ts +100 -0
  95. package/src/monitor-handler/message-handler.thread-parent.test.ts +223 -0
  96. package/src/monitor-handler/message-handler.thread-session.test.ts +77 -0
  97. package/src/monitor-handler/message-handler.ts +470 -164
  98. package/src/monitor-handler/reaction-handler.test.ts +267 -0
  99. package/src/monitor-handler/reaction-handler.ts +210 -0
  100. package/src/monitor-handler/thread-session.ts +17 -0
  101. package/src/monitor-handler.adaptive-card.test.ts +162 -0
  102. package/src/monitor-handler.feedback-authz.test.ts +314 -0
  103. package/src/monitor-handler.file-consent.test.ts +281 -79
  104. package/src/monitor-handler.sso.test.ts +563 -0
  105. package/src/monitor-handler.test-helpers.ts +180 -0
  106. package/src/monitor-handler.ts +459 -115
  107. package/src/monitor-handler.types.ts +27 -0
  108. package/src/monitor-types.ts +1 -0
  109. package/src/monitor.lifecycle.test.ts +74 -10
  110. package/src/monitor.test.ts +35 -1
  111. package/src/monitor.ts +143 -46
  112. package/src/oauth.flow.ts +77 -0
  113. package/src/oauth.shared.ts +37 -0
  114. package/src/oauth.test.ts +305 -0
  115. package/src/oauth.token.ts +158 -0
  116. package/src/oauth.ts +130 -0
  117. package/src/outbound.test.ts +10 -11
  118. package/src/outbound.ts +62 -44
  119. package/src/pending-uploads-fs.test.ts +246 -0
  120. package/src/pending-uploads-fs.ts +235 -0
  121. package/src/pending-uploads.test.ts +173 -0
  122. package/src/pending-uploads.ts +34 -2
  123. package/src/policy.test.ts +11 -5
  124. package/src/policy.ts +5 -5
  125. package/src/polls.test.ts +106 -5
  126. package/src/polls.ts +15 -7
  127. package/src/presentation.ts +68 -0
  128. package/src/probe.test.ts +27 -8
  129. package/src/probe.ts +43 -9
  130. package/src/reply-dispatcher.test.ts +437 -0
  131. package/src/reply-dispatcher.ts +259 -73
  132. package/src/reply-stream-controller.test.ts +235 -0
  133. package/src/reply-stream-controller.ts +147 -0
  134. package/src/resolve-allowlist.test.ts +105 -1
  135. package/src/resolve-allowlist.ts +112 -7
  136. package/src/runtime.ts +6 -3
  137. package/src/sdk-types.ts +43 -3
  138. package/src/sdk.test.ts +666 -0
  139. package/src/sdk.ts +867 -16
  140. package/src/secret-contract.ts +49 -0
  141. package/src/secret-input.ts +1 -1
  142. package/src/send-context.ts +76 -9
  143. package/src/send.test.ts +389 -5
  144. package/src/send.ts +140 -32
  145. package/src/sent-message-cache.ts +30 -18
  146. package/src/session-route.ts +40 -0
  147. package/src/setup-core.ts +160 -0
  148. package/src/setup-surface.test.ts +202 -0
  149. package/src/setup-surface.ts +320 -0
  150. package/src/sso-token-store.test.ts +72 -0
  151. package/src/sso-token-store.ts +166 -0
  152. package/src/sso.ts +300 -0
  153. package/src/storage.ts +1 -1
  154. package/src/store-fs.ts +2 -2
  155. package/src/streaming-message.test.ts +262 -0
  156. package/src/streaming-message.ts +297 -0
  157. package/src/test-runtime.ts +1 -1
  158. package/src/thread-parent-context.test.ts +224 -0
  159. package/src/thread-parent-context.ts +159 -0
  160. package/src/token.test.ts +237 -50
  161. package/src/token.ts +162 -7
  162. package/src/user-agent.test.ts +86 -0
  163. package/src/user-agent.ts +53 -0
  164. package/src/webhook-timeouts.ts +27 -0
  165. package/src/welcome-card.test.ts +81 -0
  166. package/src/welcome-card.ts +57 -0
  167. package/test-api.ts +1 -0
  168. package/tsconfig.json +16 -0
  169. package/CHANGELOG.md +0 -107
  170. package/src/file-lock.ts +0 -1
  171. package/src/graph-users.test.ts +0 -66
  172. package/src/onboarding.ts +0 -381
  173. package/src/polls-store.test.ts +0 -38
  174. package/src/revoked-context.test.ts +0 -39
  175. package/src/token-response.test.ts +0 -23
@@ -1,18 +1,25 @@
1
- import type { OpenClawConfig, RuntimeEnv } from "openclaw/plugin-sdk/msteams";
2
- import type { MSTeamsConversationStore } from "./conversation-store.js";
3
- import { buildFileInfoCard, parseFileConsentInvoke, uploadToConsentUrl } from "./file-consent.js";
4
- import { normalizeMSTeamsConversationId } from "./inbound.js";
5
- import type { MSTeamsAdapter } from "./messenger.js";
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
4
+ import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/text-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";
6
10
  import { createMSTeamsMessageHandler } from "./monitor-handler/message-handler.js";
7
- import type { MSTeamsMonitorLogger } from "./monitor-types.js";
8
- import { getPendingUpload, removePendingUpload } from "./pending-uploads.js";
9
- import type { MSTeamsPollStore } from "./polls.js";
10
- import { withRevokedProxyFallback } from "./revoked-context.js";
11
+ import { createMSTeamsReactionHandler } from "./monitor-handler/reaction-handler.js";
12
+ import { getMSTeamsRuntime } from "./runtime.js";
11
13
  import type { MSTeamsTurnContext } from "./sdk-types.js";
12
-
13
- export type MSTeamsAccessTokenProvider = {
14
- getAccessToken: (scope: string) => Promise<string>;
15
- };
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";
16
23
 
17
24
  export type MSTeamsActivityHandler = {
18
25
  onMessage: (
@@ -21,111 +28,287 @@ export type MSTeamsActivityHandler = {
21
28
  onMembersAdded: (
22
29
  handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
23
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;
24
37
  run?: (context: unknown) => Promise<void>;
25
38
  };
26
39
 
27
- export type MSTeamsMessageHandlerDeps = {
28
- cfg: OpenClawConfig;
29
- runtime: RuntimeEnv;
30
- appId: string;
31
- adapter: MSTeamsAdapter;
32
- tokenProvider: MSTeamsAccessTokenProvider;
33
- textLimit: number;
34
- mediaMaxBytes: number;
35
- conversationStore: MSTeamsConversationStore;
36
- pollStore: MSTeamsPollStore;
37
- log: MSTeamsMonitorLogger;
38
- };
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.access.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.senderGroupAccess.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
+ }
39
142
 
40
143
  /**
41
- * Handle fileConsent/invoke activities for large file uploads.
144
+ * Parse and handle feedback invoke activities (thumbs up/down).
145
+ * Returns true if the activity was a feedback invoke, false otherwise.
42
146
  */
43
- async function handleFileConsentInvoke(
147
+ async function handleFeedbackInvoke(
44
148
  context: MSTeamsTurnContext,
45
- log: MSTeamsMonitorLogger,
149
+ deps: MSTeamsMessageHandlerDeps,
46
150
  ): Promise<boolean> {
47
- const expiredUploadMessage =
48
- "The file upload request has expired. Please try sending the file again.";
49
151
  const activity = context.activity;
50
- if (activity.type !== "invoke" || activity.name !== "fileConsent/invoke") {
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) {
51
161
  return false;
52
162
  }
53
163
 
54
- const consentResponse = parseFileConsentInvoke(activity);
55
- if (!consentResponse) {
56
- log.debug?.("invalid file consent invoke", { value: activity.value });
164
+ // Teams feedback invoke format: actionName="feedback", actionValue.reaction="like"|"dislike"
165
+ if (value.actionName !== "feedback") {
57
166
  return false;
58
167
  }
59
168
 
60
- const uploadId =
61
- typeof consentResponse.context?.uploadId === "string"
62
- ? consentResponse.context.uploadId
63
- : undefined;
64
- const pendingFile = getPendingUpload(uploadId);
65
- if (pendingFile) {
66
- const pendingConversationId = normalizeMSTeamsConversationId(pendingFile.conversationId);
67
- const invokeConversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "");
68
- if (!invokeConversationId || pendingConversationId !== invokeConversationId) {
69
- log.info("file consent conversation mismatch", {
70
- uploadId,
71
- expectedConversationId: pendingConversationId,
72
- receivedConversationId: invokeConversationId || undefined,
73
- });
74
- if (consentResponse.action === "accept") {
75
- await context.sendActivity(expiredUploadMessage);
76
- }
77
- return true;
78
- }
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;
79
173
  }
80
174
 
81
- if (consentResponse.action === "accept" && consentResponse.uploadInfo) {
82
- if (pendingFile) {
83
- log.debug?.("user accepted file consent, uploading", {
84
- uploadId,
85
- filename: pendingFile.filename,
86
- size: pendingFile.buffer.length,
87
- });
88
-
89
- try {
90
- // Upload file to the provided URL
91
- await uploadToConsentUrl({
92
- url: consentResponse.uploadInfo.uploadUrl,
93
- buffer: pendingFile.buffer,
94
- contentType: pendingFile.contentType,
95
- });
96
-
97
- // Send confirmation card
98
- const fileInfoCard = buildFileInfoCard({
99
- filename: consentResponse.uploadInfo.name,
100
- contentUrl: consentResponse.uploadInfo.contentUrl,
101
- uniqueId: consentResponse.uploadInfo.uniqueId,
102
- fileType: consentResponse.uploadInfo.fileType,
103
- });
104
-
105
- await context.sendActivity({
106
- type: "message",
107
- attachments: [fileInfoCard],
108
- });
109
-
110
- log.info("file upload complete", {
111
- uploadId,
112
- filename: consentResponse.uploadInfo.name,
113
- uniqueId: consentResponse.uploadInfo.uniqueId,
114
- });
115
- } catch (err) {
116
- log.debug?.("file upload failed", { uploadId, error: String(err) });
117
- await context.sendActivity(`File upload failed: ${String(err)}`);
118
- } finally {
119
- removePendingUpload(uploadId);
120
- }
121
- } else {
122
- log.debug?.("pending file not found for consent", { uploadId });
123
- await context.sendActivity(expiredUploadMessage);
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
124
193
  }
125
- } else {
126
- // User declined
127
- log.debug?.("user declined file consent", { uploadId });
128
- removePendingUpload(uploadId);
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 fs.appendFile(transcriptFile, JSON.stringify(feedbackEvent) + "\n", "utf-8").catch(() => {
260
+ // Best effort — transcript dir may not exist yet
261
+ });
262
+ } catch {
263
+ // Best effort
264
+ }
265
+
266
+ // Build conversation reference for proactive messages (ack + reflection follow-up)
267
+ const conversationRef = {
268
+ activityId: activity.id,
269
+ user: {
270
+ id: activity.from?.id,
271
+ name: activity.from?.name,
272
+ aadObjectId: activity.from?.aadObjectId,
273
+ },
274
+ agent: activity.recipient
275
+ ? { id: activity.recipient.id, name: activity.recipient.name }
276
+ : undefined,
277
+ bot: activity.recipient
278
+ ? { id: activity.recipient.id, name: activity.recipient.name }
279
+ : undefined,
280
+ conversation: {
281
+ id: conversationId,
282
+ conversationType: activity.conversation?.conversationType,
283
+ tenantId: activity.conversation?.tenantId,
284
+ },
285
+ channelId: activity.channelId ?? "msteams",
286
+ serviceUrl: activity.serviceUrl,
287
+ locale: activity.locale,
288
+ };
289
+
290
+ // For negative feedback, trigger background reflection (fire-and-forget).
291
+ // No ack message — the reflection follow-up serves as the acknowledgement.
292
+ // Sending anything during the invoke handler causes "unable to reach app" errors.
293
+ if (isNegative && msteamsCfg?.feedbackReflection !== false) {
294
+ // Note: thumbedDownResponse is not populated here because we don't cache
295
+ // sent message text. The agent still has full session context for reflection
296
+ // since the reflection runs in the same session. The user comment (if any)
297
+ // provides additional signal.
298
+ runFeedbackReflection({
299
+ cfg: deps.cfg,
300
+ adapter: deps.adapter,
301
+ appId: deps.appId,
302
+ conversationRef,
303
+ sessionKey: route.sessionKey,
304
+ agentId: route.agentId,
305
+ conversationId,
306
+ feedbackMessageId: messageId,
307
+ userComment,
308
+ log: deps.log,
309
+ }).catch((err) => {
310
+ deps.log.error("feedback reflection failed", { error: formatUnknownError(err) });
311
+ });
129
312
  }
130
313
 
131
314
  return true;
@@ -136,6 +319,7 @@ export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
136
319
  deps: MSTeamsMessageHandlerDeps,
137
320
  ): T {
138
321
  const handleTeamsMessage = createMSTeamsMessageHandler(deps);
322
+ const handleReaction = createMSTeamsReactionHandler(deps);
139
323
 
140
324
  // Wrap the original run method to intercept invokes
141
325
  const originalRun = handler.run;
@@ -144,24 +328,125 @@ export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
144
328
  const ctx = context as MSTeamsTurnContext;
145
329
  // Handle file consent invokes before passing to normal flow
146
330
  if (ctx.activity?.type === "invoke" && ctx.activity?.name === "fileConsent/invoke") {
147
- // Send invoke response IMMEDIATELY to prevent Teams timeout
148
- await ctx.sendActivity({ type: "invokeResponse", value: { status: 200 } });
331
+ await respondToMSTeamsFileConsentInvoke(ctx, deps.log);
332
+ return;
333
+ }
149
334
 
150
- try {
151
- await withRevokedProxyFallback({
152
- run: async () => await handleFileConsentInvoke(ctx, deps.log),
153
- onRevoked: async () => true,
154
- onRevokedLog: () => {
155
- deps.log.debug?.(
156
- "turn context revoked during file consent invoke; skipping delayed response",
157
- );
335
+ // Handle feedback invokes (thumbs up/down on AI-generated messages).
336
+ // Just return after handling — the process() handler sends HTTP 200 automatically.
337
+ // Do NOT call sendActivity with invokeResponse; our custom adapter would POST
338
+ // a new activity to Bot Framework instead of responding to the HTTP request.
339
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "message/submitAction") {
340
+ const handled = await handleFeedbackInvoke(ctx, deps);
341
+ if (handled) {
342
+ return;
343
+ }
344
+ }
345
+
346
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "adaptiveCard/action") {
347
+ const text = serializeAdaptiveCardActionValue(ctx.activity?.value);
348
+ if (text) {
349
+ await handleTeamsMessage({
350
+ ...ctx,
351
+ activity: {
352
+ ...ctx.activity,
353
+ type: "message",
354
+ text,
158
355
  },
159
356
  });
357
+ return;
358
+ }
359
+ deps.log.debug?.("skipping adaptive card action invoke without value payload");
360
+ }
361
+
362
+ // Bot Framework OAuth SSO: Teams sends signin/tokenExchange (with a
363
+ // Teams-provided exchangeable token) or signin/verifyState (magic
364
+ // code fallback) after an oauthCard is presented. We must ack with
365
+ // HTTP 200 and, if configured, exchange the token with the Bot
366
+ // Framework User Token service and persist it for downstream tools.
367
+ if (
368
+ ctx.activity?.type === "invoke" &&
369
+ (ctx.activity?.name === "signin/tokenExchange" ||
370
+ ctx.activity?.name === "signin/verifyState")
371
+ ) {
372
+ // Always ack immediately — silently dropping the invoke causes
373
+ // the Teams card UI to report "Something went wrong".
374
+ await ctx.sendActivity({ type: "invokeResponse", value: { status: 200, body: {} } });
375
+
376
+ if (!(await isSigninInvokeAuthorized(ctx, deps))) {
377
+ return;
378
+ }
379
+
380
+ if (!deps.sso) {
381
+ deps.log.debug?.("signin invoke received but msteams.sso is not configured", {
382
+ name: ctx.activity.name,
383
+ });
384
+ return;
385
+ }
386
+
387
+ const user = {
388
+ userId: ctx.activity.from?.aadObjectId ?? ctx.activity.from?.id ?? "",
389
+ channelId: ctx.activity.channelId ?? "msteams",
390
+ };
391
+
392
+ try {
393
+ if (ctx.activity.name === "signin/tokenExchange") {
394
+ const parsed = parseSigninTokenExchangeValue(ctx.activity.value);
395
+ if (!parsed) {
396
+ deps.log.debug?.("invalid signin/tokenExchange invoke value");
397
+ return;
398
+ }
399
+ const result = await handleSigninTokenExchangeInvoke({
400
+ value: parsed,
401
+ user,
402
+ deps: deps.sso,
403
+ });
404
+ if (result.ok) {
405
+ deps.log.info("msteams sso token exchanged", {
406
+ userId: user.userId,
407
+ hasExpiry: Boolean(result.expiresAt),
408
+ });
409
+ } else {
410
+ deps.log.error("msteams sso token exchange failed", {
411
+ code: result.code,
412
+ status: result.status,
413
+ message: result.message,
414
+ });
415
+ }
416
+ return;
417
+ }
418
+
419
+ // signin/verifyState
420
+ const parsed = parseSigninVerifyStateValue(ctx.activity.value);
421
+ if (!parsed) {
422
+ deps.log.debug?.("invalid signin/verifyState invoke value");
423
+ return;
424
+ }
425
+ const result = await handleSigninVerifyStateInvoke({
426
+ value: parsed,
427
+ user,
428
+ deps: deps.sso,
429
+ });
430
+ if (result.ok) {
431
+ deps.log.info("msteams sso verifyState succeeded", {
432
+ userId: user.userId,
433
+ hasExpiry: Boolean(result.expiresAt),
434
+ });
435
+ } else {
436
+ deps.log.error("msteams sso verifyState failed", {
437
+ code: result.code,
438
+ status: result.status,
439
+ message: result.message,
440
+ });
441
+ }
160
442
  } catch (err) {
161
- deps.log.debug?.("file consent handler error", { error: String(err) });
443
+ deps.log.error("msteams sso invoke handler error", {
444
+ error: formatUnknownError(err),
445
+ });
162
446
  }
163
447
  return;
164
448
  }
449
+
165
450
  return originalRun.call(handler, context);
166
451
  };
167
452
  }
@@ -170,21 +455,80 @@ export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
170
455
  try {
171
456
  await handleTeamsMessage(context as MSTeamsTurnContext);
172
457
  } catch (err) {
173
- deps.runtime.error?.(`msteams handler failed: ${String(err)}`);
458
+ deps.runtime.error?.(`msteams handler failed: ${formatUnknownError(err)}`);
174
459
  }
175
460
  await next();
176
461
  });
177
462
 
178
463
  handler.onMembersAdded(async (context, next) => {
179
- const membersAdded = (context as MSTeamsTurnContext).activity?.membersAdded ?? [];
464
+ const ctx = context as MSTeamsTurnContext;
465
+ const membersAdded = ctx.activity?.membersAdded ?? [];
466
+ const botId = ctx.activity?.recipient?.id;
467
+ const msteamsCfg = deps.cfg.channels?.msteams;
468
+
180
469
  for (const member of membersAdded) {
181
- if (member.id !== (context as MSTeamsTurnContext).activity?.recipient?.id) {
470
+ if (member.id === botId) {
471
+ // Bot was added to a conversation — send welcome card if configured.
472
+ const conversationType =
473
+ normalizeOptionalLowercaseString(ctx.activity?.conversation?.conversationType) ??
474
+ "personal";
475
+ const isPersonal = conversationType === "personal";
476
+
477
+ if (isPersonal && msteamsCfg?.welcomeCard !== false) {
478
+ const botName = ctx.activity?.recipient?.name ?? undefined;
479
+ const card = buildWelcomeCard({
480
+ botName,
481
+ promptStarters: msteamsCfg?.promptStarters,
482
+ });
483
+ try {
484
+ await ctx.sendActivity({
485
+ type: "message",
486
+ attachments: [
487
+ {
488
+ contentType: "application/vnd.microsoft.card.adaptive",
489
+ content: card,
490
+ },
491
+ ],
492
+ });
493
+ deps.log.info("sent welcome card");
494
+ } catch (err) {
495
+ deps.log.debug?.("failed to send welcome card", { error: formatUnknownError(err) });
496
+ }
497
+ } else if (!isPersonal && msteamsCfg?.groupWelcomeCard === true) {
498
+ const botName = ctx.activity?.recipient?.name ?? undefined;
499
+ try {
500
+ await ctx.sendActivity(buildGroupWelcomeText(botName));
501
+ deps.log.info("sent group welcome message");
502
+ } catch (err) {
503
+ deps.log.debug?.("failed to send group welcome", { error: formatUnknownError(err) });
504
+ }
505
+ } else {
506
+ deps.log.debug?.("skipping welcome (disabled by config or conversation type)");
507
+ }
508
+ } else {
182
509
  deps.log.debug?.("member added", { member: member.id });
183
- // Don't send welcome message - let the user initiate conversation.
184
510
  }
185
511
  }
186
512
  await next();
187
513
  });
188
514
 
515
+ handler.onReactionsAdded(async (context, next) => {
516
+ try {
517
+ await handleReaction(context as MSTeamsTurnContext, "added");
518
+ } catch (err) {
519
+ deps.runtime.error?.(`msteams reaction handler failed: ${String(err)}`);
520
+ }
521
+ await next();
522
+ });
523
+
524
+ handler.onReactionsRemoved(async (context, next) => {
525
+ try {
526
+ await handleReaction(context as MSTeamsTurnContext, "removed");
527
+ } catch (err) {
528
+ deps.runtime.error?.(`msteams reaction handler failed: ${String(err)}`);
529
+ }
530
+ await next();
531
+ });
532
+
189
533
  return handler;
190
534
  }
@@ -0,0 +1,27 @@
1
+ import { type OpenClawConfig, 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: OpenClawConfig;
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,5 +1,6 @@
1
1
  export type MSTeamsMonitorLogger = {
2
2
  debug?: (message: string, meta?: Record<string, unknown>) => void;
3
3
  info: (message: string, meta?: Record<string, unknown>) => void;
4
+ warn?: (message: string, meta?: Record<string, unknown>) => void;
4
5
  error: (message: string, meta?: Record<string, unknown>) => void;
5
6
  };