@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.
- package/CHANGELOG.md +56 -0
- package/index.ts +18 -0
- package/openclaw.plugin.json +11 -0
- package/package.json +36 -0
- package/src/attachments/download.ts +206 -0
- package/src/attachments/graph.ts +319 -0
- package/src/attachments/html.ts +76 -0
- package/src/attachments/payload.ts +22 -0
- package/src/attachments/shared.ts +235 -0
- package/src/attachments/types.ts +37 -0
- package/src/attachments.test.ts +424 -0
- package/src/attachments.ts +18 -0
- package/src/channel.directory.test.ts +46 -0
- package/src/channel.ts +436 -0
- package/src/conversation-store-fs.test.ts +89 -0
- package/src/conversation-store-fs.ts +155 -0
- package/src/conversation-store-memory.ts +45 -0
- package/src/conversation-store.ts +41 -0
- package/src/directory-live.ts +179 -0
- package/src/errors.test.ts +46 -0
- package/src/errors.ts +158 -0
- package/src/file-consent-helpers.test.ts +234 -0
- package/src/file-consent-helpers.ts +73 -0
- package/src/file-consent.ts +122 -0
- package/src/graph-chat.ts +52 -0
- package/src/graph-upload.ts +445 -0
- package/src/inbound.test.ts +67 -0
- package/src/inbound.ts +38 -0
- package/src/index.ts +4 -0
- package/src/media-helpers.test.ts +186 -0
- package/src/media-helpers.ts +77 -0
- package/src/messenger.test.ts +245 -0
- package/src/messenger.ts +460 -0
- package/src/monitor-handler/inbound-media.ts +123 -0
- package/src/monitor-handler/message-handler.ts +629 -0
- package/src/monitor-handler.ts +166 -0
- package/src/monitor-types.ts +5 -0
- package/src/monitor.ts +290 -0
- package/src/onboarding.ts +432 -0
- package/src/outbound.ts +47 -0
- package/src/pending-uploads.ts +87 -0
- package/src/policy.test.ts +210 -0
- package/src/policy.ts +247 -0
- package/src/polls-store-memory.ts +30 -0
- package/src/polls-store.test.ts +40 -0
- package/src/polls.test.ts +73 -0
- package/src/polls.ts +300 -0
- package/src/probe.test.ts +57 -0
- package/src/probe.ts +99 -0
- package/src/reply-dispatcher.ts +128 -0
- package/src/resolve-allowlist.ts +277 -0
- package/src/runtime.ts +14 -0
- package/src/sdk-types.ts +19 -0
- package/src/sdk.ts +33 -0
- package/src/send-context.ts +156 -0
- package/src/send.ts +489 -0
- package/src/sent-message-cache.test.ts +16 -0
- package/src/sent-message-cache.ts +41 -0
- package/src/storage.ts +22 -0
- package/src/store-fs.ts +80 -0
- package/src/token.ts +19 -0
package/src/messenger.ts
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ChunkMode,
|
|
3
|
+
isSilentReplyText,
|
|
4
|
+
loadWebMedia,
|
|
5
|
+
type MarkdownTableMode,
|
|
6
|
+
type MSTeamsReplyStyle,
|
|
7
|
+
type ReplyPayload,
|
|
8
|
+
SILENT_REPLY_TOKEN,
|
|
9
|
+
} from "openclaw/plugin-sdk";
|
|
10
|
+
import type { MSTeamsAccessTokenProvider } from "./attachments/types.js";
|
|
11
|
+
import type { StoredConversationReference } from "./conversation-store.js";
|
|
12
|
+
import { classifyMSTeamsSendError } from "./errors.js";
|
|
13
|
+
import { prepareFileConsentActivity, requiresFileConsent } from "./file-consent-helpers.js";
|
|
14
|
+
import { buildTeamsFileInfoCard } from "./graph-chat.js";
|
|
15
|
+
import {
|
|
16
|
+
getDriveItemProperties,
|
|
17
|
+
uploadAndShareOneDrive,
|
|
18
|
+
uploadAndShareSharePoint,
|
|
19
|
+
} from "./graph-upload.js";
|
|
20
|
+
import { extractFilename, extractMessageId, getMimeType, isLocalPath } from "./media-helpers.js";
|
|
21
|
+
import { getMSTeamsRuntime } from "./runtime.js";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* MSTeams-specific media size limit (100MB).
|
|
25
|
+
* Higher than the default because OneDrive upload handles large files well.
|
|
26
|
+
*/
|
|
27
|
+
const MSTEAMS_MAX_MEDIA_BYTES = 100 * 1024 * 1024;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Threshold for large files that require FileConsentCard flow in personal chats.
|
|
31
|
+
* Files >= 4MB use consent flow; smaller images can use inline base64.
|
|
32
|
+
*/
|
|
33
|
+
const FILE_CONSENT_THRESHOLD_BYTES = 4 * 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
type SendContext = {
|
|
36
|
+
sendActivity: (textOrActivity: string | object) => Promise<unknown>;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export type MSTeamsConversationReference = {
|
|
40
|
+
activityId?: string;
|
|
41
|
+
user?: { id?: string; name?: string; aadObjectId?: string };
|
|
42
|
+
agent?: { id?: string; name?: string; aadObjectId?: string } | null;
|
|
43
|
+
conversation: { id: string; conversationType?: string; tenantId?: string };
|
|
44
|
+
channelId: string;
|
|
45
|
+
serviceUrl?: string;
|
|
46
|
+
locale?: string;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type MSTeamsAdapter = {
|
|
50
|
+
continueConversation: (
|
|
51
|
+
appId: string,
|
|
52
|
+
reference: MSTeamsConversationReference,
|
|
53
|
+
logic: (context: SendContext) => Promise<void>,
|
|
54
|
+
) => Promise<void>;
|
|
55
|
+
process: (
|
|
56
|
+
req: unknown,
|
|
57
|
+
res: unknown,
|
|
58
|
+
logic: (context: unknown) => Promise<void>,
|
|
59
|
+
) => Promise<void>;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type MSTeamsReplyRenderOptions = {
|
|
63
|
+
textChunkLimit: number;
|
|
64
|
+
chunkText?: boolean;
|
|
65
|
+
mediaMode?: "split" | "inline";
|
|
66
|
+
tableMode?: MarkdownTableMode;
|
|
67
|
+
chunkMode?: ChunkMode;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A rendered message that preserves media vs text distinction.
|
|
72
|
+
* When mediaUrl is present, it will be sent as a Bot Framework attachment.
|
|
73
|
+
*/
|
|
74
|
+
export type MSTeamsRenderedMessage = {
|
|
75
|
+
text?: string;
|
|
76
|
+
mediaUrl?: string;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type MSTeamsSendRetryOptions = {
|
|
80
|
+
maxAttempts?: number;
|
|
81
|
+
baseDelayMs?: number;
|
|
82
|
+
maxDelayMs?: number;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export type MSTeamsSendRetryEvent = {
|
|
86
|
+
messageIndex: number;
|
|
87
|
+
messageCount: number;
|
|
88
|
+
nextAttempt: number;
|
|
89
|
+
maxAttempts: number;
|
|
90
|
+
delayMs: number;
|
|
91
|
+
classification: ReturnType<typeof classifyMSTeamsSendError>;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
function normalizeConversationId(rawId: string): string {
|
|
95
|
+
return rawId.split(";")[0] ?? rawId;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function buildConversationReference(
|
|
99
|
+
ref: StoredConversationReference,
|
|
100
|
+
): MSTeamsConversationReference {
|
|
101
|
+
const conversationId = ref.conversation?.id?.trim();
|
|
102
|
+
if (!conversationId) {
|
|
103
|
+
throw new Error("Invalid stored reference: missing conversation.id");
|
|
104
|
+
}
|
|
105
|
+
const agent = ref.agent ?? ref.bot ?? undefined;
|
|
106
|
+
if (agent == null || !agent.id) {
|
|
107
|
+
throw new Error("Invalid stored reference: missing agent.id");
|
|
108
|
+
}
|
|
109
|
+
const user = ref.user;
|
|
110
|
+
if (!user?.id) {
|
|
111
|
+
throw new Error("Invalid stored reference: missing user.id");
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
activityId: ref.activityId,
|
|
115
|
+
user,
|
|
116
|
+
agent,
|
|
117
|
+
conversation: {
|
|
118
|
+
id: normalizeConversationId(conversationId),
|
|
119
|
+
conversationType: ref.conversation?.conversationType,
|
|
120
|
+
tenantId: ref.conversation?.tenantId,
|
|
121
|
+
},
|
|
122
|
+
channelId: ref.channelId ?? "msteams",
|
|
123
|
+
serviceUrl: ref.serviceUrl,
|
|
124
|
+
locale: ref.locale,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function pushTextMessages(
|
|
129
|
+
out: MSTeamsRenderedMessage[],
|
|
130
|
+
text: string,
|
|
131
|
+
opts: {
|
|
132
|
+
chunkText: boolean;
|
|
133
|
+
chunkLimit: number;
|
|
134
|
+
chunkMode: ChunkMode;
|
|
135
|
+
},
|
|
136
|
+
) {
|
|
137
|
+
if (!text) return;
|
|
138
|
+
if (opts.chunkText) {
|
|
139
|
+
for (const chunk of getMSTeamsRuntime().channel.text.chunkMarkdownTextWithMode(
|
|
140
|
+
text,
|
|
141
|
+
opts.chunkLimit,
|
|
142
|
+
opts.chunkMode,
|
|
143
|
+
)) {
|
|
144
|
+
const trimmed = chunk.trim();
|
|
145
|
+
if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) continue;
|
|
146
|
+
out.push({ text: trimmed });
|
|
147
|
+
}
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const trimmed = text.trim();
|
|
152
|
+
if (!trimmed || isSilentReplyText(trimmed, SILENT_REPLY_TOKEN)) return;
|
|
153
|
+
out.push({ text: trimmed });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
function clampMs(value: number, maxMs: number): number {
|
|
158
|
+
if (!Number.isFinite(value) || value < 0) return 0;
|
|
159
|
+
return Math.min(value, maxMs);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function sleep(ms: number): Promise<void> {
|
|
163
|
+
const delay = Math.max(0, ms);
|
|
164
|
+
if (delay === 0) return;
|
|
165
|
+
await new Promise<void>((resolve) => {
|
|
166
|
+
setTimeout(resolve, delay);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function resolveRetryOptions(
|
|
171
|
+
retry: false | MSTeamsSendRetryOptions | undefined,
|
|
172
|
+
): Required<MSTeamsSendRetryOptions> & { enabled: boolean } {
|
|
173
|
+
if (!retry) {
|
|
174
|
+
return { enabled: false, maxAttempts: 1, baseDelayMs: 0, maxDelayMs: 0 };
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
enabled: true,
|
|
178
|
+
maxAttempts: Math.max(1, retry?.maxAttempts ?? 3),
|
|
179
|
+
baseDelayMs: Math.max(0, retry?.baseDelayMs ?? 250),
|
|
180
|
+
maxDelayMs: Math.max(0, retry?.maxDelayMs ?? 10_000),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function computeRetryDelayMs(
|
|
185
|
+
attempt: number,
|
|
186
|
+
classification: ReturnType<typeof classifyMSTeamsSendError>,
|
|
187
|
+
opts: Required<MSTeamsSendRetryOptions>,
|
|
188
|
+
): number {
|
|
189
|
+
if (classification.retryAfterMs != null) {
|
|
190
|
+
return clampMs(classification.retryAfterMs, opts.maxDelayMs);
|
|
191
|
+
}
|
|
192
|
+
const exponential = opts.baseDelayMs * 2 ** Math.max(0, attempt - 1);
|
|
193
|
+
return clampMs(exponential, opts.maxDelayMs);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function shouldRetry(classification: ReturnType<typeof classifyMSTeamsSendError>): boolean {
|
|
197
|
+
return classification.kind === "throttled" || classification.kind === "transient";
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function renderReplyPayloadsToMessages(
|
|
201
|
+
replies: ReplyPayload[],
|
|
202
|
+
options: MSTeamsReplyRenderOptions,
|
|
203
|
+
): MSTeamsRenderedMessage[] {
|
|
204
|
+
const out: MSTeamsRenderedMessage[] = [];
|
|
205
|
+
const chunkLimit = Math.min(options.textChunkLimit, 4000);
|
|
206
|
+
const chunkText = options.chunkText !== false;
|
|
207
|
+
const chunkMode = options.chunkMode ?? "length";
|
|
208
|
+
const mediaMode = options.mediaMode ?? "split";
|
|
209
|
+
const tableMode =
|
|
210
|
+
options.tableMode ??
|
|
211
|
+
getMSTeamsRuntime().channel.text.resolveMarkdownTableMode({
|
|
212
|
+
cfg: getMSTeamsRuntime().config.loadConfig(),
|
|
213
|
+
channel: "msteams",
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
for (const payload of replies) {
|
|
217
|
+
const mediaList = payload.mediaUrls ?? (payload.mediaUrl ? [payload.mediaUrl] : []);
|
|
218
|
+
const text = getMSTeamsRuntime().channel.text.convertMarkdownTables(
|
|
219
|
+
payload.text ?? "",
|
|
220
|
+
tableMode,
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
if (!text && mediaList.length === 0) continue;
|
|
224
|
+
|
|
225
|
+
if (mediaList.length === 0) {
|
|
226
|
+
pushTextMessages(out, text, { chunkText, chunkLimit, chunkMode });
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (mediaMode === "inline") {
|
|
231
|
+
// For inline mode, combine text with first media as attachment
|
|
232
|
+
const firstMedia = mediaList[0];
|
|
233
|
+
if (firstMedia) {
|
|
234
|
+
out.push({ text: text || undefined, mediaUrl: firstMedia });
|
|
235
|
+
// Additional media URLs as separate messages
|
|
236
|
+
for (let i = 1; i < mediaList.length; i++) {
|
|
237
|
+
if (mediaList[i]) out.push({ mediaUrl: mediaList[i] });
|
|
238
|
+
}
|
|
239
|
+
} else {
|
|
240
|
+
pushTextMessages(out, text, { chunkText, chunkLimit, chunkMode });
|
|
241
|
+
}
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// mediaMode === "split"
|
|
246
|
+
pushTextMessages(out, text, { chunkText, chunkLimit, chunkMode });
|
|
247
|
+
for (const mediaUrl of mediaList) {
|
|
248
|
+
if (!mediaUrl) continue;
|
|
249
|
+
out.push({ mediaUrl });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function buildActivity(
|
|
257
|
+
msg: MSTeamsRenderedMessage,
|
|
258
|
+
conversationRef: StoredConversationReference,
|
|
259
|
+
tokenProvider?: MSTeamsAccessTokenProvider,
|
|
260
|
+
sharePointSiteId?: string,
|
|
261
|
+
mediaMaxBytes?: number,
|
|
262
|
+
): Promise<Record<string, unknown>> {
|
|
263
|
+
const activity: Record<string, unknown> = { type: "message" };
|
|
264
|
+
|
|
265
|
+
if (msg.text) {
|
|
266
|
+
activity.text = msg.text;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (msg.mediaUrl) {
|
|
270
|
+
let contentUrl = msg.mediaUrl;
|
|
271
|
+
let contentType = await getMimeType(msg.mediaUrl);
|
|
272
|
+
let fileName = await extractFilename(msg.mediaUrl);
|
|
273
|
+
|
|
274
|
+
if (isLocalPath(msg.mediaUrl)) {
|
|
275
|
+
const maxBytes = mediaMaxBytes ?? MSTEAMS_MAX_MEDIA_BYTES;
|
|
276
|
+
const media = await loadWebMedia(msg.mediaUrl, maxBytes);
|
|
277
|
+
contentType = media.contentType ?? contentType;
|
|
278
|
+
fileName = media.fileName ?? fileName;
|
|
279
|
+
|
|
280
|
+
// Determine conversation type and file type
|
|
281
|
+
// Teams only accepts base64 data URLs for images
|
|
282
|
+
const conversationType = conversationRef.conversation?.conversationType?.toLowerCase();
|
|
283
|
+
const isPersonal = conversationType === "personal";
|
|
284
|
+
const isImage = contentType?.startsWith("image/") ?? false;
|
|
285
|
+
|
|
286
|
+
if (requiresFileConsent({
|
|
287
|
+
conversationType,
|
|
288
|
+
contentType,
|
|
289
|
+
bufferSize: media.buffer.length,
|
|
290
|
+
thresholdBytes: FILE_CONSENT_THRESHOLD_BYTES,
|
|
291
|
+
})) {
|
|
292
|
+
// Large file or non-image in personal chat: use FileConsentCard flow
|
|
293
|
+
const conversationId = conversationRef.conversation?.id ?? "unknown";
|
|
294
|
+
const { activity: consentActivity } = prepareFileConsentActivity({
|
|
295
|
+
media: { buffer: media.buffer, filename: fileName, contentType },
|
|
296
|
+
conversationId,
|
|
297
|
+
description: msg.text || undefined,
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// Return the consent activity (caller sends it)
|
|
301
|
+
return consentActivity;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
if (!isPersonal && !isImage && tokenProvider && sharePointSiteId) {
|
|
305
|
+
// Non-image in group chat/channel with SharePoint site configured:
|
|
306
|
+
// Upload to SharePoint and use native file card attachment
|
|
307
|
+
const chatId = conversationRef.conversation?.id;
|
|
308
|
+
|
|
309
|
+
// Upload to SharePoint
|
|
310
|
+
const uploaded = await uploadAndShareSharePoint({
|
|
311
|
+
buffer: media.buffer,
|
|
312
|
+
filename: fileName,
|
|
313
|
+
contentType,
|
|
314
|
+
tokenProvider,
|
|
315
|
+
siteId: sharePointSiteId,
|
|
316
|
+
chatId: chatId ?? undefined,
|
|
317
|
+
usePerUserSharing: conversationType === "groupchat",
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
// Get driveItem properties needed for native file card attachment
|
|
321
|
+
const driveItem = await getDriveItemProperties({
|
|
322
|
+
siteId: sharePointSiteId,
|
|
323
|
+
itemId: uploaded.itemId,
|
|
324
|
+
tokenProvider,
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
// Build native Teams file card attachment
|
|
328
|
+
const fileCardAttachment = buildTeamsFileInfoCard(driveItem);
|
|
329
|
+
activity.attachments = [fileCardAttachment];
|
|
330
|
+
|
|
331
|
+
return activity;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (!isPersonal && !isImage && tokenProvider) {
|
|
335
|
+
// Fallback: no SharePoint site configured, try OneDrive upload
|
|
336
|
+
const uploaded = await uploadAndShareOneDrive({
|
|
337
|
+
buffer: media.buffer,
|
|
338
|
+
filename: fileName,
|
|
339
|
+
contentType,
|
|
340
|
+
tokenProvider,
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
// Bot Framework doesn't support "reference" attachment type for sending
|
|
344
|
+
const fileLink = `📎 [${uploaded.name}](${uploaded.shareUrl})`;
|
|
345
|
+
activity.text = msg.text ? `${msg.text}\n\n${fileLink}` : fileLink;
|
|
346
|
+
return activity;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Image (any chat): use base64 (works for images in all conversation types)
|
|
350
|
+
const base64 = media.buffer.toString("base64");
|
|
351
|
+
contentUrl = `data:${media.contentType};base64,${base64}`;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
activity.attachments = [
|
|
355
|
+
{
|
|
356
|
+
name: fileName,
|
|
357
|
+
contentType,
|
|
358
|
+
contentUrl,
|
|
359
|
+
},
|
|
360
|
+
];
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
return activity;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export async function sendMSTeamsMessages(params: {
|
|
367
|
+
replyStyle: MSTeamsReplyStyle;
|
|
368
|
+
adapter: MSTeamsAdapter;
|
|
369
|
+
appId: string;
|
|
370
|
+
conversationRef: StoredConversationReference;
|
|
371
|
+
context?: SendContext;
|
|
372
|
+
messages: MSTeamsRenderedMessage[];
|
|
373
|
+
retry?: false | MSTeamsSendRetryOptions;
|
|
374
|
+
onRetry?: (event: MSTeamsSendRetryEvent) => void;
|
|
375
|
+
/** Token provider for OneDrive/SharePoint uploads in group chats/channels */
|
|
376
|
+
tokenProvider?: MSTeamsAccessTokenProvider;
|
|
377
|
+
/** SharePoint site ID for file uploads in group chats/channels */
|
|
378
|
+
sharePointSiteId?: string;
|
|
379
|
+
/** Max media size in bytes. Default: 100MB. */
|
|
380
|
+
mediaMaxBytes?: number;
|
|
381
|
+
}): Promise<string[]> {
|
|
382
|
+
const messages = params.messages.filter(
|
|
383
|
+
(m) => (m.text && m.text.trim().length > 0) || m.mediaUrl,
|
|
384
|
+
);
|
|
385
|
+
if (messages.length === 0) return [];
|
|
386
|
+
|
|
387
|
+
const retryOptions = resolveRetryOptions(params.retry);
|
|
388
|
+
|
|
389
|
+
const sendWithRetry = async (
|
|
390
|
+
sendOnce: () => Promise<unknown>,
|
|
391
|
+
meta: { messageIndex: number; messageCount: number },
|
|
392
|
+
): Promise<unknown> => {
|
|
393
|
+
if (!retryOptions.enabled) return await sendOnce();
|
|
394
|
+
|
|
395
|
+
let attempt = 1;
|
|
396
|
+
while (true) {
|
|
397
|
+
try {
|
|
398
|
+
return await sendOnce();
|
|
399
|
+
} catch (err) {
|
|
400
|
+
const classification = classifyMSTeamsSendError(err);
|
|
401
|
+
const canRetry = attempt < retryOptions.maxAttempts && shouldRetry(classification);
|
|
402
|
+
if (!canRetry) throw err;
|
|
403
|
+
|
|
404
|
+
const delayMs = computeRetryDelayMs(attempt, classification, retryOptions);
|
|
405
|
+
const nextAttempt = attempt + 1;
|
|
406
|
+
params.onRetry?.({
|
|
407
|
+
messageIndex: meta.messageIndex,
|
|
408
|
+
messageCount: meta.messageCount,
|
|
409
|
+
nextAttempt,
|
|
410
|
+
maxAttempts: retryOptions.maxAttempts,
|
|
411
|
+
delayMs,
|
|
412
|
+
classification,
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
await sleep(delayMs);
|
|
416
|
+
attempt = nextAttempt;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
if (params.replyStyle === "thread") {
|
|
422
|
+
const ctx = params.context;
|
|
423
|
+
if (!ctx) {
|
|
424
|
+
throw new Error("Missing context for replyStyle=thread");
|
|
425
|
+
}
|
|
426
|
+
const messageIds: string[] = [];
|
|
427
|
+
for (const [idx, message] of messages.entries()) {
|
|
428
|
+
const response = await sendWithRetry(
|
|
429
|
+
async () =>
|
|
430
|
+
await ctx.sendActivity(
|
|
431
|
+
await buildActivity(message, params.conversationRef, params.tokenProvider, params.sharePointSiteId, params.mediaMaxBytes),
|
|
432
|
+
),
|
|
433
|
+
{ messageIndex: idx, messageCount: messages.length },
|
|
434
|
+
);
|
|
435
|
+
messageIds.push(extractMessageId(response) ?? "unknown");
|
|
436
|
+
}
|
|
437
|
+
return messageIds;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const baseRef = buildConversationReference(params.conversationRef);
|
|
441
|
+
const proactiveRef: MSTeamsConversationReference = {
|
|
442
|
+
...baseRef,
|
|
443
|
+
activityId: undefined,
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
const messageIds: string[] = [];
|
|
447
|
+
await params.adapter.continueConversation(params.appId, proactiveRef, async (ctx) => {
|
|
448
|
+
for (const [idx, message] of messages.entries()) {
|
|
449
|
+
const response = await sendWithRetry(
|
|
450
|
+
async () =>
|
|
451
|
+
await ctx.sendActivity(
|
|
452
|
+
await buildActivity(message, params.conversationRef, params.tokenProvider, params.sharePointSiteId, params.mediaMaxBytes),
|
|
453
|
+
),
|
|
454
|
+
{ messageIndex: idx, messageCount: messages.length },
|
|
455
|
+
);
|
|
456
|
+
messageIds.push(extractMessageId(response) ?? "unknown");
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
return messageIds;
|
|
460
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildMSTeamsGraphMessageUrls,
|
|
3
|
+
downloadMSTeamsAttachments,
|
|
4
|
+
downloadMSTeamsGraphMedia,
|
|
5
|
+
type MSTeamsAccessTokenProvider,
|
|
6
|
+
type MSTeamsAttachmentLike,
|
|
7
|
+
type MSTeamsHtmlAttachmentSummary,
|
|
8
|
+
type MSTeamsInboundMedia,
|
|
9
|
+
} from "../attachments.js";
|
|
10
|
+
import type { MSTeamsTurnContext } from "../sdk-types.js";
|
|
11
|
+
|
|
12
|
+
type MSTeamsLogger = {
|
|
13
|
+
debug: (message: string, meta?: Record<string, unknown>) => void;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export async function resolveMSTeamsInboundMedia(params: {
|
|
17
|
+
attachments: MSTeamsAttachmentLike[];
|
|
18
|
+
htmlSummary?: MSTeamsHtmlAttachmentSummary;
|
|
19
|
+
maxBytes: number;
|
|
20
|
+
allowHosts?: string[];
|
|
21
|
+
tokenProvider: MSTeamsAccessTokenProvider;
|
|
22
|
+
conversationType: string;
|
|
23
|
+
conversationId: string;
|
|
24
|
+
conversationMessageId?: string;
|
|
25
|
+
activity: Pick<MSTeamsTurnContext["activity"], "id" | "replyToId" | "channelData">;
|
|
26
|
+
log: MSTeamsLogger;
|
|
27
|
+
/** When true, embeds original filename in stored path for later extraction. */
|
|
28
|
+
preserveFilenames?: boolean;
|
|
29
|
+
}): Promise<MSTeamsInboundMedia[]> {
|
|
30
|
+
const {
|
|
31
|
+
attachments,
|
|
32
|
+
htmlSummary,
|
|
33
|
+
maxBytes,
|
|
34
|
+
tokenProvider,
|
|
35
|
+
allowHosts,
|
|
36
|
+
conversationType,
|
|
37
|
+
conversationId,
|
|
38
|
+
conversationMessageId,
|
|
39
|
+
activity,
|
|
40
|
+
log,
|
|
41
|
+
preserveFilenames,
|
|
42
|
+
} = params;
|
|
43
|
+
|
|
44
|
+
let mediaList = await downloadMSTeamsAttachments({
|
|
45
|
+
attachments,
|
|
46
|
+
maxBytes,
|
|
47
|
+
tokenProvider,
|
|
48
|
+
allowHosts,
|
|
49
|
+
preserveFilenames,
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
if (mediaList.length === 0) {
|
|
53
|
+
const onlyHtmlAttachments =
|
|
54
|
+
attachments.length > 0 &&
|
|
55
|
+
attachments.every((att) => String(att.contentType ?? "").startsWith("text/html"));
|
|
56
|
+
|
|
57
|
+
if (onlyHtmlAttachments) {
|
|
58
|
+
const messageUrls = buildMSTeamsGraphMessageUrls({
|
|
59
|
+
conversationType,
|
|
60
|
+
conversationId,
|
|
61
|
+
messageId: activity.id ?? undefined,
|
|
62
|
+
replyToId: activity.replyToId ?? undefined,
|
|
63
|
+
conversationMessageId,
|
|
64
|
+
channelData: activity.channelData,
|
|
65
|
+
});
|
|
66
|
+
if (messageUrls.length === 0) {
|
|
67
|
+
log.debug("graph message url unavailable", {
|
|
68
|
+
conversationType,
|
|
69
|
+
hasChannelData: Boolean(activity.channelData),
|
|
70
|
+
messageId: activity.id ?? undefined,
|
|
71
|
+
replyToId: activity.replyToId ?? undefined,
|
|
72
|
+
});
|
|
73
|
+
} else {
|
|
74
|
+
const attempts: Array<{
|
|
75
|
+
url: string;
|
|
76
|
+
hostedStatus?: number;
|
|
77
|
+
attachmentStatus?: number;
|
|
78
|
+
hostedCount?: number;
|
|
79
|
+
attachmentCount?: number;
|
|
80
|
+
tokenError?: boolean;
|
|
81
|
+
}> = [];
|
|
82
|
+
for (const messageUrl of messageUrls) {
|
|
83
|
+
const graphMedia = await downloadMSTeamsGraphMedia({
|
|
84
|
+
messageUrl,
|
|
85
|
+
tokenProvider,
|
|
86
|
+
maxBytes,
|
|
87
|
+
allowHosts,
|
|
88
|
+
preserveFilenames,
|
|
89
|
+
});
|
|
90
|
+
attempts.push({
|
|
91
|
+
url: messageUrl,
|
|
92
|
+
hostedStatus: graphMedia.hostedStatus,
|
|
93
|
+
attachmentStatus: graphMedia.attachmentStatus,
|
|
94
|
+
hostedCount: graphMedia.hostedCount,
|
|
95
|
+
attachmentCount: graphMedia.attachmentCount,
|
|
96
|
+
tokenError: graphMedia.tokenError,
|
|
97
|
+
});
|
|
98
|
+
if (graphMedia.media.length > 0) {
|
|
99
|
+
mediaList = graphMedia.media;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
if (graphMedia.tokenError) break;
|
|
103
|
+
}
|
|
104
|
+
if (mediaList.length === 0) {
|
|
105
|
+
log.debug("graph media fetch empty", { attempts });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (mediaList.length > 0) {
|
|
112
|
+
log.debug("downloaded attachments", { count: mediaList.length });
|
|
113
|
+
} else if (htmlSummary?.imgTags) {
|
|
114
|
+
log.debug("inline images detected but none downloaded", {
|
|
115
|
+
imgTags: htmlSummary.imgTags,
|
|
116
|
+
srcHosts: htmlSummary.srcHosts,
|
|
117
|
+
dataImages: htmlSummary.dataImages,
|
|
118
|
+
cidImages: htmlSummary.cidImages,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return mediaList;
|
|
123
|
+
}
|