@openclaw/msteams 2026.1.29

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 (61) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/index.ts +18 -0
  3. package/openclaw.plugin.json +11 -0
  4. package/package.json +36 -0
  5. package/src/attachments/download.ts +206 -0
  6. package/src/attachments/graph.ts +319 -0
  7. package/src/attachments/html.ts +76 -0
  8. package/src/attachments/payload.ts +22 -0
  9. package/src/attachments/shared.ts +235 -0
  10. package/src/attachments/types.ts +37 -0
  11. package/src/attachments.test.ts +424 -0
  12. package/src/attachments.ts +18 -0
  13. package/src/channel.directory.test.ts +46 -0
  14. package/src/channel.ts +436 -0
  15. package/src/conversation-store-fs.test.ts +89 -0
  16. package/src/conversation-store-fs.ts +155 -0
  17. package/src/conversation-store-memory.ts +45 -0
  18. package/src/conversation-store.ts +41 -0
  19. package/src/directory-live.ts +179 -0
  20. package/src/errors.test.ts +46 -0
  21. package/src/errors.ts +158 -0
  22. package/src/file-consent-helpers.test.ts +234 -0
  23. package/src/file-consent-helpers.ts +73 -0
  24. package/src/file-consent.ts +122 -0
  25. package/src/graph-chat.ts +52 -0
  26. package/src/graph-upload.ts +445 -0
  27. package/src/inbound.test.ts +67 -0
  28. package/src/inbound.ts +38 -0
  29. package/src/index.ts +4 -0
  30. package/src/media-helpers.test.ts +186 -0
  31. package/src/media-helpers.ts +77 -0
  32. package/src/messenger.test.ts +245 -0
  33. package/src/messenger.ts +460 -0
  34. package/src/monitor-handler/inbound-media.ts +123 -0
  35. package/src/monitor-handler/message-handler.ts +629 -0
  36. package/src/monitor-handler.ts +166 -0
  37. package/src/monitor-types.ts +5 -0
  38. package/src/monitor.ts +290 -0
  39. package/src/onboarding.ts +432 -0
  40. package/src/outbound.ts +47 -0
  41. package/src/pending-uploads.ts +87 -0
  42. package/src/policy.test.ts +210 -0
  43. package/src/policy.ts +247 -0
  44. package/src/polls-store-memory.ts +30 -0
  45. package/src/polls-store.test.ts +40 -0
  46. package/src/polls.test.ts +73 -0
  47. package/src/polls.ts +300 -0
  48. package/src/probe.test.ts +57 -0
  49. package/src/probe.ts +99 -0
  50. package/src/reply-dispatcher.ts +128 -0
  51. package/src/resolve-allowlist.ts +277 -0
  52. package/src/runtime.ts +14 -0
  53. package/src/sdk-types.ts +19 -0
  54. package/src/sdk.ts +33 -0
  55. package/src/send-context.ts +156 -0
  56. package/src/send.ts +489 -0
  57. package/src/sent-message-cache.test.ts +16 -0
  58. package/src/sent-message-cache.ts +41 -0
  59. package/src/storage.ts +22 -0
  60. package/src/store-fs.ts +80 -0
  61. package/src/token.ts +19 -0
@@ -0,0 +1,166 @@
1
+ import type { OpenClawConfig, RuntimeEnv } from "openclaw/plugin-sdk";
2
+ import type { MSTeamsConversationStore } from "./conversation-store.js";
3
+ import {
4
+ buildFileInfoCard,
5
+ parseFileConsentInvoke,
6
+ uploadToConsentUrl,
7
+ } from "./file-consent.js";
8
+ import type { MSTeamsAdapter } from "./messenger.js";
9
+ import { createMSTeamsMessageHandler } from "./monitor-handler/message-handler.js";
10
+ import type { MSTeamsMonitorLogger } from "./monitor-types.js";
11
+ import { getPendingUpload, removePendingUpload } from "./pending-uploads.js";
12
+ import type { MSTeamsPollStore } from "./polls.js";
13
+ import type { MSTeamsTurnContext } from "./sdk-types.js";
14
+
15
+ export type MSTeamsAccessTokenProvider = {
16
+ getAccessToken: (scope: string) => Promise<string>;
17
+ };
18
+
19
+ export type MSTeamsActivityHandler = {
20
+ onMessage: (
21
+ handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
22
+ ) => MSTeamsActivityHandler;
23
+ onMembersAdded: (
24
+ handler: (context: unknown, next: () => Promise<void>) => Promise<void>,
25
+ ) => MSTeamsActivityHandler;
26
+ run?: (context: unknown) => Promise<void>;
27
+ };
28
+
29
+ export type MSTeamsMessageHandlerDeps = {
30
+ cfg: OpenClawConfig;
31
+ runtime: RuntimeEnv;
32
+ appId: string;
33
+ adapter: MSTeamsAdapter;
34
+ tokenProvider: MSTeamsAccessTokenProvider;
35
+ textLimit: number;
36
+ mediaMaxBytes: number;
37
+ conversationStore: MSTeamsConversationStore;
38
+ pollStore: MSTeamsPollStore;
39
+ log: MSTeamsMonitorLogger;
40
+ };
41
+
42
+ /**
43
+ * Handle fileConsent/invoke activities for large file uploads.
44
+ */
45
+ async function handleFileConsentInvoke(
46
+ context: MSTeamsTurnContext,
47
+ log: MSTeamsMonitorLogger,
48
+ ): Promise<boolean> {
49
+ const activity = context.activity;
50
+ if (activity.type !== "invoke" || activity.name !== "fileConsent/invoke") {
51
+ return false;
52
+ }
53
+
54
+ const consentResponse = parseFileConsentInvoke(activity);
55
+ if (!consentResponse) {
56
+ log.debug("invalid file consent invoke", { value: activity.value });
57
+ return false;
58
+ }
59
+
60
+ const uploadId =
61
+ typeof consentResponse.context?.uploadId === "string"
62
+ ? consentResponse.context.uploadId
63
+ : undefined;
64
+
65
+ if (consentResponse.action === "accept" && consentResponse.uploadInfo) {
66
+ const pendingFile = getPendingUpload(uploadId);
67
+ if (pendingFile) {
68
+ log.debug("user accepted file consent, uploading", {
69
+ uploadId,
70
+ filename: pendingFile.filename,
71
+ size: pendingFile.buffer.length,
72
+ });
73
+
74
+ try {
75
+ // Upload file to the provided URL
76
+ await uploadToConsentUrl({
77
+ url: consentResponse.uploadInfo.uploadUrl,
78
+ buffer: pendingFile.buffer,
79
+ contentType: pendingFile.contentType,
80
+ });
81
+
82
+ // Send confirmation card
83
+ const fileInfoCard = buildFileInfoCard({
84
+ filename: consentResponse.uploadInfo.name,
85
+ contentUrl: consentResponse.uploadInfo.contentUrl,
86
+ uniqueId: consentResponse.uploadInfo.uniqueId,
87
+ fileType: consentResponse.uploadInfo.fileType,
88
+ });
89
+
90
+ await context.sendActivity({
91
+ type: "message",
92
+ attachments: [fileInfoCard],
93
+ });
94
+
95
+ log.info("file upload complete", {
96
+ uploadId,
97
+ filename: consentResponse.uploadInfo.name,
98
+ uniqueId: consentResponse.uploadInfo.uniqueId,
99
+ });
100
+ } catch (err) {
101
+ log.debug("file upload failed", { uploadId, error: String(err) });
102
+ await context.sendActivity(`File upload failed: ${String(err)}`);
103
+ } finally {
104
+ removePendingUpload(uploadId);
105
+ }
106
+ } else {
107
+ log.debug("pending file not found for consent", { uploadId });
108
+ await context.sendActivity(
109
+ "The file upload request has expired. Please try sending the file again.",
110
+ );
111
+ }
112
+ } else {
113
+ // User declined
114
+ log.debug("user declined file consent", { uploadId });
115
+ removePendingUpload(uploadId);
116
+ }
117
+
118
+ return true;
119
+ }
120
+
121
+ export function registerMSTeamsHandlers<T extends MSTeamsActivityHandler>(
122
+ handler: T,
123
+ deps: MSTeamsMessageHandlerDeps,
124
+ ): T {
125
+ const handleTeamsMessage = createMSTeamsMessageHandler(deps);
126
+
127
+ // Wrap the original run method to intercept invokes
128
+ const originalRun = handler.run;
129
+ if (originalRun) {
130
+ handler.run = async (context: unknown) => {
131
+ const ctx = context as MSTeamsTurnContext;
132
+ // Handle file consent invokes before passing to normal flow
133
+ if (ctx.activity?.type === "invoke" && ctx.activity?.name === "fileConsent/invoke") {
134
+ const handled = await handleFileConsentInvoke(ctx, deps.log);
135
+ if (handled) {
136
+ // Send invoke response for file consent
137
+ await ctx.sendActivity({ type: "invokeResponse", value: { status: 200 } });
138
+ return;
139
+ }
140
+ }
141
+ return originalRun.call(handler, context);
142
+ };
143
+ }
144
+
145
+ handler.onMessage(async (context, next) => {
146
+ try {
147
+ await handleTeamsMessage(context as MSTeamsTurnContext);
148
+ } catch (err) {
149
+ deps.runtime.error?.(`msteams handler failed: ${String(err)}`);
150
+ }
151
+ await next();
152
+ });
153
+
154
+ handler.onMembersAdded(async (context, next) => {
155
+ const membersAdded = (context as MSTeamsTurnContext).activity?.membersAdded ?? [];
156
+ for (const member of membersAdded) {
157
+ if (member.id !== (context as MSTeamsTurnContext).activity?.recipient?.id) {
158
+ deps.log.debug("member added", { member: member.id });
159
+ // Don't send welcome message - let the user initiate conversation.
160
+ }
161
+ }
162
+ await next();
163
+ });
164
+
165
+ return handler;
166
+ }
@@ -0,0 +1,5 @@
1
+ export type MSTeamsMonitorLogger = {
2
+ debug: (message: string, meta?: Record<string, unknown>) => void;
3
+ info: (message: string, meta?: Record<string, unknown>) => void;
4
+ error: (message: string, meta?: Record<string, unknown>) => void;
5
+ };
package/src/monitor.ts ADDED
@@ -0,0 +1,290 @@
1
+ import type { Request, Response } from "express";
2
+ import {
3
+ mergeAllowlist,
4
+ summarizeMapping,
5
+ type OpenClawConfig,
6
+ type RuntimeEnv,
7
+ } from "openclaw/plugin-sdk";
8
+ import type { MSTeamsConversationStore } from "./conversation-store.js";
9
+ import { createMSTeamsConversationStoreFs } from "./conversation-store-fs.js";
10
+ import { formatUnknownError } from "./errors.js";
11
+ import type { MSTeamsAdapter } from "./messenger.js";
12
+ import { registerMSTeamsHandlers } from "./monitor-handler.js";
13
+ import { createMSTeamsPollStoreFs, type MSTeamsPollStore } from "./polls.js";
14
+ import {
15
+ resolveMSTeamsChannelAllowlist,
16
+ resolveMSTeamsUserAllowlist,
17
+ } from "./resolve-allowlist.js";
18
+ import { createMSTeamsAdapter, loadMSTeamsSdkWithAuth } from "./sdk.js";
19
+ import { resolveMSTeamsCredentials } from "./token.js";
20
+ import { getMSTeamsRuntime } from "./runtime.js";
21
+
22
+ export type MonitorMSTeamsOpts = {
23
+ cfg: OpenClawConfig;
24
+ runtime?: RuntimeEnv;
25
+ abortSignal?: AbortSignal;
26
+ conversationStore?: MSTeamsConversationStore;
27
+ pollStore?: MSTeamsPollStore;
28
+ };
29
+
30
+ export type MonitorMSTeamsResult = {
31
+ app: unknown;
32
+ shutdown: () => Promise<void>;
33
+ };
34
+
35
+ export async function monitorMSTeamsProvider(
36
+ opts: MonitorMSTeamsOpts,
37
+ ): Promise<MonitorMSTeamsResult> {
38
+ const core = getMSTeamsRuntime();
39
+ const log = core.logging.getChildLogger({ name: "msteams" });
40
+ let cfg = opts.cfg;
41
+ let msteamsCfg = cfg.channels?.msteams;
42
+ if (!msteamsCfg?.enabled) {
43
+ log.debug("msteams provider disabled");
44
+ return { app: null, shutdown: async () => {} };
45
+ }
46
+
47
+ const creds = resolveMSTeamsCredentials(msteamsCfg);
48
+ if (!creds) {
49
+ log.error("msteams credentials not configured");
50
+ return { app: null, shutdown: async () => {} };
51
+ }
52
+ const appId = creds.appId; // Extract for use in closures
53
+
54
+ const runtime: RuntimeEnv = opts.runtime ?? {
55
+ log: console.log,
56
+ error: console.error,
57
+ exit: (code: number): never => {
58
+ throw new Error(`exit ${code}`);
59
+ },
60
+ };
61
+
62
+ let allowFrom = msteamsCfg.allowFrom;
63
+ let groupAllowFrom = msteamsCfg.groupAllowFrom;
64
+ let teamsConfig = msteamsCfg.teams;
65
+
66
+ const cleanAllowEntry = (entry: string) =>
67
+ entry
68
+ .replace(/^(msteams|teams):/i, "")
69
+ .replace(/^user:/i, "")
70
+ .trim();
71
+
72
+ const resolveAllowlistUsers = async (label: string, entries: string[]) => {
73
+ if (entries.length === 0) return { additions: [], unresolved: [] };
74
+ const resolved = await resolveMSTeamsUserAllowlist({ cfg, entries });
75
+ const additions: string[] = [];
76
+ const unresolved: string[] = [];
77
+ for (const entry of resolved) {
78
+ if (entry.resolved && entry.id) {
79
+ additions.push(entry.id);
80
+ } else {
81
+ unresolved.push(entry.input);
82
+ }
83
+ }
84
+ const mapping = resolved
85
+ .filter((entry) => entry.resolved && entry.id)
86
+ .map((entry) => `${entry.input}→${entry.id}`);
87
+ summarizeMapping(label, mapping, unresolved, runtime);
88
+ return { additions, unresolved };
89
+ };
90
+
91
+ try {
92
+ const allowEntries =
93
+ allowFrom?.map((entry) => cleanAllowEntry(String(entry))).filter(
94
+ (entry) => entry && entry !== "*",
95
+ ) ?? [];
96
+ if (allowEntries.length > 0) {
97
+ const { additions } = await resolveAllowlistUsers("msteams users", allowEntries);
98
+ allowFrom = mergeAllowlist({ existing: allowFrom, additions });
99
+ }
100
+
101
+ if (Array.isArray(groupAllowFrom) && groupAllowFrom.length > 0) {
102
+ const groupEntries = groupAllowFrom
103
+ .map((entry) => cleanAllowEntry(String(entry)))
104
+ .filter((entry) => entry && entry !== "*");
105
+ if (groupEntries.length > 0) {
106
+ const { additions } = await resolveAllowlistUsers("msteams group users", groupEntries);
107
+ groupAllowFrom = mergeAllowlist({ existing: groupAllowFrom, additions });
108
+ }
109
+ }
110
+
111
+ if (teamsConfig && Object.keys(teamsConfig).length > 0) {
112
+ const entries: Array<{ input: string; teamKey: string; channelKey?: string }> = [];
113
+ for (const [teamKey, teamCfg] of Object.entries(teamsConfig)) {
114
+ if (teamKey === "*") continue;
115
+ const channels = teamCfg?.channels ?? {};
116
+ const channelKeys = Object.keys(channels).filter((key) => key !== "*");
117
+ if (channelKeys.length === 0) {
118
+ entries.push({ input: teamKey, teamKey });
119
+ continue;
120
+ }
121
+ for (const channelKey of channelKeys) {
122
+ entries.push({
123
+ input: `${teamKey}/${channelKey}`,
124
+ teamKey,
125
+ channelKey,
126
+ });
127
+ }
128
+ }
129
+
130
+ if (entries.length > 0) {
131
+ const resolved = await resolveMSTeamsChannelAllowlist({
132
+ cfg,
133
+ entries: entries.map((entry) => entry.input),
134
+ });
135
+ const mapping: string[] = [];
136
+ const unresolved: string[] = [];
137
+ const nextTeams = { ...(teamsConfig ?? {}) };
138
+
139
+ resolved.forEach((entry, idx) => {
140
+ const source = entries[idx];
141
+ if (!source) return;
142
+ const sourceTeam = teamsConfig?.[source.teamKey] ?? {};
143
+ if (!entry.resolved || !entry.teamId) {
144
+ unresolved.push(entry.input);
145
+ return;
146
+ }
147
+ mapping.push(
148
+ entry.channelId
149
+ ? `${entry.input}→${entry.teamId}/${entry.channelId}`
150
+ : `${entry.input}→${entry.teamId}`,
151
+ );
152
+ const existing = nextTeams[entry.teamId] ?? {};
153
+ const mergedChannels = {
154
+ ...(sourceTeam.channels ?? {}),
155
+ ...(existing.channels ?? {}),
156
+ };
157
+ const mergedTeam = { ...sourceTeam, ...existing, channels: mergedChannels };
158
+ nextTeams[entry.teamId] = mergedTeam;
159
+ if (source.channelKey && entry.channelId) {
160
+ const sourceChannel = sourceTeam.channels?.[source.channelKey];
161
+ if (sourceChannel) {
162
+ nextTeams[entry.teamId] = {
163
+ ...mergedTeam,
164
+ channels: {
165
+ ...mergedChannels,
166
+ [entry.channelId]: {
167
+ ...sourceChannel,
168
+ ...(mergedChannels?.[entry.channelId] ?? {}),
169
+ },
170
+ },
171
+ };
172
+ }
173
+ }
174
+ });
175
+
176
+ teamsConfig = nextTeams;
177
+ summarizeMapping("msteams channels", mapping, unresolved, runtime);
178
+ }
179
+ }
180
+ } catch (err) {
181
+ runtime.log?.(`msteams resolve failed; using config entries. ${String(err)}`);
182
+ }
183
+
184
+ msteamsCfg = {
185
+ ...msteamsCfg,
186
+ allowFrom,
187
+ groupAllowFrom,
188
+ teams: teamsConfig,
189
+ };
190
+ cfg = {
191
+ ...cfg,
192
+ channels: {
193
+ ...cfg.channels,
194
+ msteams: msteamsCfg,
195
+ },
196
+ };
197
+
198
+ const port = msteamsCfg.webhook?.port ?? 3978;
199
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "msteams");
200
+ const MB = 1024 * 1024;
201
+ const agentDefaults = cfg.agents?.defaults;
202
+ const mediaMaxBytes =
203
+ typeof agentDefaults?.mediaMaxMb === "number" && agentDefaults.mediaMaxMb > 0
204
+ ? Math.floor(agentDefaults.mediaMaxMb * MB)
205
+ : 8 * MB;
206
+ const conversationStore = opts.conversationStore ?? createMSTeamsConversationStoreFs();
207
+ const pollStore = opts.pollStore ?? createMSTeamsPollStoreFs();
208
+
209
+ log.info(`starting provider (port ${port})`);
210
+
211
+ // Dynamic import to avoid loading SDK when provider is disabled
212
+ const express = await import("express");
213
+
214
+ const { sdk, authConfig } = await loadMSTeamsSdkWithAuth(creds);
215
+ const { ActivityHandler, MsalTokenProvider, authorizeJWT } = sdk;
216
+
217
+ // Auth configuration - create early so adapter is available for deliverReplies
218
+ const tokenProvider = new MsalTokenProvider(authConfig);
219
+ const adapter = createMSTeamsAdapter(authConfig, sdk);
220
+
221
+ const handler = registerMSTeamsHandlers(new ActivityHandler(), {
222
+ cfg,
223
+ runtime,
224
+ appId,
225
+ adapter: adapter as unknown as MSTeamsAdapter,
226
+ tokenProvider,
227
+ textLimit,
228
+ mediaMaxBytes,
229
+ conversationStore,
230
+ pollStore,
231
+ log,
232
+ });
233
+
234
+ // Create Express server
235
+ const expressApp = express.default();
236
+ expressApp.use(express.json());
237
+ expressApp.use(authorizeJWT(authConfig));
238
+
239
+ // Set up the messages endpoint - use configured path and /api/messages as fallback
240
+ const configuredPath = msteamsCfg.webhook?.path ?? "/api/messages";
241
+ const messageHandler = (req: Request, res: Response) => {
242
+ type HandlerContext = Parameters<(typeof handler)["run"]>[0];
243
+ void adapter
244
+ .process(req, res, (context: unknown) => handler.run(context as HandlerContext))
245
+ .catch((err: unknown) => {
246
+ log.error("msteams webhook failed", { error: formatUnknownError(err) });
247
+ });
248
+ };
249
+
250
+ // Listen on configured path and /api/messages (standard Bot Framework path)
251
+ expressApp.post(configuredPath, messageHandler);
252
+ if (configuredPath !== "/api/messages") {
253
+ expressApp.post("/api/messages", messageHandler);
254
+ }
255
+
256
+ log.debug("listening on paths", {
257
+ primary: configuredPath,
258
+ fallback: "/api/messages",
259
+ });
260
+
261
+ // Start listening and capture the HTTP server handle
262
+ const httpServer = expressApp.listen(port, () => {
263
+ log.info(`msteams provider started on port ${port}`);
264
+ });
265
+
266
+ httpServer.on("error", (err) => {
267
+ log.error("msteams server error", { error: String(err) });
268
+ });
269
+
270
+ const shutdown = async () => {
271
+ log.info("shutting down msteams provider");
272
+ return new Promise<void>((resolve) => {
273
+ httpServer.close((err) => {
274
+ if (err) {
275
+ log.debug("msteams server close error", { error: String(err) });
276
+ }
277
+ resolve();
278
+ });
279
+ });
280
+ };
281
+
282
+ // Handle abort signal
283
+ if (opts.abortSignal) {
284
+ opts.abortSignal.addEventListener("abort", () => {
285
+ void shutdown();
286
+ });
287
+ }
288
+
289
+ return { app: expressApp, shutdown };
290
+ }