@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
package/src/channel.ts CHANGED
@@ -1,35 +1,53 @@
1
- import {
2
- collectAllowlistProviderRestrictSendersWarnings,
3
- formatAllowFromLowercase,
4
- } from "openclaw/plugin-sdk/compat";
1
+ import { describeAccountSnapshot } from "openclaw/plugin-sdk/account-helpers";
2
+ import { formatAllowFromLowercase } from "openclaw/plugin-sdk/allow-from";
3
+ import { createTopLevelChannelConfigAdapter } from "openclaw/plugin-sdk/channel-config-helpers";
5
4
  import type {
6
- ChannelMessageActionName,
7
- ChannelPlugin,
8
- OpenClawConfig,
9
- } from "openclaw/plugin-sdk/msteams";
5
+ ChannelMessageActionAdapter,
6
+ ChannelMessageToolDiscovery,
7
+ } from "openclaw/plugin-sdk/channel-contract";
8
+ import { createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
9
+ import { createPairingPrefixStripper } from "openclaw/plugin-sdk/channel-pairing";
10
+ import {
11
+ createAllowlistProviderGroupPolicyWarningCollector,
12
+ projectConfigWarningCollector,
13
+ } from "openclaw/plugin-sdk/channel-policy";
14
+ import {
15
+ createChannelDirectoryAdapter,
16
+ createRuntimeDirectoryLiveAdapter,
17
+ listDirectoryEntriesFromSources,
18
+ } from "openclaw/plugin-sdk/directory-runtime";
19
+ import { normalizeMessagePresentation } from "openclaw/plugin-sdk/interactive-runtime";
20
+ import { createLazyRuntimeNamedExport } from "openclaw/plugin-sdk/lazy-runtime";
21
+ import { createRuntimeOutboundDelegates } from "openclaw/plugin-sdk/outbound-runtime";
22
+ import { createComputedAccountStatusAdapter } from "openclaw/plugin-sdk/status-helpers";
23
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
24
+ import { Type } from "typebox";
25
+ import type { ChannelMessageActionName, ChannelPlugin, OpenClawConfig } from "../runtime-api.js";
10
26
  import {
11
27
  buildProbeChannelStatusSummary,
12
- buildRuntimeAccountStatusSnapshot,
13
- buildChannelConfigSchema,
28
+ chunkTextForOutbound,
14
29
  createDefaultChannelRuntimeState,
15
30
  DEFAULT_ACCOUNT_ID,
16
- MSTeamsConfigSchema,
17
31
  PAIRING_APPROVED_MESSAGE,
18
- } from "openclaw/plugin-sdk/msteams";
19
- import { listMSTeamsDirectoryGroupsLive, listMSTeamsDirectoryPeersLive } from "./directory-live.js";
20
- import { msteamsOnboardingAdapter } from "./onboarding.js";
21
- import { msteamsOutbound } from "./outbound.js";
32
+ } from "../runtime-api.js";
33
+ import { msTeamsApprovalAuth } from "./approval-auth.js";
34
+ import { MSTeamsChannelConfigSchema } from "./config-schema.js";
35
+ import { collectMSTeamsMutableAllowlistWarnings } from "./doctor.js";
22
36
  import { resolveMSTeamsGroupToolPolicy } from "./policy.js";
23
- import { probeMSTeams } from "./probe.js";
37
+ import { buildMSTeamsPresentationCard } from "./presentation.js";
38
+ import type { ProbeMSTeamsResult } from "./probe.js";
24
39
  import {
25
40
  normalizeMSTeamsMessagingTarget,
26
41
  normalizeMSTeamsUserInput,
42
+ looksLikeMSTeamsTargetId,
27
43
  parseMSTeamsConversationId,
28
44
  parseMSTeamsTeamChannelInput,
29
45
  resolveMSTeamsChannelAllowlist,
30
46
  resolveMSTeamsUserAllowlist,
31
47
  } from "./resolve-allowlist.js";
32
- import { sendAdaptiveCardMSTeams, sendMessageMSTeams } from "./send.js";
48
+ import { resolveMSTeamsOutboundSessionRoute } from "./session-route.js";
49
+ import { msteamsSetupAdapter } from "./setup-core.js";
50
+ import { msteamsSetupWizard } from "./setup-surface.js";
33
51
  import { resolveMSTeamsCredentials } from "./token.js";
34
52
 
35
53
  type ResolvedMSTeamsAccount = {
@@ -44,411 +62,1075 @@ const meta = {
44
62
  selectionLabel: "Microsoft Teams (Bot Framework)",
45
63
  docsPath: "/channels/msteams",
46
64
  docsLabel: "msteams",
47
- blurb: "Bot Framework; enterprise support.",
65
+ blurb: "Teams SDK; enterprise support.",
48
66
  aliases: ["teams"],
49
67
  order: 60,
50
68
  } as const;
51
69
 
52
- export const msteamsPlugin: ChannelPlugin<ResolvedMSTeamsAccount> = {
53
- id: "msteams",
54
- meta: {
55
- ...meta,
56
- aliases: [...meta.aliases],
57
- },
58
- onboarding: msteamsOnboardingAdapter,
59
- pairing: {
60
- idLabel: "msteamsUserId",
61
- normalizeAllowEntry: (entry) => entry.replace(/^(msteams|user):/i, ""),
62
- notifyApproval: async ({ cfg, id }) => {
63
- await sendMessageMSTeams({
64
- cfg,
65
- to: id,
66
- text: PAIRING_APPROVED_MESSAGE,
67
- });
70
+ const TEAMS_GRAPH_PERMISSION_HINTS: Record<string, string> = {
71
+ "ChannelMessage.Read.All": "channel history",
72
+ "Chat.Read.All": "chat history",
73
+ "Channel.ReadBasic.All": "channel list",
74
+ "Team.ReadBasic.All": "team list",
75
+ "TeamsActivity.Read.All": "teams activity",
76
+ "Sites.Read.All": "files (SharePoint)",
77
+ "Files.Read.All": "files (OneDrive)",
78
+ };
79
+
80
+ const collectMSTeamsSecurityWarnings = createAllowlistProviderGroupPolicyWarningCollector<{
81
+ cfg: OpenClawConfig;
82
+ }>({
83
+ providerConfigPresent: (cfg) => cfg.channels?.msteams !== undefined,
84
+ resolveGroupPolicy: ({ cfg }) => cfg.channels?.msteams?.groupPolicy,
85
+ collect: ({ groupPolicy }) =>
86
+ groupPolicy === "open"
87
+ ? [
88
+ '- MS Teams groups: groupPolicy="open" allows any member to trigger (mention-gated). Set channels.msteams.groupPolicy="allowlist" + channels.msteams.groupAllowFrom to restrict senders.',
89
+ ]
90
+ : [],
91
+ });
92
+
93
+ const loadMSTeamsChannelRuntime = createLazyRuntimeNamedExport(
94
+ () => import("./channel.runtime.js"),
95
+ "msTeamsChannelRuntime",
96
+ );
97
+
98
+ const resolveMSTeamsChannelConfig = (cfg: OpenClawConfig) => ({
99
+ allowFrom: cfg.channels?.msteams?.allowFrom,
100
+ defaultTo: cfg.channels?.msteams?.defaultTo,
101
+ });
102
+
103
+ const msteamsConfigAdapter = createTopLevelChannelConfigAdapter<
104
+ ResolvedMSTeamsAccount,
105
+ {
106
+ allowFrom?: Array<string | number>;
107
+ defaultTo?: string;
108
+ }
109
+ >({
110
+ sectionKey: "msteams",
111
+ resolveAccount: (cfg) => ({
112
+ accountId: DEFAULT_ACCOUNT_ID,
113
+ enabled: cfg.channels?.msteams?.enabled !== false,
114
+ configured: Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams)),
115
+ }),
116
+ resolveAccessorAccount: ({ cfg }) => resolveMSTeamsChannelConfig(cfg),
117
+ resolveAllowFrom: (account) => account.allowFrom,
118
+ formatAllowFrom: (allowFrom) => formatAllowFromLowercase({ allowFrom }),
119
+ resolveDefaultTo: (account) => account.defaultTo,
120
+ });
121
+
122
+ function jsonActionResult(data: Record<string, unknown>) {
123
+ const text = JSON.stringify(data);
124
+ return {
125
+ content: [{ type: "text" as const, text }],
126
+ details: data,
127
+ };
128
+ }
129
+
130
+ function jsonMSTeamsActionResult(action: string, data: Record<string, unknown> = {}) {
131
+ return jsonActionResult({ channel: "msteams", action, ...data });
132
+ }
133
+
134
+ function jsonMSTeamsOkActionResult(action: string, data: Record<string, unknown> = {}) {
135
+ return jsonActionResult({ ok: true, channel: "msteams", action, ...data });
136
+ }
137
+
138
+ function jsonMSTeamsConversationResult(conversationId: string | undefined) {
139
+ return jsonActionResultWithDetails(
140
+ {
141
+ ok: true,
142
+ channel: "msteams",
143
+ conversationId,
68
144
  },
69
- },
70
- capabilities: {
71
- chatTypes: ["direct", "channel", "thread"],
72
- polls: true,
73
- threads: true,
74
- media: true,
75
- },
76
- agentPrompt: {
77
- messageToolHints: () => [
78
- "- Adaptive Cards supported. Use `action=send` with `card={type,version,body}` to send rich cards.",
79
- "- MSTeams targeting: omit `target` to reply to the current conversation (auto-inferred). Explicit targets: `user:ID` or `user:Display Name` (requires Graph API) for DMs, `conversation:19:...@thread.tacv2` for groups/channels. Prefer IDs over display names for speed.",
80
- ],
81
- },
82
- threading: {
83
- buildToolContext: ({ context, hasRepliedRef }) => ({
84
- currentChannelId: context.To?.trim() || undefined,
85
- currentThreadTs: context.ReplyToId,
86
- hasRepliedRef,
87
- }),
88
- },
89
- groups: {
90
- resolveToolPolicy: resolveMSTeamsGroupToolPolicy,
91
- },
92
- reload: { configPrefixes: ["channels.msteams"] },
93
- configSchema: buildChannelConfigSchema(MSTeamsConfigSchema),
94
- config: {
95
- listAccountIds: () => [DEFAULT_ACCOUNT_ID],
96
- resolveAccount: (cfg) => ({
97
- accountId: DEFAULT_ACCOUNT_ID,
98
- enabled: cfg.channels?.msteams?.enabled !== false,
99
- configured: Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams)),
100
- }),
101
- defaultAccountId: () => DEFAULT_ACCOUNT_ID,
102
- setAccountEnabled: ({ cfg, enabled }) => ({
103
- ...cfg,
104
- channels: {
105
- ...cfg.channels,
106
- msteams: {
107
- ...cfg.channels?.msteams,
108
- enabled,
109
- },
110
- },
111
- }),
112
- deleteAccount: ({ cfg }) => {
113
- const next = { ...cfg } as OpenClawConfig;
114
- const nextChannels = { ...cfg.channels };
115
- delete nextChannels.msteams;
116
- if (Object.keys(nextChannels).length > 0) {
117
- next.channels = nextChannels;
118
- } else {
119
- delete next.channels;
145
+ { ok: true, channel: "msteams" },
146
+ );
147
+ }
148
+
149
+ function jsonActionResultWithDetails(
150
+ contentData: Record<string, unknown>,
151
+ details: Record<string, unknown>,
152
+ ) {
153
+ return {
154
+ content: [{ type: "text" as const, text: JSON.stringify(contentData) }],
155
+ details,
156
+ };
157
+ }
158
+
159
+ const MSTEAMS_REACTION_TYPES = ["like", "heart", "laugh", "surprised", "sad", "angry"] as const;
160
+
161
+ function actionError(message: string) {
162
+ return {
163
+ isError: true as const,
164
+ content: [{ type: "text" as const, text: message }],
165
+ details: { error: message },
166
+ };
167
+ }
168
+
169
+ function resolveActionTarget(
170
+ params: Record<string, unknown>,
171
+ currentChannelId?: string | null,
172
+ ): string {
173
+ return typeof params.to === "string"
174
+ ? params.to.trim()
175
+ : typeof params.target === "string"
176
+ ? params.target.trim()
177
+ : (currentChannelId?.trim() ?? "");
178
+ }
179
+
180
+ function resolveGraphActionTarget(
181
+ params: Record<string, unknown>,
182
+ currentChannelId?: string | null,
183
+ currentGraphChannelId?: string | null,
184
+ ): string {
185
+ return resolveActionTarget(params, currentGraphChannelId ?? currentChannelId);
186
+ }
187
+
188
+ function resolveActionMessageId(params: Record<string, unknown>): string {
189
+ return normalizeOptionalString(params.messageId) ?? "";
190
+ }
191
+
192
+ function resolveActionPinnedMessageId(params: Record<string, unknown>): string {
193
+ return typeof params.pinnedMessageId === "string"
194
+ ? params.pinnedMessageId.trim()
195
+ : typeof params.messageId === "string"
196
+ ? params.messageId.trim()
197
+ : "";
198
+ }
199
+
200
+ function resolveActionQuery(params: Record<string, unknown>): string {
201
+ return normalizeOptionalString(params.query) ?? "";
202
+ }
203
+
204
+ function resolveActionContent(params: Record<string, unknown>): string {
205
+ return typeof params.text === "string"
206
+ ? params.text
207
+ : typeof params.content === "string"
208
+ ? params.content
209
+ : typeof params.message === "string"
210
+ ? params.message
211
+ : "";
212
+ }
213
+
214
+ function readOptionalTrimmedString(
215
+ params: Record<string, unknown>,
216
+ key: string,
217
+ ): string | undefined {
218
+ return typeof params[key] === "string" ? params[key].trim() || undefined : undefined;
219
+ }
220
+
221
+ function resolveActionUploadFilePath(params: Record<string, unknown>): string | undefined {
222
+ for (const key of ["filePath", "path", "media"] as const) {
223
+ if (typeof params[key] === "string") {
224
+ const value = params[key];
225
+ if (value.trim()) {
226
+ return value;
120
227
  }
121
- return next;
122
- },
123
- isConfigured: (_account, cfg) => Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams)),
124
- describeAccount: (account) => ({
125
- accountId: account.accountId,
126
- enabled: account.enabled,
127
- configured: account.configured,
128
- }),
129
- resolveAllowFrom: ({ cfg }) => cfg.channels?.msteams?.allowFrom ?? [],
130
- formatAllowFrom: ({ allowFrom }) => formatAllowFromLowercase({ allowFrom }),
131
- resolveDefaultTo: ({ cfg }) => cfg.channels?.msteams?.defaultTo?.trim() || undefined,
132
- },
133
- security: {
134
- collectWarnings: ({ cfg }) => {
135
- return collectAllowlistProviderRestrictSendersWarnings({
136
- cfg,
137
- providerConfigPresent: cfg.channels?.msteams !== undefined,
138
- configuredGroupPolicy: cfg.channels?.msteams?.groupPolicy,
139
- surface: "MS Teams groups",
140
- openScope: "any member",
141
- groupPolicyPath: "channels.msteams.groupPolicy",
142
- groupAllowFromPath: "channels.msteams.groupAllowFrom",
143
- });
144
- },
145
- },
146
- setup: {
147
- resolveAccountId: () => DEFAULT_ACCOUNT_ID,
148
- applyAccountConfig: ({ cfg }) => ({
149
- ...cfg,
150
- channels: {
151
- ...cfg.channels,
152
- msteams: {
153
- ...cfg.channels?.msteams,
154
- enabled: true,
228
+ }
229
+ }
230
+ return undefined;
231
+ }
232
+
233
+ function resolveRequiredActionTarget(params: {
234
+ actionLabel: string;
235
+ toolParams: Record<string, unknown>;
236
+ currentChannelId?: string | null;
237
+ currentGraphChannelId?: string | null;
238
+ graphOnly?: boolean;
239
+ }): string | ReturnType<typeof actionError> {
240
+ const to = params.graphOnly
241
+ ? resolveGraphActionTarget(
242
+ params.toolParams,
243
+ params.currentChannelId,
244
+ params.currentGraphChannelId,
245
+ )
246
+ : resolveActionTarget(params.toolParams, params.currentChannelId);
247
+ if (!to) {
248
+ return actionError(`${params.actionLabel} requires a target (to).`);
249
+ }
250
+ return to;
251
+ }
252
+
253
+ function resolveRequiredActionMessageTarget(params: {
254
+ actionLabel: string;
255
+ toolParams: Record<string, unknown>;
256
+ currentChannelId?: string | null;
257
+ currentGraphChannelId?: string | null;
258
+ graphOnly?: boolean;
259
+ }): { to: string; messageId: string } | ReturnType<typeof actionError> {
260
+ const to = params.graphOnly
261
+ ? resolveGraphActionTarget(
262
+ params.toolParams,
263
+ params.currentChannelId,
264
+ params.currentGraphChannelId,
265
+ )
266
+ : resolveActionTarget(params.toolParams, params.currentChannelId);
267
+ const messageId = resolveActionMessageId(params.toolParams);
268
+ if (!to || !messageId) {
269
+ return actionError(`${params.actionLabel} requires a target (to) and messageId.`);
270
+ }
271
+ return { to, messageId };
272
+ }
273
+
274
+ function resolveRequiredActionPinnedMessageTarget(params: {
275
+ actionLabel: string;
276
+ toolParams: Record<string, unknown>;
277
+ currentChannelId?: string | null;
278
+ currentGraphChannelId?: string | null;
279
+ graphOnly?: boolean;
280
+ }): { to: string; pinnedMessageId: string } | ReturnType<typeof actionError> {
281
+ const to = params.graphOnly
282
+ ? resolveGraphActionTarget(
283
+ params.toolParams,
284
+ params.currentChannelId,
285
+ params.currentGraphChannelId,
286
+ )
287
+ : resolveActionTarget(params.toolParams, params.currentChannelId);
288
+ const pinnedMessageId = resolveActionPinnedMessageId(params.toolParams);
289
+ if (!to || !pinnedMessageId) {
290
+ return actionError(`${params.actionLabel} requires a target (to) and pinnedMessageId.`);
291
+ }
292
+ return { to, pinnedMessageId };
293
+ }
294
+
295
+ async function runWithRequiredActionTarget<T>(params: {
296
+ actionLabel: string;
297
+ toolParams: Record<string, unknown>;
298
+ currentChannelId?: string | null;
299
+ currentGraphChannelId?: string | null;
300
+ graphOnly?: boolean;
301
+ run: (to: string) => Promise<T>;
302
+ }): Promise<T | ReturnType<typeof actionError>> {
303
+ const to = resolveRequiredActionTarget({
304
+ actionLabel: params.actionLabel,
305
+ toolParams: params.toolParams,
306
+ currentChannelId: params.currentChannelId,
307
+ currentGraphChannelId: params.currentGraphChannelId,
308
+ graphOnly: params.graphOnly,
309
+ });
310
+ if (typeof to !== "string") {
311
+ return to;
312
+ }
313
+ return await params.run(to);
314
+ }
315
+
316
+ async function runWithRequiredActionMessageTarget<T>(params: {
317
+ actionLabel: string;
318
+ toolParams: Record<string, unknown>;
319
+ currentChannelId?: string | null;
320
+ currentGraphChannelId?: string | null;
321
+ graphOnly?: boolean;
322
+ run: (target: { to: string; messageId: string }) => Promise<T>;
323
+ }): Promise<T | ReturnType<typeof actionError>> {
324
+ const target = resolveRequiredActionMessageTarget({
325
+ actionLabel: params.actionLabel,
326
+ toolParams: params.toolParams,
327
+ currentChannelId: params.currentChannelId,
328
+ currentGraphChannelId: params.currentGraphChannelId,
329
+ graphOnly: params.graphOnly,
330
+ });
331
+ if ("isError" in target) {
332
+ return target;
333
+ }
334
+ return await params.run(target);
335
+ }
336
+
337
+ async function runWithRequiredActionPinnedMessageTarget<T>(params: {
338
+ actionLabel: string;
339
+ toolParams: Record<string, unknown>;
340
+ currentChannelId?: string | null;
341
+ currentGraphChannelId?: string | null;
342
+ graphOnly?: boolean;
343
+ run: (target: { to: string; pinnedMessageId: string }) => Promise<T>;
344
+ }): Promise<T | ReturnType<typeof actionError>> {
345
+ const target = resolveRequiredActionPinnedMessageTarget({
346
+ actionLabel: params.actionLabel,
347
+ toolParams: params.toolParams,
348
+ currentChannelId: params.currentChannelId,
349
+ currentGraphChannelId: params.currentGraphChannelId,
350
+ graphOnly: params.graphOnly,
351
+ });
352
+ if ("isError" in target) {
353
+ return target;
354
+ }
355
+ return await params.run(target);
356
+ }
357
+
358
+ function describeMSTeamsMessageTool({
359
+ cfg,
360
+ }: Parameters<
361
+ NonNullable<ChannelMessageActionAdapter["describeMessageTool"]>
362
+ >[0]): ChannelMessageToolDiscovery {
363
+ const enabled =
364
+ cfg.channels?.msteams?.enabled !== false &&
365
+ Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams));
366
+ return {
367
+ actions: enabled
368
+ ? ([
369
+ "upload-file",
370
+ "poll",
371
+ "edit",
372
+ "delete",
373
+ "pin",
374
+ "unpin",
375
+ "list-pins",
376
+ "read",
377
+ "react",
378
+ "reactions",
379
+ "search",
380
+ "member-info",
381
+ "channel-list",
382
+ "channel-info",
383
+ "addParticipant",
384
+ "removeParticipant",
385
+ "renameGroup",
386
+ ] satisfies ChannelMessageActionName[])
387
+ : [],
388
+ capabilities: enabled ? ["presentation"] : [],
389
+ schema: enabled
390
+ ? {
391
+ actions: ["unpin"],
392
+ properties: {
393
+ pinnedMessageId: Type.Optional(
394
+ Type.String({
395
+ description:
396
+ "Pinned message resource ID for unpin (from pin or list-pins, not the chat message ID).",
397
+ }),
398
+ ),
399
+ },
400
+ }
401
+ : null,
402
+ };
403
+ }
404
+
405
+ export const msteamsPlugin: ChannelPlugin<ResolvedMSTeamsAccount, ProbeMSTeamsResult> =
406
+ createChatChannelPlugin({
407
+ base: {
408
+ id: "msteams",
409
+ meta: {
410
+ ...meta,
411
+ aliases: [...meta.aliases],
412
+ },
413
+ setupWizard: msteamsSetupWizard,
414
+ capabilities: {
415
+ chatTypes: ["direct", "channel", "thread"],
416
+ polls: true,
417
+ threads: true,
418
+ media: true,
419
+ },
420
+ streaming: {
421
+ blockStreamingCoalesceDefaults: { minChars: 1500, idleMs: 1000 },
422
+ },
423
+ agentPrompt: {
424
+ messageToolHints: () => [
425
+ "- Adaptive Cards supported. Use `action=send` with `card={type,version,body}` to send rich cards.",
426
+ "- MSTeams targeting: omit `target` to reply to the current conversation (auto-inferred). Explicit targets: `user:ID` or `user:Display Name` (requires Graph API) for DMs, `conversation:19:...@thread.tacv2` for groups/channels. Prefer IDs over display names for speed.",
427
+ ],
428
+ },
429
+ groups: {
430
+ resolveToolPolicy: resolveMSTeamsGroupToolPolicy,
431
+ },
432
+ reload: { configPrefixes: ["channels.msteams"] },
433
+ configSchema: MSTeamsChannelConfigSchema,
434
+ config: {
435
+ ...msteamsConfigAdapter,
436
+ isConfigured: (_account, cfg) => Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams)),
437
+ describeAccount: (account) =>
438
+ describeAccountSnapshot({
439
+ account,
440
+ configured: account.configured,
441
+ }),
442
+ },
443
+ approvalCapability: msTeamsApprovalAuth,
444
+ doctor: {
445
+ dmAllowFromMode: "topOnly",
446
+ groupModel: "hybrid",
447
+ groupAllowFromFallbackToAllowFrom: false,
448
+ warnOnEmptyGroupSenderAllowlist: true,
449
+ collectMutableAllowlistWarnings: collectMSTeamsMutableAllowlistWarnings,
450
+ },
451
+ setup: msteamsSetupAdapter,
452
+ messaging: {
453
+ targetPrefixes: ["msteams", "teams"],
454
+ normalizeTarget: normalizeMSTeamsMessagingTarget,
455
+ resolveOutboundSessionRoute: (params) => resolveMSTeamsOutboundSessionRoute(params),
456
+ targetResolver: {
457
+ looksLikeId: (raw) => looksLikeMSTeamsTargetId(raw),
458
+ hint: "<conversationId|user:ID|conversation:ID>",
155
459
  },
156
460
  },
157
- }),
158
- },
159
- messaging: {
160
- normalizeTarget: normalizeMSTeamsMessagingTarget,
161
- targetResolver: {
162
- looksLikeId: (raw) => {
163
- const trimmed = raw.trim();
164
- if (!trimmed) {
165
- return false;
166
- }
167
- if (/^conversation:/i.test(trimmed)) {
168
- return true;
169
- }
170
- if (/^user:/i.test(trimmed)) {
171
- // Only treat as ID if the value after user: looks like a UUID
172
- const id = trimmed.slice("user:".length).trim();
173
- return /^[0-9a-fA-F-]{16,}$/.test(id);
174
- }
175
- return trimmed.includes("@thread");
461
+ directory: createChannelDirectoryAdapter({
462
+ self: async ({ cfg }) => {
463
+ const creds = resolveMSTeamsCredentials(cfg.channels?.msteams);
464
+ if (!creds) {
465
+ return null;
466
+ }
467
+ return { kind: "user" as const, id: creds.appId, name: creds.appId };
468
+ },
469
+ listPeers: async ({ cfg, query, limit }) =>
470
+ listDirectoryEntriesFromSources({
471
+ kind: "user",
472
+ sources: [
473
+ cfg.channels?.msteams?.allowFrom ?? [],
474
+ Object.keys(cfg.channels?.msteams?.dms ?? {}),
475
+ ],
476
+ query,
477
+ limit,
478
+ normalizeId: (raw) => {
479
+ const normalized = normalizeMSTeamsMessagingTarget(raw) ?? raw;
480
+ const lowered = normalized.toLowerCase();
481
+ if (lowered.startsWith("user:") || lowered.startsWith("conversation:")) {
482
+ return normalized;
483
+ }
484
+ return `user:${normalized}`;
485
+ },
486
+ }),
487
+ listGroups: async ({ cfg, query, limit }) =>
488
+ listDirectoryEntriesFromSources({
489
+ kind: "group",
490
+ sources: [
491
+ Object.values(cfg.channels?.msteams?.teams ?? {}).flatMap((team) =>
492
+ Object.keys(team.channels ?? {}),
493
+ ),
494
+ ],
495
+ query,
496
+ limit,
497
+ normalizeId: (raw) => `conversation:${raw.replace(/^conversation:/i, "").trim()}`,
498
+ }),
499
+ ...createRuntimeDirectoryLiveAdapter({
500
+ getRuntime: loadMSTeamsChannelRuntime,
501
+ listPeersLive: (runtime) => runtime.listMSTeamsDirectoryPeersLive,
502
+ listGroupsLive: (runtime) => runtime.listMSTeamsDirectoryGroupsLive,
503
+ }),
504
+ }),
505
+ resolver: {
506
+ resolveTargets: async ({ cfg, inputs, kind, runtime }) => {
507
+ const results = inputs.map((input) => ({
508
+ input,
509
+ resolved: false,
510
+ id: undefined as string | undefined,
511
+ name: undefined as string | undefined,
512
+ note: undefined as string | undefined,
513
+ }));
514
+ type ResolveTargetResultEntry = (typeof results)[number];
515
+ type PendingTargetEntry = { input: string; query: string; index: number };
516
+
517
+ const stripPrefix = (value: string) => normalizeMSTeamsUserInput(value);
518
+ const markPendingLookupFailed = (pending: PendingTargetEntry[]) => {
519
+ pending.forEach(({ index }) => {
520
+ const entry = results[index];
521
+ if (entry) {
522
+ entry.note = "lookup failed";
523
+ }
524
+ });
525
+ };
526
+ const resolvePending = async <T>(
527
+ pending: PendingTargetEntry[],
528
+ resolveEntries: (entries: string[]) => Promise<T[]>,
529
+ applyResolvedEntry: (target: ResolveTargetResultEntry, entry: T) => void,
530
+ ) => {
531
+ if (pending.length === 0) {
532
+ return;
533
+ }
534
+ try {
535
+ const resolved = await resolveEntries(pending.map((entry) => entry.query));
536
+ resolved.forEach((entry, idx) => {
537
+ const target = results[pending[idx]?.index ?? -1];
538
+ if (!target) {
539
+ return;
540
+ }
541
+ applyResolvedEntry(target, entry);
542
+ });
543
+ } catch (err) {
544
+ runtime.error?.(`msteams resolve failed: ${String(err)}`);
545
+ markPendingLookupFailed(pending);
546
+ }
547
+ };
548
+
549
+ if (kind === "user") {
550
+ const pending: PendingTargetEntry[] = [];
551
+ results.forEach((entry, index) => {
552
+ const trimmed = entry.input.trim();
553
+ if (!trimmed) {
554
+ entry.note = "empty input";
555
+ return;
556
+ }
557
+ const cleaned = stripPrefix(trimmed);
558
+ if (/^[0-9a-fA-F-]{16,}$/.test(cleaned) || cleaned.includes("@")) {
559
+ entry.resolved = true;
560
+ entry.id = cleaned;
561
+ return;
562
+ }
563
+ pending.push({ input: entry.input, query: cleaned, index });
564
+ });
565
+
566
+ await resolvePending(
567
+ pending,
568
+ (entries) => resolveMSTeamsUserAllowlist({ cfg, entries }),
569
+ (target, entry) => {
570
+ target.resolved = entry.resolved;
571
+ target.id = entry.id;
572
+ target.name = entry.name;
573
+ target.note = entry.note;
574
+ },
575
+ );
576
+
577
+ return results;
578
+ }
579
+
580
+ const pending: PendingTargetEntry[] = [];
581
+ results.forEach((entry, index) => {
582
+ const trimmed = entry.input.trim();
583
+ if (!trimmed) {
584
+ entry.note = "empty input";
585
+ return;
586
+ }
587
+ const conversationId = parseMSTeamsConversationId(trimmed);
588
+ if (conversationId !== null) {
589
+ entry.resolved = Boolean(conversationId);
590
+ entry.id = conversationId || undefined;
591
+ entry.note = conversationId ? "conversation id" : "empty conversation id";
592
+ return;
593
+ }
594
+ const parsed = parseMSTeamsTeamChannelInput(trimmed);
595
+ if (!parsed.team) {
596
+ entry.note = "missing team";
597
+ return;
598
+ }
599
+ const query = parsed.channel ? `${parsed.team}/${parsed.channel}` : parsed.team;
600
+ pending.push({ input: entry.input, query, index });
601
+ });
602
+
603
+ await resolvePending(
604
+ pending,
605
+ (entries) => resolveMSTeamsChannelAllowlist({ cfg, entries }),
606
+ (target, entry) => {
607
+ if (!entry.resolved || !entry.teamId) {
608
+ target.resolved = false;
609
+ target.note = entry.note;
610
+ return;
611
+ }
612
+ target.resolved = true;
613
+ if (entry.channelId) {
614
+ target.id = `${entry.teamId}/${entry.channelId}`;
615
+ target.name =
616
+ entry.channelName && entry.teamName
617
+ ? `${entry.teamName}/${entry.channelName}`
618
+ : (entry.channelName ?? entry.teamName);
619
+ } else {
620
+ target.id = entry.teamId;
621
+ target.name = entry.teamName;
622
+ target.note = "team id";
623
+ }
624
+ if (entry.note) {
625
+ target.note = entry.note;
626
+ }
627
+ },
628
+ );
629
+
630
+ return results;
631
+ },
176
632
  },
177
- hint: "<conversationId|user:ID|conversation:ID>",
178
- },
179
- },
180
- directory: {
181
- self: async () => null,
182
- listPeers: async ({ cfg, query, limit }) => {
183
- const q = query?.trim().toLowerCase() || "";
184
- const ids = new Set<string>();
185
- for (const entry of cfg.channels?.msteams?.allowFrom ?? []) {
186
- const trimmed = String(entry).trim();
187
- if (trimmed && trimmed !== "*") {
188
- ids.add(trimmed);
189
- }
190
- }
191
- for (const userId of Object.keys(cfg.channels?.msteams?.dms ?? {})) {
192
- const trimmed = userId.trim();
193
- if (trimmed) {
194
- ids.add(trimmed);
195
- }
196
- }
197
- return Array.from(ids)
198
- .map((raw) => raw.trim())
199
- .filter(Boolean)
200
- .map((raw) => normalizeMSTeamsMessagingTarget(raw) ?? raw)
201
- .map((raw) => {
202
- const lowered = raw.toLowerCase();
203
- if (lowered.startsWith("user:")) {
204
- return raw;
633
+ actions: {
634
+ describeMessageTool: describeMSTeamsMessageTool,
635
+ handleAction: async (ctx) => {
636
+ const presentation =
637
+ ctx.action === "send"
638
+ ? normalizeMessagePresentation(ctx.params.presentation)
639
+ : undefined;
640
+ if (ctx.action === "send" && presentation) {
641
+ const card = buildMSTeamsPresentationCard({
642
+ presentation,
643
+ text: resolveActionContent(ctx.params),
644
+ });
645
+ return await runWithRequiredActionTarget({
646
+ actionLabel: "Card send",
647
+ toolParams: ctx.params,
648
+ run: async (to) => {
649
+ const { sendAdaptiveCardMSTeams } = await loadMSTeamsChannelRuntime();
650
+ const result = await sendAdaptiveCardMSTeams({
651
+ cfg: ctx.cfg,
652
+ to,
653
+ card,
654
+ });
655
+ return jsonActionResultWithDetails(
656
+ {
657
+ ok: true,
658
+ channel: "msteams",
659
+ messageId: result.messageId,
660
+ conversationId: result.conversationId,
661
+ },
662
+ { ok: true, channel: "msteams", messageId: result.messageId },
663
+ );
664
+ },
665
+ });
205
666
  }
206
- if (lowered.startsWith("conversation:")) {
207
- return raw;
667
+ if (ctx.action === "upload-file") {
668
+ const mediaUrl = resolveActionUploadFilePath(ctx.params);
669
+ if (!mediaUrl) {
670
+ return actionError("Upload-file requires media, filePath, or path.");
671
+ }
672
+ return await runWithRequiredActionTarget({
673
+ actionLabel: "Upload-file",
674
+ toolParams: ctx.params,
675
+ currentChannelId: ctx.toolContext?.currentChannelId,
676
+ run: async (to) => {
677
+ const { sendMessageMSTeams } = await loadMSTeamsChannelRuntime();
678
+ const result = await sendMessageMSTeams({
679
+ cfg: ctx.cfg,
680
+ to,
681
+ text: resolveActionContent(ctx.params),
682
+ mediaUrl,
683
+ filename:
684
+ readOptionalTrimmedString(ctx.params, "filename") ??
685
+ readOptionalTrimmedString(ctx.params, "title"),
686
+ mediaLocalRoots: ctx.mediaLocalRoots,
687
+ mediaReadFile: ctx.mediaReadFile,
688
+ });
689
+ return jsonActionResultWithDetails(
690
+ {
691
+ ok: true,
692
+ channel: "msteams",
693
+ action: "upload-file",
694
+ messageId: result.messageId,
695
+ conversationId: result.conversationId,
696
+ ...(result.pendingUploadId ? { pendingUploadId: result.pendingUploadId } : {}),
697
+ },
698
+ {
699
+ ok: true,
700
+ channel: "msteams",
701
+ messageId: result.messageId,
702
+ ...(result.pendingUploadId ? { pendingUploadId: result.pendingUploadId } : {}),
703
+ },
704
+ );
705
+ },
706
+ });
208
707
  }
209
- return `user:${raw}`;
210
- })
211
- .filter((id) => (q ? id.toLowerCase().includes(q) : true))
212
- .slice(0, limit && limit > 0 ? limit : undefined)
213
- .map((id) => ({ kind: "user", id }) as const);
214
- },
215
- listGroups: async ({ cfg, query, limit }) => {
216
- const q = query?.trim().toLowerCase() || "";
217
- const ids = new Set<string>();
218
- for (const team of Object.values(cfg.channels?.msteams?.teams ?? {})) {
219
- for (const channelId of Object.keys(team.channels ?? {})) {
220
- const trimmed = channelId.trim();
221
- if (trimmed && trimmed !== "*") {
222
- ids.add(trimmed);
708
+ if (ctx.action === "edit") {
709
+ const content = resolveActionContent(ctx.params);
710
+ if (!content) {
711
+ return actionError("Edit requires content.");
712
+ }
713
+ return await runWithRequiredActionMessageTarget({
714
+ actionLabel: "Edit",
715
+ toolParams: ctx.params,
716
+ currentChannelId: ctx.toolContext?.currentChannelId,
717
+ run: async (target) => {
718
+ const { editMessageMSTeams } = await loadMSTeamsChannelRuntime();
719
+ const result = await editMessageMSTeams({
720
+ cfg: ctx.cfg,
721
+ to: target.to,
722
+ activityId: target.messageId,
723
+ text: content,
724
+ });
725
+ return jsonMSTeamsConversationResult(result.conversationId);
726
+ },
727
+ });
223
728
  }
224
- }
225
- }
226
- return Array.from(ids)
227
- .map((raw) => raw.trim())
228
- .filter(Boolean)
229
- .map((raw) => raw.replace(/^conversation:/i, "").trim())
230
- .map((id) => `conversation:${id}`)
231
- .filter((id) => (q ? id.toLowerCase().includes(q) : true))
232
- .slice(0, limit && limit > 0 ? limit : undefined)
233
- .map((id) => ({ kind: "group", id }) as const);
234
- },
235
- listPeersLive: async ({ cfg, query, limit }) =>
236
- listMSTeamsDirectoryPeersLive({ cfg, query, limit }),
237
- listGroupsLive: async ({ cfg, query, limit }) =>
238
- listMSTeamsDirectoryGroupsLive({ cfg, query, limit }),
239
- },
240
- resolver: {
241
- resolveTargets: async ({ cfg, inputs, kind, runtime }) => {
242
- const results = inputs.map((input) => ({
243
- input,
244
- resolved: false,
245
- id: undefined as string | undefined,
246
- name: undefined as string | undefined,
247
- note: undefined as string | undefined,
248
- }));
249
- type ResolveTargetResultEntry = (typeof results)[number];
250
- type PendingTargetEntry = { input: string; query: string; index: number };
251
-
252
- const stripPrefix = (value: string) => normalizeMSTeamsUserInput(value);
253
- const markPendingLookupFailed = (pending: PendingTargetEntry[]) => {
254
- pending.forEach(({ index }) => {
255
- const entry = results[index];
256
- if (entry) {
257
- entry.note = "lookup failed";
729
+
730
+ if (ctx.action === "delete") {
731
+ return await runWithRequiredActionMessageTarget({
732
+ actionLabel: "Delete",
733
+ toolParams: ctx.params,
734
+ currentChannelId: ctx.toolContext?.currentChannelId,
735
+ run: async (target) => {
736
+ const { deleteMessageMSTeams } = await loadMSTeamsChannelRuntime();
737
+ const result = await deleteMessageMSTeams({
738
+ cfg: ctx.cfg,
739
+ to: target.to,
740
+ activityId: target.messageId,
741
+ });
742
+ return jsonMSTeamsConversationResult(result.conversationId);
743
+ },
744
+ });
258
745
  }
259
- });
260
- };
261
- const resolvePending = async <T>(
262
- pending: PendingTargetEntry[],
263
- resolveEntries: (entries: string[]) => Promise<T[]>,
264
- applyResolvedEntry: (target: ResolveTargetResultEntry, entry: T) => void,
265
- ) => {
266
- if (pending.length === 0) {
267
- return;
268
- }
269
- try {
270
- const resolved = await resolveEntries(pending.map((entry) => entry.query));
271
- resolved.forEach((entry, idx) => {
272
- const target = results[pending[idx]?.index ?? -1];
273
- if (!target) {
274
- return;
746
+
747
+ if (ctx.action === "read") {
748
+ return await runWithRequiredActionMessageTarget({
749
+ actionLabel: "Read",
750
+ toolParams: ctx.params,
751
+ currentChannelId: ctx.toolContext?.currentChannelId,
752
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
753
+ graphOnly: true,
754
+ run: async (target) => {
755
+ const { getMessageMSTeams } = await loadMSTeamsChannelRuntime();
756
+ const message = await getMessageMSTeams({
757
+ cfg: ctx.cfg,
758
+ to: target.to,
759
+ messageId: target.messageId,
760
+ });
761
+ return jsonMSTeamsOkActionResult("read", { message });
762
+ },
763
+ });
764
+ }
765
+
766
+ if (ctx.action === "pin") {
767
+ return await runWithRequiredActionMessageTarget({
768
+ actionLabel: "Pin",
769
+ toolParams: ctx.params,
770
+ currentChannelId: ctx.toolContext?.currentChannelId,
771
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
772
+ graphOnly: true,
773
+ run: async (target) => {
774
+ const { pinMessageMSTeams } = await loadMSTeamsChannelRuntime();
775
+ const result = await pinMessageMSTeams({
776
+ cfg: ctx.cfg,
777
+ to: target.to,
778
+ messageId: target.messageId,
779
+ });
780
+ return jsonMSTeamsActionResult("pin", result);
781
+ },
782
+ });
783
+ }
784
+
785
+ if (ctx.action === "unpin") {
786
+ return await runWithRequiredActionPinnedMessageTarget({
787
+ actionLabel: "Unpin",
788
+ toolParams: ctx.params,
789
+ currentChannelId: ctx.toolContext?.currentChannelId,
790
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
791
+ graphOnly: true,
792
+ run: async (target) => {
793
+ const { unpinMessageMSTeams } = await loadMSTeamsChannelRuntime();
794
+ const result = await unpinMessageMSTeams({
795
+ cfg: ctx.cfg,
796
+ to: target.to,
797
+ pinnedMessageId: target.pinnedMessageId,
798
+ });
799
+ return jsonMSTeamsActionResult("unpin", result);
800
+ },
801
+ });
802
+ }
803
+
804
+ if (ctx.action === "list-pins") {
805
+ return await runWithRequiredActionTarget({
806
+ actionLabel: "List-pins",
807
+ toolParams: ctx.params,
808
+ currentChannelId: ctx.toolContext?.currentChannelId,
809
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
810
+ graphOnly: true,
811
+ run: async (to) => {
812
+ const { listPinsMSTeams } = await loadMSTeamsChannelRuntime();
813
+ const result = await listPinsMSTeams({ cfg: ctx.cfg, to });
814
+ return jsonMSTeamsOkActionResult("list-pins", result);
815
+ },
816
+ });
817
+ }
818
+
819
+ if (ctx.action === "react") {
820
+ return await runWithRequiredActionMessageTarget({
821
+ actionLabel: "React",
822
+ toolParams: ctx.params,
823
+ currentChannelId: ctx.toolContext?.currentChannelId,
824
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
825
+ graphOnly: true,
826
+ run: async (target) => {
827
+ const emoji = typeof ctx.params.emoji === "string" ? ctx.params.emoji.trim() : "";
828
+ const remove = typeof ctx.params.remove === "boolean" ? ctx.params.remove : false;
829
+ if (!emoji) {
830
+ return {
831
+ isError: true,
832
+ content: [
833
+ {
834
+ type: "text" as const,
835
+ text: `React requires an emoji (reaction type). Valid types: ${MSTEAMS_REACTION_TYPES.join(", ")}.`,
836
+ },
837
+ ],
838
+ details: {
839
+ error: "React requires an emoji (reaction type).",
840
+ validTypes: [...MSTEAMS_REACTION_TYPES],
841
+ },
842
+ };
843
+ }
844
+ if (remove) {
845
+ const { unreactMessageMSTeams } = await loadMSTeamsChannelRuntime();
846
+ const result = await unreactMessageMSTeams({
847
+ cfg: ctx.cfg,
848
+ to: target.to,
849
+ messageId: target.messageId,
850
+ reactionType: emoji,
851
+ });
852
+ return jsonMSTeamsActionResult("react", {
853
+ removed: true,
854
+ reactionType: emoji,
855
+ ...result,
856
+ });
857
+ }
858
+ const { reactMessageMSTeams } = await loadMSTeamsChannelRuntime();
859
+ const result = await reactMessageMSTeams({
860
+ cfg: ctx.cfg,
861
+ to: target.to,
862
+ messageId: target.messageId,
863
+ reactionType: emoji,
864
+ });
865
+ return jsonMSTeamsActionResult("react", {
866
+ reactionType: emoji,
867
+ ...result,
868
+ });
869
+ },
870
+ });
871
+ }
872
+
873
+ if (ctx.action === "reactions") {
874
+ return await runWithRequiredActionMessageTarget({
875
+ actionLabel: "Reactions",
876
+ toolParams: ctx.params,
877
+ currentChannelId: ctx.toolContext?.currentChannelId,
878
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
879
+ graphOnly: true,
880
+ run: async (target) => {
881
+ const { listReactionsMSTeams } = await loadMSTeamsChannelRuntime();
882
+ const result = await listReactionsMSTeams({
883
+ cfg: ctx.cfg,
884
+ to: target.to,
885
+ messageId: target.messageId,
886
+ });
887
+ return jsonMSTeamsOkActionResult("reactions", result);
888
+ },
889
+ });
890
+ }
891
+
892
+ if (ctx.action === "search") {
893
+ return await runWithRequiredActionTarget({
894
+ actionLabel: "Search",
895
+ toolParams: ctx.params,
896
+ currentChannelId: ctx.toolContext?.currentChannelId,
897
+ currentGraphChannelId: ctx.toolContext?.currentGraphChannelId,
898
+ graphOnly: true,
899
+ run: async (to) => {
900
+ const query = resolveActionQuery(ctx.params);
901
+ if (!query) {
902
+ return actionError("Search requires a target (to) and query.");
903
+ }
904
+ const limit = typeof ctx.params.limit === "number" ? ctx.params.limit : undefined;
905
+ const from =
906
+ typeof ctx.params.from === "string" ? ctx.params.from.trim() : undefined;
907
+ const { searchMessagesMSTeams } = await loadMSTeamsChannelRuntime();
908
+ const result = await searchMessagesMSTeams({
909
+ cfg: ctx.cfg,
910
+ to,
911
+ query,
912
+ from: from || undefined,
913
+ limit,
914
+ });
915
+ return jsonMSTeamsOkActionResult("search", result);
916
+ },
917
+ });
918
+ }
919
+
920
+ if (ctx.action === "member-info") {
921
+ const userId = normalizeOptionalString(ctx.params.userId) ?? "";
922
+ if (!userId) {
923
+ return actionError("member-info requires a userId.");
275
924
  }
276
- applyResolvedEntry(target, entry);
277
- });
278
- } catch (err) {
279
- runtime.error?.(`msteams resolve failed: ${String(err)}`);
280
- markPendingLookupFailed(pending);
281
- }
282
- };
283
-
284
- if (kind === "user") {
285
- const pending: PendingTargetEntry[] = [];
286
- results.forEach((entry, index) => {
287
- const trimmed = entry.input.trim();
288
- if (!trimmed) {
289
- entry.note = "empty input";
290
- return;
925
+ const { getMemberInfoMSTeams } = await loadMSTeamsChannelRuntime();
926
+ const result = await getMemberInfoMSTeams({ cfg: ctx.cfg, userId });
927
+ return jsonMSTeamsOkActionResult("member-info", result);
291
928
  }
292
- const cleaned = stripPrefix(trimmed);
293
- if (/^[0-9a-fA-F-]{16,}$/.test(cleaned) || cleaned.includes("@")) {
294
- entry.resolved = true;
295
- entry.id = cleaned;
296
- return;
929
+
930
+ if (ctx.action === "channel-list") {
931
+ const teamId = normalizeOptionalString(ctx.params.teamId) ?? "";
932
+ if (!teamId) {
933
+ return actionError("channel-list requires a teamId.");
934
+ }
935
+ const { listChannelsMSTeams } = await loadMSTeamsChannelRuntime();
936
+ const result = await listChannelsMSTeams({ cfg: ctx.cfg, teamId });
937
+ return jsonMSTeamsOkActionResult("channel-list", result);
297
938
  }
298
- pending.push({ input: entry.input, query: cleaned, index });
299
- });
300
-
301
- await resolvePending(
302
- pending,
303
- (entries) => resolveMSTeamsUserAllowlist({ cfg, entries }),
304
- (target, entry) => {
305
- target.resolved = entry.resolved;
306
- target.id = entry.id;
307
- target.name = entry.name;
308
- target.note = entry.note;
309
- },
310
- );
311
939
 
312
- return results;
313
- }
940
+ if (ctx.action === "channel-info") {
941
+ const teamId = normalizeOptionalString(ctx.params.teamId) ?? "";
942
+ const channelId = normalizeOptionalString(ctx.params.channelId) ?? "";
943
+ if (!teamId || !channelId) {
944
+ return actionError("channel-info requires teamId and channelId.");
945
+ }
946
+ const { getChannelInfoMSTeams } = await loadMSTeamsChannelRuntime();
947
+ const result = await getChannelInfoMSTeams({
948
+ cfg: ctx.cfg,
949
+ teamId,
950
+ channelId,
951
+ });
952
+ return jsonMSTeamsOkActionResult("channel-info", {
953
+ channelInfo: result.channel,
954
+ });
955
+ }
314
956
 
315
- const pending: PendingTargetEntry[] = [];
316
- results.forEach((entry, index) => {
317
- const trimmed = entry.input.trim();
318
- if (!trimmed) {
319
- entry.note = "empty input";
320
- return;
321
- }
322
- const conversationId = parseMSTeamsConversationId(trimmed);
323
- if (conversationId !== null) {
324
- entry.resolved = Boolean(conversationId);
325
- entry.id = conversationId || undefined;
326
- entry.note = conversationId ? "conversation id" : "empty conversation id";
327
- return;
328
- }
329
- const parsed = parseMSTeamsTeamChannelInput(trimmed);
330
- if (!parsed.team) {
331
- entry.note = "missing team";
332
- return;
333
- }
334
- const query = parsed.channel ? `${parsed.team}/${parsed.channel}` : parsed.team;
335
- pending.push({ input: entry.input, query, index });
336
- });
337
-
338
- await resolvePending(
339
- pending,
340
- (entries) => resolveMSTeamsChannelAllowlist({ cfg, entries }),
341
- (target, entry) => {
342
- if (!entry.resolved || !entry.teamId) {
343
- target.resolved = false;
344
- target.note = entry.note;
345
- return;
957
+ if (ctx.action === "addParticipant") {
958
+ const userId = typeof ctx.params.userId === "string" ? ctx.params.userId.trim() : "";
959
+ if (!userId) {
960
+ return actionError("addParticipant requires a userId.");
961
+ }
962
+ return await runWithRequiredActionTarget({
963
+ actionLabel: "addParticipant",
964
+ toolParams: ctx.params,
965
+ currentChannelId: ctx.toolContext?.currentChannelId,
966
+ run: async (to) => {
967
+ const role = readOptionalTrimmedString(ctx.params, "role");
968
+ const { addParticipantMSTeams } = await loadMSTeamsChannelRuntime();
969
+ const result = await addParticipantMSTeams({
970
+ cfg: ctx.cfg,
971
+ to,
972
+ userId,
973
+ role,
974
+ });
975
+ return jsonMSTeamsOkActionResult("addParticipant", result);
976
+ },
977
+ });
346
978
  }
347
- target.resolved = true;
348
- if (entry.channelId) {
349
- target.id = `${entry.teamId}/${entry.channelId}`;
350
- target.name =
351
- entry.channelName && entry.teamName
352
- ? `${entry.teamName}/${entry.channelName}`
353
- : (entry.channelName ?? entry.teamName);
354
- } else {
355
- target.id = entry.teamId;
356
- target.name = entry.teamName;
357
- target.note = "team id";
979
+
980
+ if (ctx.action === "removeParticipant") {
981
+ const userId = typeof ctx.params.userId === "string" ? ctx.params.userId.trim() : "";
982
+ if (!userId) {
983
+ return actionError("removeParticipant requires a userId.");
984
+ }
985
+ return await runWithRequiredActionTarget({
986
+ actionLabel: "removeParticipant",
987
+ toolParams: ctx.params,
988
+ currentChannelId: ctx.toolContext?.currentChannelId,
989
+ run: async (to) => {
990
+ const { removeParticipantMSTeams } = await loadMSTeamsChannelRuntime();
991
+ const result = await removeParticipantMSTeams({
992
+ cfg: ctx.cfg,
993
+ to,
994
+ userId,
995
+ });
996
+ return jsonMSTeamsOkActionResult("removeParticipant", result);
997
+ },
998
+ });
358
999
  }
359
- if (entry.note) {
360
- target.note = entry.note;
1000
+
1001
+ if (ctx.action === "renameGroup") {
1002
+ const name = typeof ctx.params.name === "string" ? ctx.params.name.trim() : "";
1003
+ if (!name) {
1004
+ return actionError("renameGroup requires a name.");
1005
+ }
1006
+ return await runWithRequiredActionTarget({
1007
+ actionLabel: "renameGroup",
1008
+ toolParams: ctx.params,
1009
+ currentChannelId: ctx.toolContext?.currentChannelId,
1010
+ run: async (to) => {
1011
+ const { renameGroupMSTeams } = await loadMSTeamsChannelRuntime();
1012
+ const result = await renameGroupMSTeams({
1013
+ cfg: ctx.cfg,
1014
+ to,
1015
+ name,
1016
+ });
1017
+ return jsonMSTeamsOkActionResult("renameGroup", result);
1018
+ },
1019
+ });
361
1020
  }
362
- },
363
- );
364
1021
 
365
- return results;
1022
+ // Return null to fall through to default handler
1023
+ return null as never;
1024
+ },
1025
+ },
1026
+ status: createComputedAccountStatusAdapter<ResolvedMSTeamsAccount, ProbeMSTeamsResult>({
1027
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID, { port: null }),
1028
+ buildChannelSummary: ({ snapshot }) =>
1029
+ buildProbeChannelStatusSummary(snapshot, {
1030
+ port: snapshot.port ?? null,
1031
+ }),
1032
+ probeAccount: async ({ cfg }) =>
1033
+ await (await loadMSTeamsChannelRuntime()).probeMSTeams(cfg.channels?.msteams),
1034
+ formatCapabilitiesProbe: ({ probe }) => {
1035
+ const teamsProbe = probe;
1036
+ const lines: Array<{ text: string; tone?: "error" }> = [];
1037
+ const appId = typeof teamsProbe?.appId === "string" ? teamsProbe.appId.trim() : "";
1038
+ if (appId) {
1039
+ lines.push({ text: `App: ${appId}` });
1040
+ }
1041
+ const graph = teamsProbe?.graph;
1042
+ if (graph) {
1043
+ const roles = Array.isArray(graph.roles)
1044
+ ? graph.roles.map((role) => role.trim()).filter(Boolean)
1045
+ : [];
1046
+ const scopes = Array.isArray(graph.scopes)
1047
+ ? graph.scopes.map((scope) => scope.trim()).filter(Boolean)
1048
+ : [];
1049
+ const formatPermission = (permission: string) => {
1050
+ const hint = TEAMS_GRAPH_PERMISSION_HINTS[permission];
1051
+ return hint ? `${permission} (${hint})` : permission;
1052
+ };
1053
+ if (!graph.ok) {
1054
+ lines.push({ text: `Graph: ${graph.error ?? "failed"}`, tone: "error" });
1055
+ } else if (roles.length > 0 || scopes.length > 0) {
1056
+ if (roles.length > 0) {
1057
+ lines.push({ text: `Graph roles: ${roles.map(formatPermission).join(", ")}` });
1058
+ }
1059
+ if (scopes.length > 0) {
1060
+ lines.push({ text: `Graph scopes: ${scopes.map(formatPermission).join(", ")}` });
1061
+ }
1062
+ } else if (graph.ok) {
1063
+ lines.push({ text: "Graph: ok" });
1064
+ }
1065
+ }
1066
+ return lines;
1067
+ },
1068
+ resolveAccountSnapshot: ({ account, runtime }) => ({
1069
+ accountId: account.accountId,
1070
+ enabled: account.enabled,
1071
+ configured: account.configured,
1072
+ extra: {
1073
+ port: runtime?.port ?? null,
1074
+ },
1075
+ }),
1076
+ }),
1077
+ gateway: {
1078
+ startAccount: async (ctx) => {
1079
+ const { monitorMSTeamsProvider } = await import("./index.js");
1080
+ const port = ctx.cfg.channels?.msteams?.webhook?.port ?? 3978;
1081
+ ctx.setStatus({ accountId: ctx.accountId, port });
1082
+ ctx.log?.info(`starting provider (port ${port})`);
1083
+ return monitorMSTeamsProvider({
1084
+ cfg: ctx.cfg,
1085
+ runtime: ctx.runtime,
1086
+ abortSignal: ctx.abortSignal,
1087
+ });
1088
+ },
1089
+ },
366
1090
  },
367
- },
368
- actions: {
369
- listActions: ({ cfg }) => {
370
- const enabled =
371
- cfg.channels?.msteams?.enabled !== false &&
372
- Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams));
373
- if (!enabled) {
374
- return [];
375
- }
376
- return ["poll"] satisfies ChannelMessageActionName[];
1091
+ security: {
1092
+ collectWarnings: projectConfigWarningCollector<{ cfg: OpenClawConfig }>(
1093
+ collectMSTeamsSecurityWarnings,
1094
+ ),
377
1095
  },
378
- supportsCards: ({ cfg }) => {
379
- return (
380
- cfg.channels?.msteams?.enabled !== false &&
381
- Boolean(resolveMSTeamsCredentials(cfg.channels?.msteams))
382
- );
1096
+ pairing: {
1097
+ text: {
1098
+ idLabel: "msteamsUserId",
1099
+ message: PAIRING_APPROVED_MESSAGE,
1100
+ normalizeAllowEntry: createPairingPrefixStripper(/^(msteams|user):/i),
1101
+ notify: async ({ cfg, id, message }) => {
1102
+ const { sendMessageMSTeams } = await loadMSTeamsChannelRuntime();
1103
+ await sendMessageMSTeams({
1104
+ cfg,
1105
+ to: id,
1106
+ text: message,
1107
+ });
1108
+ },
1109
+ },
383
1110
  },
384
- handleAction: async (ctx) => {
385
- // Handle send action with card parameter
386
- if (ctx.action === "send" && ctx.params.card) {
387
- const card = ctx.params.card as Record<string, unknown>;
388
- const to =
389
- typeof ctx.params.to === "string"
390
- ? ctx.params.to.trim()
391
- : typeof ctx.params.target === "string"
392
- ? ctx.params.target.trim()
393
- : "";
394
- if (!to) {
395
- return {
396
- isError: true,
397
- content: [{ type: "text" as const, text: "Card send requires a target (to)." }],
398
- details: { error: "Card send requires a target (to)." },
399
- };
400
- }
401
- const result = await sendAdaptiveCardMSTeams({
402
- cfg: ctx.cfg,
403
- to,
404
- card,
405
- });
1111
+ threading: {
1112
+ buildToolContext: ({ context, hasRepliedRef }) => {
1113
+ const nativeChannelId = context.NativeChannelId?.trim();
1114
+ const hasChannelRoute = Boolean(nativeChannelId && nativeChannelId.includes("/"));
406
1115
  return {
407
- content: [
408
- {
409
- type: "text" as const,
410
- text: JSON.stringify({
411
- ok: true,
412
- channel: "msteams",
413
- messageId: result.messageId,
414
- conversationId: result.conversationId,
415
- }),
416
- },
417
- ],
418
- details: { ok: true, channel: "msteams", messageId: result.messageId },
1116
+ currentChannelId: normalizeOptionalString(context.To),
1117
+ currentGraphChannelId: hasChannelRoute ? nativeChannelId : undefined,
1118
+ currentThreadTs: context.ReplyToId,
1119
+ hasRepliedRef,
419
1120
  };
420
- }
421
- // Return null to fall through to default handler
422
- return null as never;
1121
+ },
423
1122
  },
424
- },
425
- outbound: msteamsOutbound,
426
- status: {
427
- defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID, { port: null }),
428
- buildChannelSummary: ({ snapshot }) =>
429
- buildProbeChannelStatusSummary(snapshot, {
430
- port: snapshot.port ?? null,
1123
+ outbound: {
1124
+ deliveryMode: "direct",
1125
+ chunker: chunkTextForOutbound,
1126
+ chunkerMode: "markdown",
1127
+ textChunkLimit: 4000,
1128
+ pollMaxOptions: 12,
1129
+ ...createRuntimeOutboundDelegates({
1130
+ getRuntime: loadMSTeamsChannelRuntime,
1131
+ sendText: { resolve: (runtime) => runtime.msteamsOutbound.sendText },
1132
+ sendMedia: { resolve: (runtime) => runtime.msteamsOutbound.sendMedia },
1133
+ sendPoll: { resolve: (runtime) => runtime.msteamsOutbound.sendPoll },
431
1134
  }),
432
- probeAccount: async ({ cfg }) => await probeMSTeams(cfg.channels?.msteams),
433
- buildAccountSnapshot: ({ account, runtime, probe }) => ({
434
- accountId: account.accountId,
435
- enabled: account.enabled,
436
- configured: account.configured,
437
- ...buildRuntimeAccountStatusSnapshot({ runtime, probe }),
438
- port: runtime?.port ?? null,
439
- }),
440
- },
441
- gateway: {
442
- startAccount: async (ctx) => {
443
- const { monitorMSTeamsProvider } = await import("./index.js");
444
- const port = ctx.cfg.channels?.msteams?.webhook?.port ?? 3978;
445
- ctx.setStatus({ accountId: ctx.accountId, port });
446
- ctx.log?.info(`starting provider (port ${port})`);
447
- return monitorMSTeamsProvider({
448
- cfg: ctx.cfg,
449
- runtime: ctx.runtime,
450
- abortSignal: ctx.abortSignal,
451
- });
452
1135
  },
453
- },
454
- };
1136
+ });