@openclaw/msteams 2026.5.2-beta.2 → 2026.5.3-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.
- package/dist/api.js +3 -0
- package/dist/channel-D7hdreTh.js +984 -0
- package/dist/channel-config-api.js +2 -0
- package/dist/channel-plugin-api.js +2 -0
- package/dist/channel.runtime-BC1ruIfN.js +573 -0
- package/dist/config-schema-B8QezH6t.js +15 -0
- package/dist/contract-api.js +2 -0
- package/dist/graph-users-9uQJepqr.js +1354 -0
- package/dist/index.js +22 -0
- package/dist/oauth-BWJyilR1.js +114 -0
- package/dist/oauth.token-xxpoLWy5.js +115 -0
- package/dist/policy-DTnU2GR7.js +142 -0
- package/dist/probe-D_H8yFps.js +2194 -0
- package/dist/resolve-allowlist-D41JSziq.js +219 -0
- package/dist/runtime-api-DV1iVMn1.js +28 -0
- package/dist/runtime-api.js +2 -0
- package/dist/secret-contract-BuoEXmPS.js +35 -0
- package/dist/secret-contract-api.js +2 -0
- package/dist/setup-entry.js +15 -0
- package/dist/setup-plugin-api.js +64 -0
- package/dist/setup-surface-BLkFQYIQ.js +313 -0
- package/dist/src-CFp1QpFd.js +4064 -0
- package/dist/test-api.js +2 -0
- package/package.json +14 -6
- package/api.ts +0 -3
- package/channel-config-api.ts +0 -1
- package/channel-plugin-api.ts +0 -2
- package/config-api.ts +0 -4
- package/contract-api.ts +0 -4
- package/index.ts +0 -20
- package/runtime-api.ts +0 -73
- package/secret-contract-api.ts +0 -5
- package/setup-entry.ts +0 -13
- package/setup-plugin-api.ts +0 -3
- package/src/ai-entity.ts +0 -7
- package/src/approval-auth.ts +0 -44
- package/src/attachments/bot-framework.test.ts +0 -461
- package/src/attachments/bot-framework.ts +0 -362
- package/src/attachments/download.ts +0 -311
- package/src/attachments/graph.test.ts +0 -416
- package/src/attachments/graph.ts +0 -484
- package/src/attachments/html.ts +0 -122
- package/src/attachments/payload.ts +0 -14
- package/src/attachments/remote-media.test.ts +0 -137
- package/src/attachments/remote-media.ts +0 -112
- package/src/attachments/shared.test.ts +0 -530
- package/src/attachments/shared.ts +0 -626
- package/src/attachments/types.ts +0 -47
- package/src/attachments.graph.test.ts +0 -342
- package/src/attachments.helpers.test.ts +0 -246
- package/src/attachments.test-helpers.ts +0 -17
- package/src/attachments.test.ts +0 -687
- package/src/attachments.ts +0 -18
- package/src/block-streaming-config.test.ts +0 -61
- package/src/channel-api.ts +0 -1
- package/src/channel.actions.test.ts +0 -742
- package/src/channel.directory.test.ts +0 -200
- package/src/channel.runtime.ts +0 -56
- package/src/channel.setup.ts +0 -77
- package/src/channel.test.ts +0 -128
- package/src/channel.ts +0 -1136
- package/src/config-schema.ts +0 -6
- package/src/config-ui-hints.ts +0 -12
- package/src/conversation-store-fs.test.ts +0 -74
- package/src/conversation-store-fs.ts +0 -149
- package/src/conversation-store-helpers.test.ts +0 -202
- package/src/conversation-store-helpers.ts +0 -105
- package/src/conversation-store-memory.ts +0 -51
- package/src/conversation-store.shared.test.ts +0 -225
- package/src/conversation-store.ts +0 -71
- package/src/directory-live.test.ts +0 -156
- package/src/directory-live.ts +0 -111
- package/src/doctor.ts +0 -27
- package/src/errors.test.ts +0 -133
- package/src/errors.ts +0 -246
- package/src/feedback-reflection-prompt.ts +0 -117
- package/src/feedback-reflection-store.ts +0 -114
- package/src/feedback-reflection.test.ts +0 -237
- package/src/feedback-reflection.ts +0 -283
- package/src/file-consent-helpers.test.ts +0 -326
- package/src/file-consent-helpers.ts +0 -126
- package/src/file-consent-invoke.ts +0 -150
- package/src/file-consent.test.ts +0 -363
- package/src/file-consent.ts +0 -287
- package/src/graph-chat.ts +0 -55
- package/src/graph-group-management.test.ts +0 -318
- package/src/graph-group-management.ts +0 -168
- package/src/graph-members.test.ts +0 -89
- package/src/graph-members.ts +0 -48
- package/src/graph-messages.actions.test.ts +0 -243
- package/src/graph-messages.read.test.ts +0 -391
- package/src/graph-messages.search.test.ts +0 -213
- package/src/graph-messages.test-helpers.ts +0 -50
- package/src/graph-messages.ts +0 -534
- package/src/graph-teams.test.ts +0 -215
- package/src/graph-teams.ts +0 -114
- package/src/graph-thread.test.ts +0 -246
- package/src/graph-thread.ts +0 -146
- package/src/graph-upload.test.ts +0 -258
- package/src/graph-upload.ts +0 -531
- package/src/graph-users.ts +0 -29
- package/src/graph.test.ts +0 -516
- package/src/graph.ts +0 -293
- package/src/inbound.test.ts +0 -221
- package/src/inbound.ts +0 -148
- package/src/index.ts +0 -4
- package/src/media-helpers.test.ts +0 -202
- package/src/media-helpers.ts +0 -105
- package/src/mentions.test.ts +0 -244
- package/src/mentions.ts +0 -114
- package/src/messenger.test.ts +0 -865
- package/src/messenger.ts +0 -605
- package/src/monitor-handler/access.ts +0 -125
- package/src/monitor-handler/inbound-media.test.ts +0 -289
- package/src/monitor-handler/inbound-media.ts +0 -180
- package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
- package/src/monitor-handler/message-handler.authz.test.ts +0 -669
- package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
- package/src/monitor-handler/message-handler.test-support.ts +0 -100
- package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -223
- package/src/monitor-handler/message-handler.thread-session.test.ts +0 -77
- package/src/monitor-handler/message-handler.ts +0 -1000
- package/src/monitor-handler/reaction-handler.test.ts +0 -267
- package/src/monitor-handler/reaction-handler.ts +0 -210
- package/src/monitor-handler/thread-session.ts +0 -17
- package/src/monitor-handler.adaptive-card.test.ts +0 -162
- package/src/monitor-handler.feedback-authz.test.ts +0 -314
- package/src/monitor-handler.file-consent.test.ts +0 -423
- package/src/monitor-handler.sso.test.ts +0 -563
- package/src/monitor-handler.test-helpers.ts +0 -180
- package/src/monitor-handler.ts +0 -534
- package/src/monitor-handler.types.ts +0 -27
- package/src/monitor-types.ts +0 -6
- package/src/monitor.lifecycle.test.ts +0 -278
- package/src/monitor.test.ts +0 -119
- package/src/monitor.ts +0 -442
- package/src/oauth.flow.ts +0 -77
- package/src/oauth.shared.ts +0 -37
- package/src/oauth.test.ts +0 -305
- package/src/oauth.token.ts +0 -158
- package/src/oauth.ts +0 -130
- package/src/outbound.test.ts +0 -130
- package/src/outbound.ts +0 -71
- package/src/pending-uploads-fs.test.ts +0 -246
- package/src/pending-uploads-fs.ts +0 -235
- package/src/pending-uploads.test.ts +0 -173
- package/src/pending-uploads.ts +0 -121
- package/src/policy.test.ts +0 -240
- package/src/policy.ts +0 -262
- package/src/polls-store-memory.ts +0 -32
- package/src/polls.test.ts +0 -160
- package/src/polls.ts +0 -323
- package/src/presentation.ts +0 -68
- package/src/probe.test.ts +0 -77
- package/src/probe.ts +0 -132
- package/src/reply-dispatcher.test.ts +0 -437
- package/src/reply-dispatcher.ts +0 -346
- package/src/reply-stream-controller.test.ts +0 -235
- package/src/reply-stream-controller.ts +0 -147
- package/src/resolve-allowlist.test.ts +0 -250
- package/src/resolve-allowlist.ts +0 -309
- package/src/revoked-context.ts +0 -17
- package/src/runtime.ts +0 -9
- package/src/sdk-types.ts +0 -59
- package/src/sdk.test.ts +0 -666
- package/src/sdk.ts +0 -884
- package/src/secret-contract.ts +0 -49
- package/src/secret-input.ts +0 -7
- package/src/send-context.ts +0 -231
- package/src/send.test.ts +0 -493
- package/src/send.ts +0 -637
- package/src/sent-message-cache.test.ts +0 -15
- package/src/sent-message-cache.ts +0 -56
- package/src/session-route.ts +0 -40
- package/src/setup-core.ts +0 -160
- package/src/setup-surface.test.ts +0 -202
- package/src/setup-surface.ts +0 -320
- package/src/sso-token-store.test.ts +0 -72
- package/src/sso-token-store.ts +0 -166
- package/src/sso.ts +0 -300
- package/src/storage.ts +0 -25
- package/src/store-fs.ts +0 -44
- package/src/streaming-message.test.ts +0 -262
- package/src/streaming-message.ts +0 -297
- package/src/test-runtime.ts +0 -16
- package/src/thread-parent-context.test.ts +0 -224
- package/src/thread-parent-context.ts +0 -159
- package/src/token-response.ts +0 -11
- package/src/token.test.ts +0 -259
- package/src/token.ts +0 -195
- package/src/user-agent.test.ts +0 -86
- package/src/user-agent.ts +0 -53
- package/src/webhook-timeouts.ts +0 -27
- package/src/welcome-card.test.ts +0 -81
- package/src/welcome-card.ts +0 -57
- package/test-api.ts +0 -1
- package/tsconfig.json +0 -16
|
@@ -1,1000 +0,0 @@
|
|
|
1
|
-
import { formatAllowlistMatchMeta } from "openclaw/plugin-sdk/allow-from";
|
|
2
|
-
import { resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
|
|
3
|
-
import {
|
|
4
|
-
logInboundDrop,
|
|
5
|
-
resolveInboundSessionEnvelopeContext,
|
|
6
|
-
} from "openclaw/plugin-sdk/channel-inbound";
|
|
7
|
-
import { resolveDualTextControlCommandGate } from "openclaw/plugin-sdk/command-gating";
|
|
8
|
-
import {
|
|
9
|
-
filterSupplementalContextItems,
|
|
10
|
-
resolveChannelContextVisibilityMode,
|
|
11
|
-
shouldIncludeSupplementalContext,
|
|
12
|
-
} from "openclaw/plugin-sdk/context-visibility-runtime";
|
|
13
|
-
import { evaluateSenderGroupAccessForPolicy } from "openclaw/plugin-sdk/group-access";
|
|
14
|
-
import {
|
|
15
|
-
dispatchReplyFromConfigWithSettledDispatcher,
|
|
16
|
-
hasFinalInboundReplyDispatch,
|
|
17
|
-
resolveInboundReplyDispatchCounts,
|
|
18
|
-
} from "openclaw/plugin-sdk/inbound-reply-dispatch";
|
|
19
|
-
import {
|
|
20
|
-
buildPendingHistoryContextFromMap,
|
|
21
|
-
DEFAULT_GROUP_HISTORY_LIMIT,
|
|
22
|
-
recordPendingHistoryEntryIfEnabled,
|
|
23
|
-
type HistoryEntry,
|
|
24
|
-
} from "openclaw/plugin-sdk/reply-history";
|
|
25
|
-
import {
|
|
26
|
-
buildMSTeamsAttachmentPlaceholder,
|
|
27
|
-
buildMSTeamsMediaPayload,
|
|
28
|
-
type MSTeamsAttachmentLike,
|
|
29
|
-
summarizeMSTeamsHtmlAttachments,
|
|
30
|
-
} from "../attachments.js";
|
|
31
|
-
import { isRecord } from "../attachments/shared.js";
|
|
32
|
-
import type { StoredConversationReference } from "../conversation-store.js";
|
|
33
|
-
import { formatUnknownError } from "../errors.js";
|
|
34
|
-
import {
|
|
35
|
-
fetchThreadReplies,
|
|
36
|
-
formatThreadContext,
|
|
37
|
-
resolveTeamGroupId,
|
|
38
|
-
type GraphThreadMessage,
|
|
39
|
-
} from "../graph-thread.js";
|
|
40
|
-
import { resolveGraphChatId } from "../graph-upload.js";
|
|
41
|
-
import {
|
|
42
|
-
extractMSTeamsConversationMessageId,
|
|
43
|
-
extractMSTeamsQuoteInfo,
|
|
44
|
-
normalizeMSTeamsConversationId,
|
|
45
|
-
parseMSTeamsActivityTimestamp,
|
|
46
|
-
stripMSTeamsMentionTags,
|
|
47
|
-
translateMSTeamsDmConversationIdForGraph,
|
|
48
|
-
wasMSTeamsBotMentioned,
|
|
49
|
-
} from "../inbound.js";
|
|
50
|
-
import {
|
|
51
|
-
fetchParentMessageCached,
|
|
52
|
-
formatParentContextEvent,
|
|
53
|
-
markParentContextInjected,
|
|
54
|
-
shouldInjectParentContext,
|
|
55
|
-
summarizeParentMessage,
|
|
56
|
-
} from "../thread-parent-context.js";
|
|
57
|
-
|
|
58
|
-
function extractTextFromHtmlAttachments(attachments: MSTeamsAttachmentLike[]): string {
|
|
59
|
-
for (const attachment of attachments) {
|
|
60
|
-
if (attachment.contentType !== "text/html") {
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
const content = attachment.content;
|
|
64
|
-
const raw =
|
|
65
|
-
typeof content === "string"
|
|
66
|
-
? content
|
|
67
|
-
: isRecord(content) && typeof content.text === "string"
|
|
68
|
-
? content.text
|
|
69
|
-
: isRecord(content) && typeof content.body === "string"
|
|
70
|
-
? content.body
|
|
71
|
-
: "";
|
|
72
|
-
if (!raw) {
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
const text = raw
|
|
76
|
-
.replace(/<at[^>]*>.*?<\/at>/gis, " ")
|
|
77
|
-
.replace(/<a\b[^>]*href=["']([^"']+)["'][^>]*>(.*?)<\/a>/gis, "$2 $1")
|
|
78
|
-
.replace(/<br\s*\/?>/gi, "\n")
|
|
79
|
-
.replace(/<\/p>/gi, "\n")
|
|
80
|
-
.replace(/<[^>]+>/g, " ")
|
|
81
|
-
.replace(/ /gi, " ")
|
|
82
|
-
.replace(/&/gi, "&")
|
|
83
|
-
.replace(/\s+/g, " ")
|
|
84
|
-
.trim();
|
|
85
|
-
if (text) {
|
|
86
|
-
return text;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
return "";
|
|
90
|
-
}
|
|
91
|
-
import type { MSTeamsMessageHandlerDeps } from "../monitor-handler.types.js";
|
|
92
|
-
import {
|
|
93
|
-
isMSTeamsGroupAllowed,
|
|
94
|
-
resolveMSTeamsAllowlistMatch,
|
|
95
|
-
resolveMSTeamsReplyPolicy,
|
|
96
|
-
} from "../policy.js";
|
|
97
|
-
import { extractMSTeamsPollVote } from "../polls.js";
|
|
98
|
-
import { createMSTeamsReplyDispatcher } from "../reply-dispatcher.js";
|
|
99
|
-
import { getMSTeamsRuntime } from "../runtime.js";
|
|
100
|
-
import type { MSTeamsTurnContext } from "../sdk-types.js";
|
|
101
|
-
import { recordMSTeamsSentMessage, wasMSTeamsMessageSent } from "../sent-message-cache.js";
|
|
102
|
-
import { resolveMSTeamsSenderAccess } from "./access.js";
|
|
103
|
-
import { resolveMSTeamsInboundMedia } from "./inbound-media.js";
|
|
104
|
-
import { resolveMSTeamsRouteSessionKey } from "./thread-session.js";
|
|
105
|
-
|
|
106
|
-
function buildStoredConversationReference(params: {
|
|
107
|
-
activity: MSTeamsTurnContext["activity"];
|
|
108
|
-
conversationId: string;
|
|
109
|
-
conversationType: string;
|
|
110
|
-
teamId?: string;
|
|
111
|
-
/** Thread root message ID for channel thread messages. */
|
|
112
|
-
threadId?: string;
|
|
113
|
-
}): StoredConversationReference {
|
|
114
|
-
const { activity, conversationId, conversationType, teamId, threadId } = params;
|
|
115
|
-
const from = activity.from;
|
|
116
|
-
const conversation = activity.conversation;
|
|
117
|
-
const agent = activity.recipient;
|
|
118
|
-
const clientInfo = activity.entities?.find((e) => e.type === "clientInfo") as
|
|
119
|
-
| { timezone?: string }
|
|
120
|
-
| undefined;
|
|
121
|
-
// Bot Framework requires `tenantId` on outbound proactive activities so the
|
|
122
|
-
// connector can route them to the correct Azure AD tenant; missing it causes
|
|
123
|
-
// HTTP 403. Channel activities often leave `conversation.tenantId` unset, so
|
|
124
|
-
// prefer the canonical `channelData.tenant.id` source when available.
|
|
125
|
-
const channelDataTenantId = activity.channelData?.tenant?.id;
|
|
126
|
-
const tenantId = channelDataTenantId ?? conversation?.tenantId;
|
|
127
|
-
const aadObjectId = from?.aadObjectId;
|
|
128
|
-
return {
|
|
129
|
-
activityId: activity.id,
|
|
130
|
-
user: from ? { id: from.id, name: from.name, aadObjectId: from.aadObjectId } : undefined,
|
|
131
|
-
agent,
|
|
132
|
-
bot: agent ? { id: agent.id, name: agent.name } : undefined,
|
|
133
|
-
conversation: {
|
|
134
|
-
id: conversationId,
|
|
135
|
-
conversationType,
|
|
136
|
-
tenantId,
|
|
137
|
-
},
|
|
138
|
-
...(tenantId ? { tenantId } : {}),
|
|
139
|
-
...(aadObjectId ? { aadObjectId } : {}),
|
|
140
|
-
teamId,
|
|
141
|
-
channelId: activity.channelId,
|
|
142
|
-
serviceUrl: activity.serviceUrl,
|
|
143
|
-
locale: activity.locale,
|
|
144
|
-
...(clientInfo?.timezone ? { timezone: clientInfo.timezone } : {}),
|
|
145
|
-
...(threadId ? { threadId } : {}),
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export function createMSTeamsMessageHandler(deps: MSTeamsMessageHandlerDeps) {
|
|
150
|
-
const {
|
|
151
|
-
cfg,
|
|
152
|
-
runtime,
|
|
153
|
-
appId,
|
|
154
|
-
adapter,
|
|
155
|
-
tokenProvider,
|
|
156
|
-
textLimit,
|
|
157
|
-
mediaMaxBytes,
|
|
158
|
-
conversationStore,
|
|
159
|
-
pollStore,
|
|
160
|
-
log,
|
|
161
|
-
} = deps;
|
|
162
|
-
const core = getMSTeamsRuntime();
|
|
163
|
-
const logVerboseMessage = (message: string) => {
|
|
164
|
-
if (core.logging.shouldLogVerbose()) {
|
|
165
|
-
log.debug?.(message);
|
|
166
|
-
}
|
|
167
|
-
};
|
|
168
|
-
const msteamsCfg = cfg.channels?.msteams;
|
|
169
|
-
const contextVisibilityMode = resolveChannelContextVisibilityMode({
|
|
170
|
-
cfg,
|
|
171
|
-
channel: "msteams",
|
|
172
|
-
});
|
|
173
|
-
const historyLimit = Math.max(
|
|
174
|
-
0,
|
|
175
|
-
msteamsCfg?.historyLimit ??
|
|
176
|
-
cfg.messages?.groupChat?.historyLimit ??
|
|
177
|
-
DEFAULT_GROUP_HISTORY_LIMIT,
|
|
178
|
-
);
|
|
179
|
-
const conversationHistories = new Map<string, HistoryEntry[]>();
|
|
180
|
-
const inboundDebounceMs = core.channel.debounce.resolveInboundDebounceMs({
|
|
181
|
-
cfg,
|
|
182
|
-
channel: "msteams",
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
type MSTeamsDebounceEntry = {
|
|
186
|
-
context: MSTeamsTurnContext;
|
|
187
|
-
rawText: string;
|
|
188
|
-
text: string;
|
|
189
|
-
attachments: MSTeamsAttachmentLike[];
|
|
190
|
-
wasMentioned: boolean;
|
|
191
|
-
implicitMentionKinds: Array<"reply_to_bot">;
|
|
192
|
-
};
|
|
193
|
-
|
|
194
|
-
const handleTeamsMessageNow = async (params: MSTeamsDebounceEntry) => {
|
|
195
|
-
const context = params.context;
|
|
196
|
-
const activity = context.activity;
|
|
197
|
-
const rawText = params.rawText;
|
|
198
|
-
const text = params.text;
|
|
199
|
-
const attachments = params.attachments;
|
|
200
|
-
const attachmentPlaceholder = buildMSTeamsAttachmentPlaceholder(attachments, {
|
|
201
|
-
maxInlineBytes: mediaMaxBytes,
|
|
202
|
-
maxInlineTotalBytes: mediaMaxBytes,
|
|
203
|
-
});
|
|
204
|
-
const rawBody = text || attachmentPlaceholder;
|
|
205
|
-
const quoteInfo = extractMSTeamsQuoteInfo(attachments);
|
|
206
|
-
let quoteSenderId: string | undefined;
|
|
207
|
-
let quoteSenderName: string | undefined;
|
|
208
|
-
const from = activity.from;
|
|
209
|
-
const conversation = activity.conversation;
|
|
210
|
-
|
|
211
|
-
const attachmentTypes = attachments
|
|
212
|
-
.map((att) => (typeof att.contentType === "string" ? att.contentType : undefined))
|
|
213
|
-
.filter(Boolean)
|
|
214
|
-
.slice(0, 3);
|
|
215
|
-
const htmlSummary = summarizeMSTeamsHtmlAttachments(attachments);
|
|
216
|
-
|
|
217
|
-
log.info("received message", {
|
|
218
|
-
rawText: rawText.slice(0, 50),
|
|
219
|
-
text: text.slice(0, 50),
|
|
220
|
-
attachments: attachments.length,
|
|
221
|
-
attachmentTypes,
|
|
222
|
-
from: from?.id,
|
|
223
|
-
conversation: conversation?.id,
|
|
224
|
-
});
|
|
225
|
-
if (htmlSummary) {
|
|
226
|
-
log.debug?.("html attachment summary", htmlSummary);
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
if (!from?.id) {
|
|
230
|
-
log.debug?.("skipping message without from.id");
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Teams conversation.id may include ";messageid=..." suffix - strip it for session key.
|
|
235
|
-
const rawConversationId = conversation?.id ?? "";
|
|
236
|
-
const conversationId = normalizeMSTeamsConversationId(rawConversationId);
|
|
237
|
-
const conversationMessageId = extractMSTeamsConversationMessageId(rawConversationId);
|
|
238
|
-
const conversationType = conversation?.conversationType ?? "personal";
|
|
239
|
-
const teamId = activity.channelData?.team?.id;
|
|
240
|
-
// For channel thread messages, resolve the thread root message ID so outbound
|
|
241
|
-
// replies land in the correct thread. The root ID comes from the `messageid=`
|
|
242
|
-
// portion of conversation.id (preferred) or from activity.replyToId.
|
|
243
|
-
const threadId =
|
|
244
|
-
conversationType === "channel"
|
|
245
|
-
? (conversationMessageId ?? activity.replyToId ?? undefined)
|
|
246
|
-
: undefined;
|
|
247
|
-
const conversationRef = buildStoredConversationReference({
|
|
248
|
-
activity,
|
|
249
|
-
conversationId,
|
|
250
|
-
conversationType,
|
|
251
|
-
teamId,
|
|
252
|
-
threadId,
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
const {
|
|
256
|
-
dmPolicy,
|
|
257
|
-
senderId,
|
|
258
|
-
senderName,
|
|
259
|
-
pairing,
|
|
260
|
-
isDirectMessage,
|
|
261
|
-
channelGate,
|
|
262
|
-
access,
|
|
263
|
-
configuredDmAllowFrom,
|
|
264
|
-
effectiveDmAllowFrom,
|
|
265
|
-
effectiveGroupAllowFrom,
|
|
266
|
-
allowNameMatching,
|
|
267
|
-
groupPolicy,
|
|
268
|
-
} = await resolveMSTeamsSenderAccess({
|
|
269
|
-
cfg,
|
|
270
|
-
activity,
|
|
271
|
-
});
|
|
272
|
-
const useAccessGroups = cfg.commands?.useAccessGroups !== false;
|
|
273
|
-
const isChannel = conversationType === "channel";
|
|
274
|
-
|
|
275
|
-
if (isDirectMessage && msteamsCfg && access.decision !== "allow") {
|
|
276
|
-
if (access.reason === "dmPolicy=disabled") {
|
|
277
|
-
log.info("dropping dm (dms disabled)", {
|
|
278
|
-
sender: senderId,
|
|
279
|
-
label: senderName,
|
|
280
|
-
});
|
|
281
|
-
log.debug?.("dropping dm (dms disabled)");
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
const allowMatch = resolveMSTeamsAllowlistMatch({
|
|
285
|
-
allowFrom: effectiveDmAllowFrom,
|
|
286
|
-
senderId,
|
|
287
|
-
senderName,
|
|
288
|
-
allowNameMatching,
|
|
289
|
-
});
|
|
290
|
-
if (access.decision === "pairing") {
|
|
291
|
-
conversationStore.upsert(conversationId, conversationRef).catch((err) => {
|
|
292
|
-
log.debug?.("failed to save conversation reference", {
|
|
293
|
-
error: formatUnknownError(err),
|
|
294
|
-
});
|
|
295
|
-
});
|
|
296
|
-
const request = await pairing.upsertPairingRequest({
|
|
297
|
-
id: senderId,
|
|
298
|
-
meta: { name: senderName },
|
|
299
|
-
});
|
|
300
|
-
if (request) {
|
|
301
|
-
log.info("msteams pairing request created", {
|
|
302
|
-
sender: senderId,
|
|
303
|
-
label: senderName,
|
|
304
|
-
});
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
log.debug?.("dropping dm (not allowlisted)", {
|
|
308
|
-
sender: senderId,
|
|
309
|
-
label: senderName,
|
|
310
|
-
allowlistMatch: formatAllowlistMatchMeta(allowMatch),
|
|
311
|
-
});
|
|
312
|
-
log.info("dropping dm (not allowlisted)", {
|
|
313
|
-
sender: senderId,
|
|
314
|
-
label: senderName,
|
|
315
|
-
dmPolicy,
|
|
316
|
-
reason: access.reason,
|
|
317
|
-
allowlistMatch: formatAllowlistMatchMeta(allowMatch),
|
|
318
|
-
});
|
|
319
|
-
return;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
if (!isDirectMessage && msteamsCfg) {
|
|
323
|
-
if (channelGate.allowlistConfigured && !channelGate.allowed) {
|
|
324
|
-
log.info("dropping group message (not in team/channel allowlist)", {
|
|
325
|
-
conversationId,
|
|
326
|
-
teamKey: channelGate.teamKey ?? "none",
|
|
327
|
-
channelKey: channelGate.channelKey ?? "none",
|
|
328
|
-
channelMatchKey: channelGate.channelMatchKey ?? "none",
|
|
329
|
-
channelMatchSource: channelGate.channelMatchSource ?? "none",
|
|
330
|
-
});
|
|
331
|
-
log.debug?.("dropping group message (not in team/channel allowlist)", {
|
|
332
|
-
conversationId,
|
|
333
|
-
teamKey: channelGate.teamKey ?? "none",
|
|
334
|
-
channelKey: channelGate.channelKey ?? "none",
|
|
335
|
-
channelMatchKey: channelGate.channelMatchKey ?? "none",
|
|
336
|
-
channelMatchSource: channelGate.channelMatchSource ?? "none",
|
|
337
|
-
});
|
|
338
|
-
return;
|
|
339
|
-
}
|
|
340
|
-
const senderGroupAccess = evaluateSenderGroupAccessForPolicy({
|
|
341
|
-
groupPolicy,
|
|
342
|
-
groupAllowFrom: effectiveGroupAllowFrom,
|
|
343
|
-
senderId,
|
|
344
|
-
isSenderAllowed: (_senderId, allowFrom) =>
|
|
345
|
-
resolveMSTeamsAllowlistMatch({
|
|
346
|
-
allowFrom,
|
|
347
|
-
senderId,
|
|
348
|
-
senderName,
|
|
349
|
-
allowNameMatching,
|
|
350
|
-
}).allowed,
|
|
351
|
-
});
|
|
352
|
-
|
|
353
|
-
if (!senderGroupAccess.allowed && senderGroupAccess.reason === "disabled") {
|
|
354
|
-
log.info("dropping group message (groupPolicy: disabled)", {
|
|
355
|
-
conversationId,
|
|
356
|
-
});
|
|
357
|
-
log.debug?.("dropping group message (groupPolicy: disabled)", {
|
|
358
|
-
conversationId,
|
|
359
|
-
});
|
|
360
|
-
return;
|
|
361
|
-
}
|
|
362
|
-
if (!senderGroupAccess.allowed && senderGroupAccess.reason === "empty_allowlist") {
|
|
363
|
-
log.info("dropping group message (groupPolicy: allowlist, no allowlist)", {
|
|
364
|
-
conversationId,
|
|
365
|
-
});
|
|
366
|
-
log.debug?.("dropping group message (groupPolicy: allowlist, no allowlist)", {
|
|
367
|
-
conversationId,
|
|
368
|
-
});
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
if (!senderGroupAccess.allowed && senderGroupAccess.reason === "sender_not_allowlisted") {
|
|
372
|
-
const allowMatch = resolveMSTeamsAllowlistMatch({
|
|
373
|
-
allowFrom: effectiveGroupAllowFrom,
|
|
374
|
-
senderId,
|
|
375
|
-
senderName,
|
|
376
|
-
allowNameMatching,
|
|
377
|
-
});
|
|
378
|
-
log.debug?.("dropping group message (not in groupAllowFrom)", {
|
|
379
|
-
sender: senderId,
|
|
380
|
-
label: senderName,
|
|
381
|
-
allowlistMatch: formatAllowlistMatchMeta(allowMatch),
|
|
382
|
-
});
|
|
383
|
-
log.info("dropping group message (not in groupAllowFrom)", {
|
|
384
|
-
sender: senderId,
|
|
385
|
-
label: senderName,
|
|
386
|
-
allowlistMatch: formatAllowlistMatchMeta(allowMatch),
|
|
387
|
-
});
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
const commandDmAllowFrom = isDirectMessage ? effectiveDmAllowFrom : configuredDmAllowFrom;
|
|
393
|
-
const ownerAllowedForCommands = isMSTeamsGroupAllowed({
|
|
394
|
-
groupPolicy: "allowlist",
|
|
395
|
-
allowFrom: commandDmAllowFrom,
|
|
396
|
-
senderId,
|
|
397
|
-
senderName,
|
|
398
|
-
allowNameMatching,
|
|
399
|
-
});
|
|
400
|
-
const groupAllowedForCommands = isMSTeamsGroupAllowed({
|
|
401
|
-
groupPolicy: "allowlist",
|
|
402
|
-
allowFrom: effectiveGroupAllowFrom,
|
|
403
|
-
senderId,
|
|
404
|
-
senderName,
|
|
405
|
-
allowNameMatching,
|
|
406
|
-
});
|
|
407
|
-
const { commandAuthorized, shouldBlock } = resolveDualTextControlCommandGate({
|
|
408
|
-
useAccessGroups,
|
|
409
|
-
primaryConfigured: commandDmAllowFrom.length > 0,
|
|
410
|
-
primaryAllowed: ownerAllowedForCommands,
|
|
411
|
-
secondaryConfigured: effectiveGroupAllowFrom.length > 0,
|
|
412
|
-
secondaryAllowed: groupAllowedForCommands,
|
|
413
|
-
hasControlCommand: core.channel.text.hasControlCommand(text, cfg),
|
|
414
|
-
});
|
|
415
|
-
if (shouldBlock) {
|
|
416
|
-
logInboundDrop({
|
|
417
|
-
log: logVerboseMessage,
|
|
418
|
-
channel: "msteams",
|
|
419
|
-
reason: "control command (unauthorized)",
|
|
420
|
-
target: senderId,
|
|
421
|
-
});
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
conversationStore.upsert(conversationId, conversationRef).catch((err) => {
|
|
426
|
-
log.debug?.("failed to save conversation reference", {
|
|
427
|
-
error: formatUnknownError(err),
|
|
428
|
-
});
|
|
429
|
-
});
|
|
430
|
-
|
|
431
|
-
const pollVote = extractMSTeamsPollVote(activity);
|
|
432
|
-
if (pollVote) {
|
|
433
|
-
try {
|
|
434
|
-
const poll = await pollStore.recordVote({
|
|
435
|
-
pollId: pollVote.pollId,
|
|
436
|
-
voterId: senderId,
|
|
437
|
-
selections: pollVote.selections,
|
|
438
|
-
});
|
|
439
|
-
if (!poll) {
|
|
440
|
-
log.debug?.("poll vote ignored (poll not found)", {
|
|
441
|
-
pollId: pollVote.pollId,
|
|
442
|
-
});
|
|
443
|
-
} else {
|
|
444
|
-
log.info("recorded poll vote", {
|
|
445
|
-
pollId: pollVote.pollId,
|
|
446
|
-
voter: senderId,
|
|
447
|
-
selections: pollVote.selections,
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
|
-
} catch (err) {
|
|
451
|
-
log.error("failed to record poll vote", {
|
|
452
|
-
pollId: pollVote.pollId,
|
|
453
|
-
error: formatUnknownError(err),
|
|
454
|
-
});
|
|
455
|
-
}
|
|
456
|
-
return;
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
if (!rawBody) {
|
|
460
|
-
log.debug?.("skipping empty message after stripping mentions");
|
|
461
|
-
return;
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
const teamsFrom = isDirectMessage
|
|
465
|
-
? `msteams:${senderId}`
|
|
466
|
-
: isChannel
|
|
467
|
-
? `msteams:channel:${conversationId}`
|
|
468
|
-
: `msteams:group:${conversationId}`;
|
|
469
|
-
const teamsTo = isDirectMessage ? `user:${senderId}` : `conversation:${conversationId}`;
|
|
470
|
-
|
|
471
|
-
const route = core.channel.routing.resolveAgentRoute({
|
|
472
|
-
cfg,
|
|
473
|
-
channel: "msteams",
|
|
474
|
-
teamId,
|
|
475
|
-
peer: {
|
|
476
|
-
kind: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
|
|
477
|
-
id: isDirectMessage ? senderId : conversationId,
|
|
478
|
-
},
|
|
479
|
-
});
|
|
480
|
-
|
|
481
|
-
// Isolate channel thread sessions: each thread gets its own session key so
|
|
482
|
-
// context does not bleed across threads. Prefer conversationMessageId (the
|
|
483
|
-
// ;messageid= portion of conversation.id, i.e. the thread root) over
|
|
484
|
-
// activity.replyToId (which may point to a non-root parent in deep threads).
|
|
485
|
-
// DMs and group chats are unaffected — only channel thread replies fork.
|
|
486
|
-
route.sessionKey = resolveMSTeamsRouteSessionKey({
|
|
487
|
-
baseSessionKey: route.sessionKey,
|
|
488
|
-
isChannel,
|
|
489
|
-
conversationMessageId,
|
|
490
|
-
replyToId: activity.replyToId,
|
|
491
|
-
});
|
|
492
|
-
|
|
493
|
-
const preview = rawBody.replace(/\s+/g, " ").slice(0, 160);
|
|
494
|
-
const inboundLabel = isDirectMessage
|
|
495
|
-
? `Teams DM from ${senderName}`
|
|
496
|
-
: `Teams message in ${conversationType} from ${senderName}`;
|
|
497
|
-
|
|
498
|
-
core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, {
|
|
499
|
-
sessionKey: route.sessionKey,
|
|
500
|
-
contextKey: `msteams:message:${conversationId}:${activity.id ?? "unknown"}`,
|
|
501
|
-
});
|
|
502
|
-
|
|
503
|
-
const channelId = conversationId;
|
|
504
|
-
const { teamConfig, channelConfig } = channelGate;
|
|
505
|
-
const { requireMention, replyStyle } = resolveMSTeamsReplyPolicy({
|
|
506
|
-
isDirectMessage,
|
|
507
|
-
globalConfig: msteamsCfg,
|
|
508
|
-
teamConfig,
|
|
509
|
-
channelConfig,
|
|
510
|
-
});
|
|
511
|
-
const timestamp = parseMSTeamsActivityTimestamp(activity.timestamp);
|
|
512
|
-
const mentionDecision = resolveInboundMentionDecision({
|
|
513
|
-
facts: {
|
|
514
|
-
canDetectMention: true,
|
|
515
|
-
wasMentioned: params.wasMentioned,
|
|
516
|
-
implicitMentionKinds: params.implicitMentionKinds,
|
|
517
|
-
},
|
|
518
|
-
policy: {
|
|
519
|
-
isGroup: !isDirectMessage,
|
|
520
|
-
requireMention,
|
|
521
|
-
allowTextCommands: false,
|
|
522
|
-
hasControlCommand: false,
|
|
523
|
-
commandAuthorized: false,
|
|
524
|
-
},
|
|
525
|
-
});
|
|
526
|
-
|
|
527
|
-
if (!isDirectMessage) {
|
|
528
|
-
const mentioned = mentionDecision.effectiveWasMentioned;
|
|
529
|
-
if (requireMention && mentionDecision.shouldSkip) {
|
|
530
|
-
log.debug?.("skipping message (mention required)", {
|
|
531
|
-
teamId,
|
|
532
|
-
channelId,
|
|
533
|
-
requireMention,
|
|
534
|
-
mentioned,
|
|
535
|
-
});
|
|
536
|
-
recordPendingHistoryEntryIfEnabled({
|
|
537
|
-
historyMap: conversationHistories,
|
|
538
|
-
historyKey: conversationId,
|
|
539
|
-
limit: historyLimit,
|
|
540
|
-
entry: {
|
|
541
|
-
sender: senderName,
|
|
542
|
-
body: rawBody,
|
|
543
|
-
timestamp: timestamp?.getTime(),
|
|
544
|
-
messageId: activity.id ?? undefined,
|
|
545
|
-
},
|
|
546
|
-
});
|
|
547
|
-
return;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
let graphConversationId = translateMSTeamsDmConversationIdForGraph({
|
|
551
|
-
isDirectMessage,
|
|
552
|
-
conversationId,
|
|
553
|
-
aadObjectId: from.aadObjectId,
|
|
554
|
-
appId,
|
|
555
|
-
});
|
|
556
|
-
|
|
557
|
-
// For personal DMs the Bot Framework conversation ID (`a:...`) and the
|
|
558
|
-
// synthetic `19:{userId}_{appId}@unq.gbl.spaces` format produced by
|
|
559
|
-
// translateMSTeamsDmConversationIdForGraph are not always accepted by the
|
|
560
|
-
// Graph `/chats/{chatId}/messages` endpoint. Resolve the real Graph chat
|
|
561
|
-
// ID via the API (with conversation store caching) so the Graph media
|
|
562
|
-
// download fallback works when the direct Bot Framework download fails.
|
|
563
|
-
if (isDirectMessage && conversationId.startsWith("a:")) {
|
|
564
|
-
const cached = await conversationStore.get(conversationId);
|
|
565
|
-
if (cached?.graphChatId) {
|
|
566
|
-
graphConversationId = cached.graphChatId;
|
|
567
|
-
} else {
|
|
568
|
-
try {
|
|
569
|
-
const resolved = await resolveGraphChatId({
|
|
570
|
-
botFrameworkConversationId: conversationId,
|
|
571
|
-
userAadObjectId: from.aadObjectId ?? undefined,
|
|
572
|
-
tokenProvider,
|
|
573
|
-
});
|
|
574
|
-
if (resolved) {
|
|
575
|
-
graphConversationId = resolved;
|
|
576
|
-
conversationStore
|
|
577
|
-
.upsert(conversationId, { ...conversationRef, graphChatId: resolved })
|
|
578
|
-
.catch(() => {});
|
|
579
|
-
}
|
|
580
|
-
} catch {
|
|
581
|
-
log.debug?.("failed to resolve Graph chat ID for inbound media", { conversationId });
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
const mediaList = await resolveMSTeamsInboundMedia({
|
|
587
|
-
attachments,
|
|
588
|
-
htmlSummary: htmlSummary ?? undefined,
|
|
589
|
-
maxBytes: mediaMaxBytes,
|
|
590
|
-
tokenProvider,
|
|
591
|
-
allowHosts: msteamsCfg?.mediaAllowHosts,
|
|
592
|
-
authAllowHosts: msteamsCfg?.mediaAuthAllowHosts,
|
|
593
|
-
conversationType,
|
|
594
|
-
conversationId: graphConversationId,
|
|
595
|
-
conversationMessageId: conversationMessageId ?? undefined,
|
|
596
|
-
serviceUrl: activity.serviceUrl,
|
|
597
|
-
activity: {
|
|
598
|
-
id: activity.id,
|
|
599
|
-
replyToId: activity.replyToId,
|
|
600
|
-
channelData: activity.channelData,
|
|
601
|
-
},
|
|
602
|
-
log,
|
|
603
|
-
preserveFilenames: (cfg as { media?: { preserveFilenames?: boolean } }).media
|
|
604
|
-
?.preserveFilenames,
|
|
605
|
-
});
|
|
606
|
-
|
|
607
|
-
const mediaPayload = buildMSTeamsMediaPayload(mediaList);
|
|
608
|
-
|
|
609
|
-
// Fetch thread history when the message is a reply inside a Teams channel thread.
|
|
610
|
-
// This is a best-effort enhancement; errors are logged and do not block the reply.
|
|
611
|
-
//
|
|
612
|
-
// We also enqueue a compact `Replying to @sender: …` system event when the parent
|
|
613
|
-
// is resolvable. On brand-new thread sessions (see PR #62713), this gives the agent
|
|
614
|
-
// immediate parent context even before the fuller `[Thread history]` block is assembled.
|
|
615
|
-
// Parent fetches are cached (5 min LRU, 100 entries) and per-session deduped so
|
|
616
|
-
// consecutive replies in the same thread do not re-inject identical context.
|
|
617
|
-
let threadContext: string | undefined;
|
|
618
|
-
if (activity.replyToId && isChannel && teamId) {
|
|
619
|
-
try {
|
|
620
|
-
const graphToken = await tokenProvider.getAccessToken("https://graph.microsoft.com");
|
|
621
|
-
const groupId = await resolveTeamGroupId(graphToken, teamId);
|
|
622
|
-
// Use allSettled so a failure in one fetch does not discard the other.
|
|
623
|
-
// For example, reply-fetch 403 should not throw away a successful parent fetch.
|
|
624
|
-
const [parentResult, repliesResult] = await Promise.allSettled([
|
|
625
|
-
fetchParentMessageCached(graphToken, groupId, conversationId, activity.replyToId),
|
|
626
|
-
fetchThreadReplies(graphToken, groupId, conversationId, activity.replyToId),
|
|
627
|
-
]);
|
|
628
|
-
const parentMsg = parentResult.status === "fulfilled" ? parentResult.value : undefined;
|
|
629
|
-
const replies = repliesResult.status === "fulfilled" ? repliesResult.value : [];
|
|
630
|
-
if (parentResult.status === "rejected") {
|
|
631
|
-
log.debug?.("failed to fetch parent message", {
|
|
632
|
-
error: formatUnknownError(parentResult.reason),
|
|
633
|
-
});
|
|
634
|
-
}
|
|
635
|
-
if (repliesResult.status === "rejected") {
|
|
636
|
-
log.debug?.("failed to fetch thread replies", {
|
|
637
|
-
error: formatUnknownError(repliesResult.reason),
|
|
638
|
-
});
|
|
639
|
-
}
|
|
640
|
-
const isThreadSenderAllowed = (msg: GraphThreadMessage) =>
|
|
641
|
-
groupPolicy === "allowlist"
|
|
642
|
-
? resolveMSTeamsAllowlistMatch({
|
|
643
|
-
allowFrom: effectiveGroupAllowFrom,
|
|
644
|
-
senderId: msg.from?.user?.id ?? "",
|
|
645
|
-
senderName: msg.from?.user?.displayName,
|
|
646
|
-
allowNameMatching,
|
|
647
|
-
}).allowed
|
|
648
|
-
: true;
|
|
649
|
-
const parentSummary = summarizeParentMessage(parentMsg);
|
|
650
|
-
const visibleParentMessages = parentMsg
|
|
651
|
-
? filterSupplementalContextItems({
|
|
652
|
-
items: [parentMsg],
|
|
653
|
-
mode: contextVisibilityMode,
|
|
654
|
-
kind: "thread",
|
|
655
|
-
isSenderAllowed: isThreadSenderAllowed,
|
|
656
|
-
}).items
|
|
657
|
-
: [];
|
|
658
|
-
if (
|
|
659
|
-
parentSummary &&
|
|
660
|
-
visibleParentMessages.length > 0 &&
|
|
661
|
-
shouldInjectParentContext(route.sessionKey, activity.replyToId)
|
|
662
|
-
) {
|
|
663
|
-
core.system.enqueueSystemEvent(formatParentContextEvent(parentSummary), {
|
|
664
|
-
sessionKey: route.sessionKey,
|
|
665
|
-
contextKey: `msteams:thread-parent:${conversationId}:${activity.replyToId}`,
|
|
666
|
-
});
|
|
667
|
-
markParentContextInjected(route.sessionKey, activity.replyToId);
|
|
668
|
-
}
|
|
669
|
-
const allMessages = parentMsg ? [parentMsg, ...replies] : replies;
|
|
670
|
-
quoteSenderId = parentMsg?.from?.user?.id ?? parentMsg?.from?.application?.id ?? undefined;
|
|
671
|
-
quoteSenderName =
|
|
672
|
-
parentMsg?.from?.user?.displayName ??
|
|
673
|
-
parentMsg?.from?.application?.displayName ??
|
|
674
|
-
quoteInfo?.sender;
|
|
675
|
-
const { items: threadMessages } = filterSupplementalContextItems({
|
|
676
|
-
items: allMessages,
|
|
677
|
-
mode: contextVisibilityMode,
|
|
678
|
-
kind: "thread",
|
|
679
|
-
isSenderAllowed: isThreadSenderAllowed,
|
|
680
|
-
});
|
|
681
|
-
const formatted = formatThreadContext(threadMessages, activity.id);
|
|
682
|
-
if (formatted) {
|
|
683
|
-
threadContext = formatted;
|
|
684
|
-
}
|
|
685
|
-
} catch (err) {
|
|
686
|
-
log.debug?.("failed to fetch thread history", { error: formatUnknownError(err) });
|
|
687
|
-
// Graceful degradation: thread history is an optional enhancement.
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
quoteSenderName ??= quoteInfo?.sender;
|
|
691
|
-
|
|
692
|
-
const envelopeFrom = isDirectMessage ? senderName : conversationType;
|
|
693
|
-
const { storePath, envelopeOptions, previousTimestamp } = resolveInboundSessionEnvelopeContext({
|
|
694
|
-
cfg,
|
|
695
|
-
agentId: route.agentId,
|
|
696
|
-
sessionKey: route.sessionKey,
|
|
697
|
-
});
|
|
698
|
-
const body = core.channel.reply.formatAgentEnvelope({
|
|
699
|
-
channel: "Teams",
|
|
700
|
-
from: envelopeFrom,
|
|
701
|
-
timestamp,
|
|
702
|
-
previousTimestamp,
|
|
703
|
-
envelope: envelopeOptions,
|
|
704
|
-
body: rawBody,
|
|
705
|
-
});
|
|
706
|
-
let combinedBody = body;
|
|
707
|
-
const isRoomish = !isDirectMessage;
|
|
708
|
-
const historyKey = isRoomish ? conversationId : undefined;
|
|
709
|
-
if (isRoomish && historyKey) {
|
|
710
|
-
combinedBody = buildPendingHistoryContextFromMap({
|
|
711
|
-
historyMap: conversationHistories,
|
|
712
|
-
historyKey,
|
|
713
|
-
limit: historyLimit,
|
|
714
|
-
currentMessage: combinedBody,
|
|
715
|
-
formatEntry: (entry) =>
|
|
716
|
-
core.channel.reply.formatAgentEnvelope({
|
|
717
|
-
channel: "Teams",
|
|
718
|
-
from: conversationType,
|
|
719
|
-
timestamp: entry.timestamp,
|
|
720
|
-
body: `${entry.sender}: ${entry.body}${entry.messageId ? ` [id:${entry.messageId}]` : ""}`,
|
|
721
|
-
envelope: envelopeOptions,
|
|
722
|
-
}),
|
|
723
|
-
});
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
const inboundHistory =
|
|
727
|
-
isRoomish && historyKey && historyLimit > 0
|
|
728
|
-
? (conversationHistories.get(historyKey) ?? []).map((entry) => ({
|
|
729
|
-
sender: entry.sender,
|
|
730
|
-
body: entry.body,
|
|
731
|
-
timestamp: entry.timestamp,
|
|
732
|
-
}))
|
|
733
|
-
: undefined;
|
|
734
|
-
const commandBody = text.trim();
|
|
735
|
-
const quoteSenderAllowed =
|
|
736
|
-
quoteInfo && quoteInfo.sender
|
|
737
|
-
? !isChannel || groupPolicy !== "allowlist"
|
|
738
|
-
? true
|
|
739
|
-
: resolveMSTeamsAllowlistMatch({
|
|
740
|
-
allowFrom: effectiveGroupAllowFrom,
|
|
741
|
-
senderId: quoteSenderId ?? "",
|
|
742
|
-
senderName: quoteSenderName,
|
|
743
|
-
allowNameMatching,
|
|
744
|
-
}).allowed
|
|
745
|
-
: true;
|
|
746
|
-
const includeQuoteContext =
|
|
747
|
-
quoteInfo &&
|
|
748
|
-
shouldIncludeSupplementalContext({
|
|
749
|
-
mode: contextVisibilityMode,
|
|
750
|
-
kind: "quote",
|
|
751
|
-
senderAllowed: quoteSenderAllowed,
|
|
752
|
-
});
|
|
753
|
-
|
|
754
|
-
// Prepend thread history to the agent body so the agent has full thread context.
|
|
755
|
-
const bodyForAgent = threadContext
|
|
756
|
-
? `[Thread history]\n${threadContext}\n[/Thread history]\n\n${rawBody}`
|
|
757
|
-
: rawBody;
|
|
758
|
-
|
|
759
|
-
// For Teams *channel* messages (not group chats / DMs), preserve the
|
|
760
|
-
// `teamId/channelId` pair on NativeChannelId so downstream action handlers
|
|
761
|
-
// can route through `/teams/{teamId}/channels/{channelId}` via Graph API.
|
|
762
|
-
// The bare conversation id (`19:...@thread.tacv2`) is insufficient on its
|
|
763
|
-
// own because channel Graph endpoints require the owning team id too.
|
|
764
|
-
const nativeChannelId = isChannel && teamId ? `${teamId}/${conversationId}` : undefined;
|
|
765
|
-
|
|
766
|
-
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
767
|
-
Body: combinedBody,
|
|
768
|
-
BodyForAgent: bodyForAgent,
|
|
769
|
-
InboundHistory: inboundHistory,
|
|
770
|
-
RawBody: rawBody,
|
|
771
|
-
CommandBody: commandBody,
|
|
772
|
-
BodyForCommands: commandBody,
|
|
773
|
-
From: teamsFrom,
|
|
774
|
-
To: teamsTo,
|
|
775
|
-
SessionKey: route.sessionKey,
|
|
776
|
-
AccountId: route.accountId,
|
|
777
|
-
ChatType: isDirectMessage ? "direct" : isChannel ? "channel" : "group",
|
|
778
|
-
ConversationLabel: envelopeFrom,
|
|
779
|
-
GroupSubject: !isDirectMessage ? conversationType : undefined,
|
|
780
|
-
GroupSpace: teamId,
|
|
781
|
-
SenderName: senderName,
|
|
782
|
-
SenderId: senderId,
|
|
783
|
-
Provider: "msteams" as const,
|
|
784
|
-
Surface: "msteams" as const,
|
|
785
|
-
MessageSid: activity.id,
|
|
786
|
-
Timestamp: timestamp?.getTime() ?? Date.now(),
|
|
787
|
-
WasMentioned: isDirectMessage || mentionDecision.effectiveWasMentioned,
|
|
788
|
-
CommandAuthorized: commandAuthorized,
|
|
789
|
-
OriginatingChannel: "msteams" as const,
|
|
790
|
-
OriginatingTo: teamsTo,
|
|
791
|
-
NativeChannelId: nativeChannelId,
|
|
792
|
-
ReplyToId: activity.replyToId ?? undefined,
|
|
793
|
-
ReplyToBody: includeQuoteContext ? quoteInfo?.body : undefined,
|
|
794
|
-
ReplyToSender: includeQuoteContext ? quoteInfo?.sender : undefined,
|
|
795
|
-
ReplyToIsQuote: quoteInfo ? true : undefined,
|
|
796
|
-
...mediaPayload,
|
|
797
|
-
});
|
|
798
|
-
|
|
799
|
-
logVerboseMessage(`msteams inbound: from=${ctxPayload.From} preview="${preview}"`);
|
|
800
|
-
|
|
801
|
-
const sharePointSiteId = msteamsCfg?.sharePointSiteId;
|
|
802
|
-
const { dispatcher, replyOptions, markDispatchIdle } = createMSTeamsReplyDispatcher({
|
|
803
|
-
cfg,
|
|
804
|
-
agentId: route.agentId,
|
|
805
|
-
sessionKey: route.sessionKey,
|
|
806
|
-
accountId: route.accountId,
|
|
807
|
-
runtime,
|
|
808
|
-
log,
|
|
809
|
-
adapter,
|
|
810
|
-
appId,
|
|
811
|
-
conversationRef,
|
|
812
|
-
context,
|
|
813
|
-
replyStyle,
|
|
814
|
-
textLimit,
|
|
815
|
-
onSentMessageIds: (ids) => {
|
|
816
|
-
for (const id of ids) {
|
|
817
|
-
recordMSTeamsSentMessage(conversationId, id);
|
|
818
|
-
}
|
|
819
|
-
},
|
|
820
|
-
tokenProvider,
|
|
821
|
-
sharePointSiteId,
|
|
822
|
-
});
|
|
823
|
-
|
|
824
|
-
// Use Teams clientInfo timezone if no explicit userTimezone is configured.
|
|
825
|
-
// This ensures the agent knows the sender's timezone for time-aware responses
|
|
826
|
-
// and proactive sends within the same session.
|
|
827
|
-
const activityClientInfo = activity.entities?.find((e) => e.type === "clientInfo") as
|
|
828
|
-
| { timezone?: string }
|
|
829
|
-
| undefined;
|
|
830
|
-
const senderTimezone = activityClientInfo?.timezone || conversationRef.timezone;
|
|
831
|
-
const configOverride =
|
|
832
|
-
senderTimezone && !cfg.agents?.defaults?.userTimezone
|
|
833
|
-
? {
|
|
834
|
-
agents: {
|
|
835
|
-
defaults: { ...cfg.agents?.defaults, userTimezone: senderTimezone },
|
|
836
|
-
},
|
|
837
|
-
}
|
|
838
|
-
: undefined;
|
|
839
|
-
|
|
840
|
-
log.info("dispatching to agent", { sessionKey: route.sessionKey });
|
|
841
|
-
try {
|
|
842
|
-
const turnResult = await core.channel.turn.run({
|
|
843
|
-
channel: "msteams",
|
|
844
|
-
accountId: route.accountId,
|
|
845
|
-
raw: context,
|
|
846
|
-
adapter: {
|
|
847
|
-
ingest: () => ({
|
|
848
|
-
id: activity.id ?? `${teamsFrom}:${Date.now()}`,
|
|
849
|
-
timestamp: timestamp?.getTime(),
|
|
850
|
-
rawText: rawBody,
|
|
851
|
-
textForAgent: bodyForAgent,
|
|
852
|
-
textForCommands: commandBody,
|
|
853
|
-
raw: activity,
|
|
854
|
-
}),
|
|
855
|
-
resolveTurn: () => ({
|
|
856
|
-
channel: "msteams",
|
|
857
|
-
accountId: route.accountId,
|
|
858
|
-
routeSessionKey: route.sessionKey,
|
|
859
|
-
storePath,
|
|
860
|
-
ctxPayload,
|
|
861
|
-
recordInboundSession: core.channel.session.recordInboundSession,
|
|
862
|
-
record: {
|
|
863
|
-
onRecordError: (err) => {
|
|
864
|
-
logVerboseMessage(
|
|
865
|
-
`msteams: failed updating session meta: ${formatUnknownError(err)}`,
|
|
866
|
-
);
|
|
867
|
-
},
|
|
868
|
-
},
|
|
869
|
-
history: {
|
|
870
|
-
isGroup: isRoomish,
|
|
871
|
-
historyKey,
|
|
872
|
-
historyMap: conversationHistories,
|
|
873
|
-
limit: historyLimit,
|
|
874
|
-
},
|
|
875
|
-
onPreDispatchFailure: () =>
|
|
876
|
-
core.channel.reply.settleReplyDispatcher({
|
|
877
|
-
dispatcher,
|
|
878
|
-
onSettled: () => markDispatchIdle(),
|
|
879
|
-
}),
|
|
880
|
-
runDispatch: () =>
|
|
881
|
-
dispatchReplyFromConfigWithSettledDispatcher({
|
|
882
|
-
cfg,
|
|
883
|
-
ctxPayload,
|
|
884
|
-
dispatcher,
|
|
885
|
-
onSettled: () => markDispatchIdle(),
|
|
886
|
-
replyOptions,
|
|
887
|
-
configOverride,
|
|
888
|
-
}),
|
|
889
|
-
}),
|
|
890
|
-
},
|
|
891
|
-
});
|
|
892
|
-
const dispatchResult = turnResult.dispatched ? turnResult.dispatchResult : undefined;
|
|
893
|
-
const queuedFinal = dispatchResult?.queuedFinal ?? false;
|
|
894
|
-
const counts = resolveInboundReplyDispatchCounts(dispatchResult);
|
|
895
|
-
const hasFinalResponse = hasFinalInboundReplyDispatch(dispatchResult);
|
|
896
|
-
|
|
897
|
-
log.info("dispatch complete", { queuedFinal, counts });
|
|
898
|
-
|
|
899
|
-
if (!hasFinalResponse) {
|
|
900
|
-
return;
|
|
901
|
-
}
|
|
902
|
-
const finalCount = counts.final;
|
|
903
|
-
logVerboseMessage(
|
|
904
|
-
`msteams: delivered ${finalCount} reply${finalCount === 1 ? "" : "ies"} to ${teamsTo}`,
|
|
905
|
-
);
|
|
906
|
-
} catch (err) {
|
|
907
|
-
log.error("dispatch failed", { error: formatUnknownError(err) });
|
|
908
|
-
runtime.error?.(`msteams dispatch failed: ${formatUnknownError(err)}`);
|
|
909
|
-
try {
|
|
910
|
-
await context.sendActivity("⚠️ Something went wrong. Please try again.");
|
|
911
|
-
} catch {
|
|
912
|
-
// Best effort.
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
};
|
|
916
|
-
|
|
917
|
-
const inboundDebouncer = core.channel.debounce.createInboundDebouncer<MSTeamsDebounceEntry>({
|
|
918
|
-
debounceMs: inboundDebounceMs,
|
|
919
|
-
buildKey: (entry) => {
|
|
920
|
-
const conversationId = normalizeMSTeamsConversationId(
|
|
921
|
-
entry.context.activity.conversation?.id ?? "",
|
|
922
|
-
);
|
|
923
|
-
const senderId =
|
|
924
|
-
entry.context.activity.from?.aadObjectId ?? entry.context.activity.from?.id ?? "";
|
|
925
|
-
if (!senderId || !conversationId) {
|
|
926
|
-
return null;
|
|
927
|
-
}
|
|
928
|
-
return `msteams:${appId}:${conversationId}:${senderId}`;
|
|
929
|
-
},
|
|
930
|
-
shouldDebounce: (entry) => {
|
|
931
|
-
if (!entry.text.trim()) {
|
|
932
|
-
return false;
|
|
933
|
-
}
|
|
934
|
-
if (entry.attachments.length > 0) {
|
|
935
|
-
return false;
|
|
936
|
-
}
|
|
937
|
-
return !core.channel.text.hasControlCommand(entry.text, cfg);
|
|
938
|
-
},
|
|
939
|
-
onFlush: async (entries) => {
|
|
940
|
-
const last = entries.at(-1);
|
|
941
|
-
if (!last) {
|
|
942
|
-
return;
|
|
943
|
-
}
|
|
944
|
-
if (entries.length === 1) {
|
|
945
|
-
await handleTeamsMessageNow(last);
|
|
946
|
-
return;
|
|
947
|
-
}
|
|
948
|
-
const combinedText = entries
|
|
949
|
-
.map((entry) => entry.text)
|
|
950
|
-
.filter(Boolean)
|
|
951
|
-
.join("\n");
|
|
952
|
-
if (!combinedText.trim()) {
|
|
953
|
-
return;
|
|
954
|
-
}
|
|
955
|
-
const combinedRawText = entries
|
|
956
|
-
.map((entry) => entry.rawText)
|
|
957
|
-
.filter(Boolean)
|
|
958
|
-
.join("\n");
|
|
959
|
-
const wasMentioned = entries.some((entry) => entry.wasMentioned);
|
|
960
|
-
const implicitMentionKinds = entries.flatMap((entry) => entry.implicitMentionKinds);
|
|
961
|
-
await handleTeamsMessageNow({
|
|
962
|
-
context: last.context,
|
|
963
|
-
rawText: combinedRawText,
|
|
964
|
-
text: combinedText,
|
|
965
|
-
attachments: [],
|
|
966
|
-
wasMentioned,
|
|
967
|
-
implicitMentionKinds,
|
|
968
|
-
});
|
|
969
|
-
},
|
|
970
|
-
onError: (err) => {
|
|
971
|
-
runtime.error?.(`msteams debounce flush failed: ${formatUnknownError(err)}`);
|
|
972
|
-
},
|
|
973
|
-
});
|
|
974
|
-
|
|
975
|
-
return async function handleTeamsMessage(context: MSTeamsTurnContext) {
|
|
976
|
-
const activity = context.activity;
|
|
977
|
-
const attachments = Array.isArray(activity.attachments)
|
|
978
|
-
? (activity.attachments as unknown as MSTeamsAttachmentLike[])
|
|
979
|
-
: [];
|
|
980
|
-
const rawText = activity.text?.trim() ?? "";
|
|
981
|
-
const htmlText = extractTextFromHtmlAttachments(attachments);
|
|
982
|
-
const text = stripMSTeamsMentionTags(rawText || htmlText);
|
|
983
|
-
const wasMentioned = wasMSTeamsBotMentioned(activity);
|
|
984
|
-
const conversationId = normalizeMSTeamsConversationId(activity.conversation?.id ?? "");
|
|
985
|
-
const replyToId = activity.replyToId ?? undefined;
|
|
986
|
-
const implicitMentionKinds: Array<"reply_to_bot"> =
|
|
987
|
-
conversationId && replyToId && wasMSTeamsMessageSent(conversationId, replyToId)
|
|
988
|
-
? ["reply_to_bot"]
|
|
989
|
-
: [];
|
|
990
|
-
|
|
991
|
-
await inboundDebouncer.enqueue({
|
|
992
|
-
context,
|
|
993
|
-
rawText,
|
|
994
|
-
text,
|
|
995
|
-
attachments,
|
|
996
|
-
wasMentioned,
|
|
997
|
-
implicitMentionKinds,
|
|
998
|
-
});
|
|
999
|
-
};
|
|
1000
|
-
}
|