@openclaw/mattermost 2026.7.2-beta.7 → 2026.7.33

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 (31) hide show
  1. package/dist/{client-CqqzTcno.js → .setup/accounts-CkvUBI7I.mjs} +101 -55
  2. package/dist/.setup/channel-plugin-api-DQ6gNcH0.mjs +31 -0
  3. package/dist/.setup/channel-plugin-api-jFFWYXht.mjs +3 -0
  4. package/dist/{channel-plugin-runtime-DlrMaSIu.js → .setup/channel-plugin-runtime-BLOKRsgT.mjs} +260 -344
  5. package/dist/.setup/channel.runtime-CK6s04r7.mjs +2653 -0
  6. package/dist/.setup/doctor-contract-ttH0DCuq.mjs +7 -0
  7. package/dist/{gateway-auth-bypass-CL1PxV3z.js → .setup/gateway-auth-bypass-BIXLORHU.mjs} +2 -3
  8. package/dist/{monitor-auth-rctDliGZ.js → .setup/monitor-auth-CeakcTAO.mjs} +13 -14
  9. package/dist/.setup/secret-contract-Cx0LUNXy.mjs +44 -0
  10. package/dist/.setup/secret-contract-api-BLTnjVCZ.mjs +3 -0
  11. package/dist/{slash-state-DM8qmFJR.js → .setup/slash-state-D1e1_KaK.mjs} +572 -311
  12. package/dist/api.js +2 -3
  13. package/dist/channel-plugin-api.js +2 -38
  14. package/dist/channel-plugin-runtime.js +1 -1
  15. package/dist/doctor-contract-api.js +1 -1
  16. package/dist/gateway-auth-api.js +1 -1
  17. package/dist/policy-api.js +1 -1
  18. package/dist/runtime-api.js +3 -2
  19. package/dist/secret-contract-api.js +1 -1
  20. package/dist/setup-entry.js +3 -2
  21. package/dist/slash-route-api.js +1 -1
  22. package/node_modules/ws/lib/permessage-deflate.js +3 -1
  23. package/node_modules/ws/package.json +1 -1
  24. package/openclaw.plugin.json +231 -277
  25. package/package.json +6 -52
  26. package/dist/accounts-NaMdx9yF.js +0 -86
  27. package/dist/channel.runtime-DndW9G7T.js +0 -3207
  28. package/dist/doctor-contract-BaUvVh8e.js +0 -19
  29. package/dist/interactions-BQXY_48h.js +0 -375
  30. package/dist/secret-contract-B4R5Bmhv.js +0 -28
  31. /package/dist/{runtime-CNB4YGqJ.js → .setup/runtime-CNB4YGqJ.mjs} +0 -0
@@ -0,0 +1,2653 @@
1
+ import { C as resolveChannelMediaMaxBytes, E as warnMissingProviderGroupPolicyFallbackOnce, S as resolveAllowlistProviderRuntimeGroupPolicy, T as resolveDefaultGroupPolicy, _ as logInboundDrop, c as buildAgentMediaPayload, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as DEFAULT_GROUP_HISTORY_LIMIT, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, x as registerPluginHttpRoute, y as parseTcpPort } from "./monitor-auth-CeakcTAO.mjs";
2
+ import { _ as readMattermostError, a as MattermostPostSchema, b as updateMattermostPost, c as createMattermostPost, f as fetchMattermostMe, g as normalizeMattermostBaseUrl, h as fetchMattermostUserTeams, i as resolveMattermostReplyToMode, l as deleteMattermostPost, o as createMattermostClient, p as fetchMattermostUser, r as resolveMattermostAccount, t as listMattermostAccountIds, u as fetchMattermostChannel, y as sendMattermostTyping } from "./accounts-CkvUBI7I.mjs";
3
+ import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.mjs";
4
+ import { C as registerSlashCommands, S as isSlashCommandsEnabled, T as resolveSlashCommandConfig, _ as renderMattermostModelsPickerView, a as sendMessageMattermost, b as DEFAULT_COMMAND_SPECS, c as computeInteractionCallbackUrl, d as setInteractionCallbackUrl, f as setInteractionSecret, g as parseMattermostModelPickerContext, h as buildMattermostAllowedModelRefs, l as createMattermostInteractionHandler, m as deliverMattermostReplyPayload, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as createMattermostReplyDeliveryBarrier, r as getSlashCommandState, s as buildButtonProps, t as activateSlashCommands, u as resolveInteractionCallbackPath, v as renderMattermostProviderPickerView, w as resolveCallbackUrl, x as cleanupSlashCommands, y as resolveMattermostModelPickerCurrentModel } from "./slash-state-D1e1_KaK.mjs";
5
+ import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
6
+ import { formatInboundFromLabel, formatInboundMediaUnavailableText } from "openclaw/plugin-sdk/channel-inbound";
7
+ import { buildChannelProgressDraftLineForEntry, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
8
+ import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
9
+ import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
10
+ import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
11
+ import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
12
+ import { fetchWithSsrFGuard, isPrivateNetworkOptInEnabled, ssrfPolicyFromPrivateNetworkOptIn } from "openclaw/plugin-sdk/ssrf-runtime";
13
+ import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
14
+ import { z } from "zod";
15
+ import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
16
+ import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
17
+ import { randomUUID } from "node:crypto";
18
+ import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
19
+ import { createClaimableDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
20
+ import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
21
+ import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
22
+ import WebSocket from "ws";
23
+ import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
24
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
25
+ //#region extensions/mattermost/src/mattermost/directory.ts
26
+ function buildClient(params) {
27
+ const account = resolveMattermostAccount({
28
+ cfg: params.cfg,
29
+ accountId: params.accountId
30
+ });
31
+ if (!account.enabled || !account.botToken || !account.baseUrl) return null;
32
+ return createMattermostClient({
33
+ baseUrl: account.baseUrl,
34
+ botToken: account.botToken,
35
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
36
+ });
37
+ }
38
+ /**
39
+ * Build clients from ALL enabled accounts (deduplicated by token).
40
+ *
41
+ * We always scan every account because:
42
+ * - Private channels are only visible to bots that are members
43
+ * - The requesting agent's account may have an expired/invalid token
44
+ *
45
+ * This means a single healthy bot token is enough for directory discovery.
46
+ */
47
+ function buildClients(params) {
48
+ const accountIds = listMattermostAccountIds(params.cfg);
49
+ const seen = /* @__PURE__ */ new Set();
50
+ const clients = [];
51
+ for (const id of accountIds) {
52
+ const client = buildClient({
53
+ cfg: params.cfg,
54
+ accountId: id
55
+ });
56
+ if (client && !seen.has(client.token)) {
57
+ seen.add(client.token);
58
+ clients.push(client);
59
+ }
60
+ }
61
+ return clients;
62
+ }
63
+ /**
64
+ * List channels (public + private) visible to any configured bot account.
65
+ *
66
+ * NOTE: Uses per_page=200 which covers most instances. Mattermost does not
67
+ * return a "has more" indicator, so very large instances (200+ channels per bot)
68
+ * may see incomplete results. Pagination can be added if needed.
69
+ */
70
+ async function listMattermostDirectoryGroups(params) {
71
+ const clients = buildClients(params);
72
+ if (!clients.length) return [];
73
+ const q = normalizeLowercaseStringOrEmpty(params.query);
74
+ const seenIds = /* @__PURE__ */ new Set();
75
+ const entries = [];
76
+ for (const client of clients) try {
77
+ const me = await fetchMattermostMe(client);
78
+ const channels = await client.request(`/users/${me.id}/channels?per_page=200`);
79
+ for (const ch of channels) {
80
+ if (ch.type !== "O" && ch.type !== "P") continue;
81
+ if (seenIds.has(ch.id)) continue;
82
+ if (q) {
83
+ const name = normalizeLowercaseStringOrEmpty(ch.name);
84
+ const display = normalizeLowercaseStringOrEmpty(ch.display_name);
85
+ if (!name.includes(q) && !display.includes(q)) continue;
86
+ }
87
+ seenIds.add(ch.id);
88
+ entries.push({
89
+ kind: "group",
90
+ id: `channel:${ch.id}`,
91
+ name: ch.name ?? void 0,
92
+ handle: ch.display_name ?? void 0
93
+ });
94
+ }
95
+ } catch (err) {
96
+ console.debug?.("[mattermost-directory] listGroups: skipping account:", err?.message);
97
+ continue;
98
+ }
99
+ return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
100
+ }
101
+ /**
102
+ * List team members as peer directory entries.
103
+ *
104
+ * Uses only the first available client since all bots in a team see the same
105
+ * user list (unlike channels where membership varies). Uses the first team
106
+ * returned — multi-team setups will only see members from that team.
107
+ *
108
+ * Uses paginated member listing with per_page=200, the Mattermost API maximum.
109
+ */
110
+ async function listMattermostDirectoryPeers(params) {
111
+ const clients = buildClients(params);
112
+ if (!clients.length) return [];
113
+ const client = clients[0];
114
+ try {
115
+ const me = await fetchMattermostMe(client);
116
+ const teams = await client.request("/users/me/teams");
117
+ if (!teams.length) return [];
118
+ const teamId = teams[0].id;
119
+ const q = normalizeLowercaseStringOrEmpty(params.query);
120
+ let users;
121
+ if (q) users = await client.request("/users/search", {
122
+ method: "POST",
123
+ body: JSON.stringify({
124
+ term: q,
125
+ team_id: teamId
126
+ })
127
+ });
128
+ else {
129
+ const pageSize = 200;
130
+ const userIds = [];
131
+ for (let page = 0;; page += 1) {
132
+ const pageMembers = await client.request(`/teams/${teamId}/members?page=${page}&per_page=${pageSize}`);
133
+ for (const member of pageMembers) if (member.user_id !== me.id) userIds.push(member.user_id);
134
+ if (pageMembers.length < pageSize) break;
135
+ }
136
+ if (!userIds.length) return [];
137
+ users = [];
138
+ for (let index = 0; index < userIds.length; index += pageSize) {
139
+ const userIdBatch = userIds.slice(index, index + pageSize);
140
+ users.push(...await client.request("/users/ids", {
141
+ method: "POST",
142
+ body: JSON.stringify(userIdBatch)
143
+ }));
144
+ }
145
+ }
146
+ const entries = users.filter((u) => u.id !== me.id).map((u) => ({
147
+ kind: "user",
148
+ id: `user:${u.id}`,
149
+ name: u.username ?? void 0,
150
+ handle: [u.first_name, u.last_name].filter(Boolean).join(" ").trim() || u.nickname || void 0
151
+ }));
152
+ return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
153
+ } catch (err) {
154
+ console.debug?.("[mattermost-directory] listPeers failed:", err?.message);
155
+ return [];
156
+ }
157
+ }
158
+ //#endregion
159
+ //#region extensions/mattermost/src/mattermost/draft-stream.ts
160
+ const MATTERMOST_STREAM_MAX_CHARS = 4e3;
161
+ const DEFAULT_THROTTLE_MS = 1e3;
162
+ function normalizeMattermostDraftText(text, maxChars) {
163
+ const trimmed = text.trim();
164
+ if (!trimmed) return "";
165
+ if (trimmed.length <= maxChars) return trimmed;
166
+ return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
167
+ }
168
+ function createMattermostDraftStream(params) {
169
+ const maxChars = Math.min(params.maxChars ?? MATTERMOST_STREAM_MAX_CHARS, MATTERMOST_STREAM_MAX_CHARS);
170
+ const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
171
+ const streamState = {
172
+ stopped: false,
173
+ final: false
174
+ };
175
+ let streamPostId;
176
+ let lastSentText = "";
177
+ const sendOrEditStreamMessage = async (text) => {
178
+ if (streamState.stopped && !streamState.final) return false;
179
+ const normalized = normalizeMattermostDraftText(params.renderText?.(text) ?? text, maxChars);
180
+ if (!normalized) return false;
181
+ if (normalized === lastSentText) return true;
182
+ try {
183
+ if (streamPostId) await updateMattermostPost(params.client, streamPostId, { message: normalized });
184
+ else {
185
+ const postId = (await createMattermostPost(params.client, {
186
+ channelId: params.channelId,
187
+ message: normalized,
188
+ rootId: params.rootId
189
+ })).id?.trim();
190
+ if (!postId) {
191
+ streamState.stopped = true;
192
+ params.warn?.("mattermost stream preview stopped (missing post id from create)");
193
+ return false;
194
+ }
195
+ streamPostId = postId;
196
+ }
197
+ lastSentText = normalized;
198
+ return true;
199
+ } catch (err) {
200
+ streamState.stopped = true;
201
+ params.warn?.(`mattermost stream preview failed: ${err instanceof Error ? err.message : String(err)}`);
202
+ return false;
203
+ }
204
+ };
205
+ const { loop, update, stop, clear, discardPending, seal } = createFinalizableDraftLifecycle({
206
+ throttleMs,
207
+ state: streamState,
208
+ sendOrEditStreamMessage,
209
+ readMessageId: () => streamPostId,
210
+ clearMessageId: () => {
211
+ streamPostId = void 0;
212
+ },
213
+ isValidMessageId: (value) => typeof value === "string" && value.length > 0,
214
+ deleteMessage: async (postId) => {
215
+ await deleteMattermostPost(params.client, postId);
216
+ },
217
+ warn: params.warn,
218
+ warnPrefix: "mattermost stream preview cleanup failed"
219
+ });
220
+ const forceNewMessage = () => {
221
+ streamPostId = void 0;
222
+ lastSentText = "";
223
+ loop.resetPending();
224
+ loop.resetThrottleWindow();
225
+ };
226
+ params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
227
+ return {
228
+ update,
229
+ flush: loop.flush,
230
+ postId: () => streamPostId,
231
+ clear,
232
+ discardPending,
233
+ seal,
234
+ stop,
235
+ forceNewMessage
236
+ };
237
+ }
238
+ //#endregion
239
+ //#region extensions/mattermost/src/mattermost/monitor-gating.ts
240
+ function mapMattermostChannelTypeToChatType(channelType) {
241
+ const normalized = channelType?.trim().toUpperCase();
242
+ if (!normalized) return "direct";
243
+ if (normalized === "D") return "direct";
244
+ if (normalized === "G" || normalized === "P") return "group";
245
+ return "channel";
246
+ }
247
+ function resolveMattermostTrustedChatKind(params) {
248
+ const channelType = params.channelType?.trim();
249
+ if (channelType) return mapMattermostChannelTypeToChatType(channelType);
250
+ return params.fallback ?? "direct";
251
+ }
252
+ function evaluateMattermostMentionGate(params) {
253
+ const shouldRequireMention = params.kind !== "direct" && params.resolveRequireMention({
254
+ cfg: params.cfg,
255
+ channel: "mattermost",
256
+ accountId: params.accountId,
257
+ groupId: params.channelId,
258
+ requireMentionOverride: params.requireMentionOverride
259
+ });
260
+ const shouldBypassMention = params.isControlCommand && shouldRequireMention && !params.wasMentioned && params.commandAuthorized;
261
+ const effectiveWasMentioned = params.wasMentioned || shouldBypassMention || params.oncharTriggered || params.threadAlreadyEngaged === true;
262
+ if (params.oncharEnabled && !params.oncharTriggered && !params.wasMentioned && !params.isControlCommand && params.threadAlreadyEngaged !== true) return {
263
+ shouldRequireMention,
264
+ shouldBypassMention,
265
+ effectiveWasMentioned,
266
+ dropReason: "onchar-not-triggered"
267
+ };
268
+ if (params.kind !== "direct" && shouldRequireMention && params.canDetectMention && !effectiveWasMentioned) return {
269
+ shouldRequireMention,
270
+ shouldBypassMention,
271
+ effectiveWasMentioned,
272
+ dropReason: "missing-mention"
273
+ };
274
+ return {
275
+ shouldRequireMention,
276
+ shouldBypassMention,
277
+ effectiveWasMentioned,
278
+ dropReason: null
279
+ };
280
+ }
281
+ //#endregion
282
+ //#region extensions/mattermost/src/mattermost/monitor-helpers.ts
283
+ const formatInboundFromLabel$1 = formatInboundFromLabel;
284
+ function resolveThreadSessionKeys$1(params) {
285
+ return resolveThreadSessionKeys({
286
+ ...params,
287
+ normalizeThreadId: (threadId) => threadId
288
+ });
289
+ }
290
+ /**
291
+ * Strip bot mention from message text while preserving newlines and
292
+ * block-level Markdown formatting (headings, lists, blockquotes).
293
+ */
294
+ function normalizeMention(text, mention) {
295
+ if (!mention) return text.trim();
296
+ const escaped = mention.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
297
+ const hasMentionRe = new RegExp(`@${escaped}\\b`, "i");
298
+ const leadingMentionRe = new RegExp(`^([\\t ]*)@${escaped}\\b[\\t ]*`, "i");
299
+ const trailingMentionRe = new RegExp(`[\\t ]*@${escaped}\\b[\\t ]*$`, "i");
300
+ const normalizedLines = text.split("\n").map((line) => {
301
+ const hadMention = hasMentionRe.test(line);
302
+ const normalizedLine = line.replace(leadingMentionRe, "$1").replace(trailingMentionRe, "").replace(new RegExp(`@${escaped}\\b`, "gi"), "").replace(/(\S)[ \t]{2,}/g, "$1 ");
303
+ return {
304
+ text: normalizedLine,
305
+ mentionOnlyBlank: hadMention && normalizedLine.trim() === ""
306
+ };
307
+ });
308
+ while (normalizedLines[0]?.mentionOnlyBlank) normalizedLines.shift();
309
+ while (normalizedLines.at(-1)?.text.trim() === "") normalizedLines.pop();
310
+ return normalizedLines.map((line) => line.text).join("\n");
311
+ }
312
+ function shouldDropEmptyMattermostBody(params) {
313
+ if (/[^\p{White_Space}\p{Cc}\p{Cf}\p{M}]/u.test(params.bodyText)) return false;
314
+ const botUsername = normalizeLowercaseStringOrEmpty(params.botUsername ?? "");
315
+ const bareMention = params.rawText.match(/^[ \t]*(@\S+)[ \t]*$/u)?.[1];
316
+ return !botUsername || normalizeLowercaseStringOrEmpty(bareMention ?? "") !== `@${botUsername}`;
317
+ }
318
+ //#endregion
319
+ //#region extensions/mattermost/src/mattermost/monitor-onchar.ts
320
+ const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
321
+ function resolveOncharPrefixes(prefixes) {
322
+ const cleaned = prefixes ? normalizeStringEntries(prefixes) : DEFAULT_ONCHAR_PREFIXES;
323
+ return cleaned.length > 0 ? cleaned : DEFAULT_ONCHAR_PREFIXES;
324
+ }
325
+ function stripOncharPrefix(text, prefixes) {
326
+ const trimmed = text.trimStart();
327
+ for (const prefix of prefixes) {
328
+ if (!prefix) continue;
329
+ if (trimmed.startsWith(prefix)) return {
330
+ triggered: true,
331
+ stripped: trimmed.slice(prefix.length).trimStart()
332
+ };
333
+ }
334
+ return {
335
+ triggered: false,
336
+ stripped: text
337
+ };
338
+ }
339
+ //#endregion
340
+ //#region extensions/mattermost/src/mattermost/monitor-resources.ts
341
+ function formatMattermostInboundMediaText(params) {
342
+ const unavailableCount = Math.max(0, params.expectedCount - params.mediaCount);
343
+ if (unavailableCount === 0) return params.body;
344
+ return formatInboundMediaUnavailableText({
345
+ body: params.body,
346
+ mediaPlaceholder: params.mediaCount === 0 ? params.mediaPlaceholder : void 0,
347
+ notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]`
348
+ });
349
+ }
350
+ const CHANNEL_CACHE_TTL_MS = 3e5;
351
+ const USER_CACHE_TTL_MS = 6e5;
352
+ function createMattermostMonitorResources(params) {
353
+ const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
354
+ const channelCache = /* @__PURE__ */ new Map();
355
+ const userCache = /* @__PURE__ */ new Map();
356
+ const getCachedValue = (cache, key, nowMs) => {
357
+ const cached = cache.get(key);
358
+ if (!cached) return;
359
+ if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
360
+ cache.delete(key);
361
+ };
362
+ const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
363
+ const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
364
+ if (expiresAt !== void 0) cache.set(key, {
365
+ value,
366
+ expiresAt
367
+ });
368
+ };
369
+ const resolveMattermostMedia = async (fileIds) => {
370
+ const ids = normalizeStringEntries(fileIds ?? []);
371
+ if (ids.length === 0) return [];
372
+ const out = [];
373
+ for (const fileId of ids) try {
374
+ const saved = await saveRemoteMedia({
375
+ url: `${client.apiBaseUrl}/files/${fileId}`,
376
+ requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
377
+ filePathHint: fileId,
378
+ maxBytes: mediaMaxBytes,
379
+ ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] }
380
+ });
381
+ const contentType = saved.contentType ?? void 0;
382
+ out.push({
383
+ path: saved.path,
384
+ contentType,
385
+ kind: mediaKindFromMime(contentType) ?? "unknown"
386
+ });
387
+ } catch (err) {
388
+ logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
389
+ }
390
+ return out;
391
+ };
392
+ const sendTypingIndicator = async (channelId, parentId) => {
393
+ await sendMattermostTyping(client, {
394
+ channelId,
395
+ parentId
396
+ });
397
+ };
398
+ const resolveChannelInfo = async (channelId) => {
399
+ const rawNow = Date.now();
400
+ const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
401
+ if (cached !== void 0) return cached;
402
+ try {
403
+ const info = await fetchMattermostChannel(client, channelId);
404
+ setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
405
+ return info;
406
+ } catch (err) {
407
+ logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
408
+ setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
409
+ return null;
410
+ }
411
+ };
412
+ const resolveUserInfo = async (userId) => {
413
+ const rawNow = Date.now();
414
+ const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
415
+ if (cached !== void 0) return cached;
416
+ try {
417
+ const info = await fetchMattermostUser(client, userId);
418
+ setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
419
+ return info;
420
+ } catch (err) {
421
+ logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
422
+ setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
423
+ return null;
424
+ }
425
+ };
426
+ const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
427
+ callbackUrl,
428
+ accountId,
429
+ channelId,
430
+ buttons
431
+ });
432
+ const updateModelPickerPost = async (paramsLocal) => {
433
+ const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
434
+ await updateMattermostPost(client, paramsLocal.postId, {
435
+ message: paramsLocal.message,
436
+ props
437
+ });
438
+ return {};
439
+ };
440
+ return {
441
+ resolveMattermostMedia,
442
+ sendTypingIndicator,
443
+ resolveChannelInfo,
444
+ resolveUserInfo,
445
+ updateModelPickerPost
446
+ };
447
+ }
448
+ //#endregion
449
+ //#region extensions/mattermost/src/mattermost/monitor-slash.ts
450
+ function buildSlashCommands(params) {
451
+ const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
452
+ if (!params.nativeSkills) return commandsToRegister;
453
+ try {
454
+ const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
455
+ for (const spec of skillCommands) {
456
+ const name = typeof spec.name === "string" ? spec.name.trim() : "";
457
+ if (!name) continue;
458
+ const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
459
+ commandsToRegister.push({
460
+ trigger,
461
+ description: spec.description || `Run skill ${name}`,
462
+ autoComplete: true,
463
+ autoCompleteHint: "[args]",
464
+ originalName: name
465
+ });
466
+ }
467
+ } catch (err) {
468
+ params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
469
+ }
470
+ return commandsToRegister;
471
+ }
472
+ function dedupeSlashCommands(commands) {
473
+ const seen = /* @__PURE__ */ new Set();
474
+ return commands.filter((cmd) => {
475
+ const key = cmd.trigger.trim();
476
+ if (!key || seen.has(key)) return false;
477
+ seen.add(key);
478
+ return true;
479
+ });
480
+ }
481
+ function buildTriggerMap(commands) {
482
+ const triggerMap = /* @__PURE__ */ new Map();
483
+ for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
484
+ return triggerMap;
485
+ }
486
+ function warnOnSuspiciousCallbackUrl(params) {
487
+ try {
488
+ const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
489
+ const callbackHost = new URL(params.callbackUrl).hostname;
490
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${params.callbackUrl} (loopback) while baseUrl is ${params.baseUrl}. This MAY be unreachable depending on your deployment. If native slash commands don't work, set channels.mattermost.commands.callbackUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
491
+ } catch {}
492
+ }
493
+ async function registerSlashCommandsAcrossTeams(params) {
494
+ const registered = [];
495
+ let teamRegistrationFailures = 0;
496
+ for (const team of params.teams) try {
497
+ const created = await registerSlashCommands({
498
+ client: params.client,
499
+ teamId: team.id,
500
+ creatorUserId: params.botUserId,
501
+ callbackUrl: params.callbackUrl,
502
+ commands: params.commands,
503
+ log: (msg) => params.runtime.log?.(msg)
504
+ });
505
+ registered.push(...created);
506
+ } catch (err) {
507
+ teamRegistrationFailures += 1;
508
+ params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
509
+ }
510
+ return {
511
+ registered,
512
+ teamRegistrationFailures
513
+ };
514
+ }
515
+ async function registerMattermostMonitorSlashCommands(params) {
516
+ const commandsRaw = params.account.config.commands;
517
+ const slashConfig = resolveSlashCommandConfig(commandsRaw);
518
+ if (!isSlashCommandsEnabled(slashConfig)) return;
519
+ try {
520
+ const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
521
+ const slashGatewayPort = parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789;
522
+ const slashCallbackUrl = resolveCallbackUrl({
523
+ config: slashConfig,
524
+ gatewayPort: slashGatewayPort,
525
+ gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
526
+ });
527
+ warnOnSuspiciousCallbackUrl({
528
+ runtime: params.runtime,
529
+ baseUrl: params.baseUrl,
530
+ callbackUrl: slashCallbackUrl
531
+ });
532
+ const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
533
+ cfg: params.cfg,
534
+ runtime: params.runtime,
535
+ nativeSkills: slashConfig.nativeSkills === true
536
+ }));
537
+ const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
538
+ client: params.client,
539
+ teams,
540
+ botUserId: params.botUserId,
541
+ callbackUrl: slashCallbackUrl,
542
+ commands: dedupedCommands,
543
+ runtime: params.runtime
544
+ });
545
+ if (registered.length === 0) {
546
+ params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
547
+ return;
548
+ }
549
+ if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
550
+ activateSlashCommands({
551
+ account: params.account,
552
+ commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
553
+ registeredCommands: registered,
554
+ triggerMap: buildTriggerMap(dedupedCommands),
555
+ api: {
556
+ cfg: params.cfg,
557
+ runtime: params.runtime
558
+ },
559
+ log: (msg) => params.runtime.log?.(msg)
560
+ });
561
+ params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
562
+ } catch (err) {
563
+ params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
564
+ }
565
+ }
566
+ //#endregion
567
+ //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
568
+ const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16777216;
569
+ const MattermostEventPayloadSchema = z.object({
570
+ event: z.string().optional(),
571
+ data: z.object({
572
+ post: z.union([z.string(), MattermostPostSchema]).optional(),
573
+ reaction: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
574
+ channel_id: z.string().optional(),
575
+ channel_name: z.string().optional(),
576
+ channel_display_name: z.string().optional(),
577
+ channel_type: z.string().optional(),
578
+ sender_name: z.string().optional(),
579
+ team_id: z.string().optional()
580
+ }).optional(),
581
+ broadcast: z.object({
582
+ channel_id: z.string().optional(),
583
+ team_id: z.string().optional(),
584
+ user_id: z.string().optional()
585
+ }).optional()
586
+ });
587
+ function parseMattermostEventPayload(raw) {
588
+ return safeParseJsonWithSchema(MattermostEventPayloadSchema, raw);
589
+ }
590
+ function parseMattermostPost(value) {
591
+ if (typeof value === "string") return safeParseJsonWithSchema(MattermostPostSchema, value);
592
+ return safeParseWithSchema(MattermostPostSchema, value);
593
+ }
594
+ var WebSocketClosedBeforeOpenError = class extends Error {
595
+ constructor(code, reason) {
596
+ super(`websocket closed before open (code ${code})`);
597
+ this.code = code;
598
+ this.reason = reason;
599
+ this.name = "WebSocketClosedBeforeOpenError";
600
+ }
601
+ };
602
+ const defaultMattermostWebSocketFactory = (url) => {
603
+ const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
604
+ return new WebSocket(url, {
605
+ ...agent ? { agent } : {},
606
+ maxPayload: MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES
607
+ });
608
+ };
609
+ function parsePostedPayload(payload) {
610
+ if (payload.event !== "posted") return null;
611
+ const postData = payload.data?.post;
612
+ if (!postData) return null;
613
+ const post = parseMattermostPost(postData);
614
+ if (!post) return null;
615
+ return {
616
+ payload,
617
+ post
618
+ };
619
+ }
620
+ function createMattermostConnectOnce(opts) {
621
+ const webSocketFactory = opts.webSocketFactory ?? defaultMattermostWebSocketFactory;
622
+ const healthCheckIntervalMs = opts.healthCheckIntervalMs ?? 3e4;
623
+ const pingIntervalMs = opts.pingIntervalMs ?? 3e4;
624
+ const pongTimeoutMs = opts.pongTimeoutMs ?? 1e4;
625
+ return async () => {
626
+ const flowId = randomUUID();
627
+ const ws = webSocketFactory(opts.wsUrl);
628
+ const onAbort = () => ws.terminate();
629
+ opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
630
+ const getBotUpdateAt = opts.getBotUpdateAt;
631
+ try {
632
+ return await new Promise((resolve, reject) => {
633
+ let opened = false;
634
+ let settled = false;
635
+ let healthCheckEnabled = getBotUpdateAt != null;
636
+ let healthCheckInFlight = false;
637
+ let healthCheckTimer;
638
+ let protocolKeepaliveEnabled = true;
639
+ let protocolPingTimer;
640
+ let protocolPongTimer;
641
+ let initialUpdateAt;
642
+ const clearTimers = () => {
643
+ if (healthCheckTimer !== void 0) {
644
+ clearTimeout(healthCheckTimer);
645
+ healthCheckTimer = void 0;
646
+ }
647
+ if (protocolPingTimer !== void 0) {
648
+ clearTimeout(protocolPingTimer);
649
+ protocolPingTimer = void 0;
650
+ }
651
+ if (protocolPongTimer !== void 0) {
652
+ clearTimeout(protocolPongTimer);
653
+ protocolPongTimer = void 0;
654
+ }
655
+ };
656
+ const stopHealthChecks = () => {
657
+ healthCheckEnabled = false;
658
+ protocolKeepaliveEnabled = false;
659
+ clearTimers();
660
+ };
661
+ const sendProtocolPing = () => {
662
+ if (!protocolKeepaliveEnabled || settled) return;
663
+ if (protocolPongTimer !== void 0) clearTimeout(protocolPongTimer);
664
+ protocolPongTimer = setTimeout(() => {
665
+ protocolPongTimer = void 0;
666
+ if (!protocolKeepaliveEnabled || settled) return;
667
+ opts.runtime.error?.("mattermost websocket pong timeout — reconnecting");
668
+ stopHealthChecks();
669
+ ws.terminate();
670
+ }, pongTimeoutMs);
671
+ try {
672
+ ws.ping();
673
+ } catch (err) {
674
+ if (!protocolKeepaliveEnabled || settled) return;
675
+ opts.runtime.error?.(`mattermost websocket ping failed: ${String(err)}`);
676
+ stopHealthChecks();
677
+ ws.terminate();
678
+ }
679
+ };
680
+ const scheduleProtocolPing = () => {
681
+ if (!protocolKeepaliveEnabled || settled || protocolPingTimer !== void 0) return;
682
+ protocolPingTimer = setTimeout(() => {
683
+ protocolPingTimer = void 0;
684
+ sendProtocolPing();
685
+ }, pingIntervalMs);
686
+ };
687
+ const scheduleHealthCheck = () => {
688
+ if (!getBotUpdateAt || !healthCheckEnabled || settled || healthCheckInFlight) return;
689
+ healthCheckTimer = setTimeout(() => {
690
+ healthCheckTimer = void 0;
691
+ runHealthCheck();
692
+ }, healthCheckIntervalMs);
693
+ };
694
+ const runHealthCheck = async () => {
695
+ if (!getBotUpdateAt || !healthCheckEnabled || settled || healthCheckInFlight) return;
696
+ healthCheckInFlight = true;
697
+ try {
698
+ const current = await getBotUpdateAt();
699
+ if (!healthCheckEnabled || settled) return;
700
+ if (initialUpdateAt === void 0) {
701
+ initialUpdateAt = current;
702
+ return;
703
+ }
704
+ if (current !== initialUpdateAt) {
705
+ opts.runtime.log?.(`mattermost: bot account updated (update_at changed: ${initialUpdateAt} → ${current}) — reconnecting`);
706
+ stopHealthChecks();
707
+ ws.terminate();
708
+ }
709
+ } catch (err) {
710
+ if (!healthCheckEnabled || settled) return;
711
+ const label = initialUpdateAt === void 0 ? "mattermost: failed to get initial update_at" : "mattermost: health check error";
712
+ opts.runtime.error?.(`${label}: ${String(err)}`);
713
+ } finally {
714
+ healthCheckInFlight = false;
715
+ scheduleHealthCheck();
716
+ }
717
+ };
718
+ const resolveOnce = () => {
719
+ if (settled) return;
720
+ settled = true;
721
+ stopHealthChecks();
722
+ resolve();
723
+ };
724
+ const rejectOnce = (error) => {
725
+ if (settled) return;
726
+ settled = true;
727
+ stopHealthChecks();
728
+ reject(error);
729
+ };
730
+ ws.on("open", () => {
731
+ opened = true;
732
+ captureWsEvent({
733
+ url: opts.wsUrl,
734
+ direction: "local",
735
+ kind: "ws-open",
736
+ flowId,
737
+ meta: { subsystem: "mattermost-websocket" }
738
+ });
739
+ opts.statusSink?.({
740
+ connected: true,
741
+ lastConnectedAt: Date.now(),
742
+ lastError: null
743
+ });
744
+ const authPayload = JSON.stringify({
745
+ seq: opts.nextSeq(),
746
+ action: "authentication_challenge",
747
+ data: { token: opts.botToken }
748
+ });
749
+ captureWsEvent({
750
+ url: opts.wsUrl,
751
+ direction: "outbound",
752
+ kind: "ws-frame",
753
+ flowId,
754
+ payload: authPayload,
755
+ meta: {
756
+ subsystem: "mattermost-websocket",
757
+ eventType: "authentication_challenge"
758
+ }
759
+ });
760
+ ws.send(authPayload);
761
+ scheduleProtocolPing();
762
+ if (getBotUpdateAt) runHealthCheck();
763
+ });
764
+ ws.on("pong", () => {
765
+ if (protocolPongTimer !== void 0) {
766
+ clearTimeout(protocolPongTimer);
767
+ protocolPongTimer = void 0;
768
+ }
769
+ scheduleProtocolPing();
770
+ });
771
+ ws.on("message", async (data) => {
772
+ captureWsEvent({
773
+ url: opts.wsUrl,
774
+ direction: "inbound",
775
+ kind: "ws-frame",
776
+ flowId,
777
+ payload: Buffer.from(rawDataToString(data)),
778
+ meta: { subsystem: "mattermost-websocket" }
779
+ });
780
+ const payload = parseMattermostEventPayload(rawDataToString(data));
781
+ if (!payload) return;
782
+ if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
783
+ if (!opts.onReaction) return;
784
+ try {
785
+ await opts.onReaction(payload);
786
+ } catch (err) {
787
+ opts.runtime.error?.(`mattermost reaction handler failed: ${String(err)}`);
788
+ }
789
+ return;
790
+ }
791
+ if (payload.event !== "posted") return;
792
+ const parsed = parsePostedPayload(payload);
793
+ if (!parsed) return;
794
+ try {
795
+ await opts.onPosted(parsed.post, parsed.payload);
796
+ } catch (err) {
797
+ opts.runtime.error?.(`mattermost handler failed: ${String(err)}`);
798
+ }
799
+ });
800
+ ws.on("close", (code, reason) => {
801
+ captureWsEvent({
802
+ url: opts.wsUrl,
803
+ direction: "local",
804
+ kind: "ws-close",
805
+ flowId,
806
+ closeCode: code,
807
+ payload: reason,
808
+ meta: { subsystem: "mattermost-websocket" }
809
+ });
810
+ stopHealthChecks();
811
+ const message = reasonToString(reason);
812
+ opts.statusSink?.({
813
+ connected: false,
814
+ lastDisconnect: {
815
+ at: Date.now(),
816
+ status: code,
817
+ error: message || void 0
818
+ }
819
+ });
820
+ if (opened) {
821
+ resolveOnce();
822
+ return;
823
+ }
824
+ rejectOnce(new WebSocketClosedBeforeOpenError(code, message || void 0));
825
+ });
826
+ ws.on("error", (err) => {
827
+ captureWsEvent({
828
+ url: opts.wsUrl,
829
+ direction: "local",
830
+ kind: "error",
831
+ flowId,
832
+ errorText: String(err),
833
+ meta: { subsystem: "mattermost-websocket" }
834
+ });
835
+ opts.runtime.error?.(`mattermost websocket error: ${String(err)}`);
836
+ opts.statusSink?.({ lastError: String(err) });
837
+ try {
838
+ ws.close();
839
+ } catch {}
840
+ });
841
+ });
842
+ } finally {
843
+ opts.abortSignal?.removeEventListener("abort", onAbort);
844
+ }
845
+ };
846
+ }
847
+ function reasonToString(reason) {
848
+ if (!reason) return "";
849
+ if (typeof reason === "string") return reason;
850
+ return reason.length > 0 ? reason.toString("utf8") : "";
851
+ }
852
+ //#endregion
853
+ //#region extensions/mattermost/src/mattermost/no-visible-reply-diagnostic.ts
854
+ /**
855
+ * Detects the #80501 symptom: `deliverMattermostReplyPayload` accepted a
856
+ * substantive (non-reasoning) payload, called the underlying
857
+ * `deliverTextOrMediaReply`, and the outcome was `"empty"` — meaning the
858
+ * payload had no text and no media to send, so no Mattermost API call
859
+ * happened. The agent's run completes successfully, but no visible
860
+ * channel/thread reply ever surfaces to the user.
861
+ *
862
+ * Returns a structured violation when the outcome is `"empty"` for a payload
863
+ * that nominally carried user-facing content (text or media bytes that ended
864
+ * up dropped by `resolveSendableOutboundReplyParts`/`sendMediaWithLeadingCaption`).
865
+ * Returns `null` for `"reasoning_skipped"` (intentional suppression),
866
+ * `"text"`, or `"media"` (successful visible sends).
867
+ */
868
+ function evaluateMattermostNoVisibleReply(params) {
869
+ if (params.outcome !== "empty") return null;
870
+ const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
871
+ const mediaUrlCount = countOutboundMedia(params.payload);
872
+ if (finalText.length === 0 && mediaUrlCount === 0) return null;
873
+ return {
874
+ reason: "no-visible-reply-after-final-delivery",
875
+ outcome: params.outcome,
876
+ finalTextLength: finalText.length,
877
+ mediaUrlCount
878
+ };
879
+ }
880
+ function formatMattermostNoVisibleReplyLog(params) {
881
+ return `mattermost no-visible-reply: ${params.violation.reason} to=${params.to} accountId=${params.accountId} agentId=${params.agentId ?? "unknown"} outcome=${params.violation.outcome} finalTextLength=${params.violation.finalTextLength} mediaUrlCount=${params.violation.mediaUrlCount}`;
882
+ }
883
+ //#endregion
884
+ //#region extensions/mattermost/src/mattermost/reconnect.ts
885
+ /**
886
+ * Reconnection loop with exponential backoff.
887
+ *
888
+ * Calls `connectFn` in a while loop. On normal resolve (connection closed),
889
+ * the backoff resets. On thrown error (connection failed), the current delay is
890
+ * used, then doubled for the next retry.
891
+ * The loop exits when `abortSignal` fires.
892
+ */
893
+ async function runWithReconnect(connectFn, opts = {}) {
894
+ const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
895
+ const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
896
+ const random = opts.random ?? Math.random;
897
+ const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
898
+ let attempt = 0;
899
+ while (!opts.abortSignal?.aborted) {
900
+ let outcome = "resolved";
901
+ let error;
902
+ try {
903
+ await connectFn();
904
+ backoff.reset();
905
+ } catch (err) {
906
+ if (opts.abortSignal?.aborted) return;
907
+ outcome = "rejected";
908
+ error = err;
909
+ opts.onError?.(err);
910
+ }
911
+ if (opts.abortSignal?.aborted) return;
912
+ const delayMs = withJitter(backoff.current(), jitterRatio, random);
913
+ if (!(opts.shouldReconnect?.({
914
+ attempt,
915
+ delayMs,
916
+ outcome,
917
+ error
918
+ }) ?? true)) return;
919
+ opts.onReconnect?.(delayMs);
920
+ await sleepAbortable(delayMs, opts.abortSignal);
921
+ if (outcome === "rejected") backoff.increase();
922
+ attempt++;
923
+ }
924
+ }
925
+ function createReconnectBackoff(initialDelayMs, maxDelayMs) {
926
+ let retryDelay = initialDelayMs;
927
+ return {
928
+ current: () => retryDelay,
929
+ reset: () => {
930
+ retryDelay = initialDelayMs;
931
+ },
932
+ increase: () => {
933
+ retryDelay = Math.min(retryDelay * 2, maxDelayMs);
934
+ }
935
+ };
936
+ }
937
+ function withJitter(baseMs, jitterRatio, random) {
938
+ if (jitterRatio <= 0) return baseMs;
939
+ const normalized = Math.max(0, Math.min(1, random()));
940
+ const spread = baseMs * jitterRatio;
941
+ return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
942
+ }
943
+ function sleepAbortable(ms, signal) {
944
+ return new Promise((resolve) => {
945
+ if (signal?.aborted) {
946
+ resolve();
947
+ return;
948
+ }
949
+ const onAbort = () => {
950
+ clearTimeout(timer);
951
+ resolve();
952
+ };
953
+ const timer = setTimeout(() => {
954
+ signal?.removeEventListener("abort", onAbort);
955
+ resolve();
956
+ }, ms);
957
+ signal?.addEventListener("abort", onAbort, { once: true });
958
+ });
959
+ }
960
+ //#endregion
961
+ //#region extensions/mattermost/src/mattermost/thread-participation.ts
962
+ const threadParticipation = createPersistentDedupeCache({
963
+ globalKey: Symbol.for("openclaw.mattermostThreadParticipation"),
964
+ ttlMs: 6048e5,
965
+ maxSize: 5e3,
966
+ persistent: {
967
+ namespace: "mattermost.thread-participation",
968
+ maxEntries: 1e3,
969
+ openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
970
+ logError: (error) => {
971
+ try {
972
+ getOptionalMattermostRuntime()?.logging.getChildLogger({
973
+ plugin: "mattermost",
974
+ feature: "thread-participation-state"
975
+ }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
976
+ } catch {}
977
+ }
978
+ }
979
+ });
980
+ function makeKey(accountId, channelId, threadRootId) {
981
+ return `${accountId}:${channelId}:${threadRootId}`;
982
+ }
983
+ function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
984
+ if (!accountId || !channelId || !threadRootId) return;
985
+ threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
986
+ ...opts?.agentId ? { agentId: opts.agentId } : {},
987
+ repliedAt: Date.now()
988
+ });
989
+ }
990
+ async function hasMattermostThreadParticipationWithPersistence(params) {
991
+ if (!params.accountId || !params.channelId || !params.threadRootId) return false;
992
+ return await threadParticipation.lookup(makeKey(params.accountId, params.channelId, params.threadRootId));
993
+ }
994
+ //#endregion
995
+ //#region extensions/mattermost/src/mattermost/monitor.ts
996
+ function shouldUpdateMattermostDraftToolProgress(account) {
997
+ return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config);
998
+ }
999
+ function shouldSuppressMattermostDefaultToolProgressMessages(account) {
1000
+ return account.streamingMode !== "off";
1001
+ }
1002
+ const RECENT_MATTERMOST_MESSAGE_TTL_MS = 3e5;
1003
+ const RECENT_MATTERMOST_MESSAGE_MAX = 2e3;
1004
+ function normalizeInteractionSourceIps(values) {
1005
+ return normalizeTrimmedStringList(values);
1006
+ }
1007
+ const recentInboundMessages = createClaimableDedupe({
1008
+ ttlMs: RECENT_MATTERMOST_MESSAGE_TTL_MS,
1009
+ memoryMaxSize: RECENT_MATTERMOST_MESSAGE_MAX
1010
+ });
1011
+ var MattermostRetryableInboundError = class extends Error {
1012
+ constructor(message, options) {
1013
+ super(message, options);
1014
+ this.name = "MattermostRetryableInboundError";
1015
+ }
1016
+ };
1017
+ function buildMattermostModelPickerSelectMessageSid(params) {
1018
+ const provider = normalizeLowercaseStringOrEmpty(params.provider);
1019
+ const model = normalizeLowercaseStringOrEmpty(params.model);
1020
+ return `interaction:${params.postId}:select:${provider}/${model}`;
1021
+ }
1022
+ function buildMattermostInboundReplayKeys(params) {
1023
+ return uniqueStrings(params.messageIds.map((id) => `${params.accountId}:${id.trim()}`)).filter((key) => !key.endsWith(":"));
1024
+ }
1025
+ async function processMattermostReplayGuardedPost(params) {
1026
+ const replayGuard = params.replayGuard ?? recentInboundMessages;
1027
+ const replayKeys = buildMattermostInboundReplayKeys({
1028
+ accountId: params.accountId,
1029
+ messageIds: params.messageIds
1030
+ });
1031
+ if (replayKeys.length === 0) {
1032
+ await params.handlePost();
1033
+ return "processed";
1034
+ }
1035
+ const claimedKeys = [];
1036
+ for (const replayKey of replayKeys) if ((await replayGuard.claim(replayKey)).kind === "claimed") claimedKeys.push(replayKey);
1037
+ if (claimedKeys.length === 0) return "duplicate";
1038
+ try {
1039
+ await params.handlePost();
1040
+ await Promise.all(claimedKeys.map((replayKey) => replayGuard.commit(replayKey)));
1041
+ return "processed";
1042
+ } catch (error) {
1043
+ if (error instanceof MattermostRetryableInboundError) claimedKeys.forEach((replayKey) => replayGuard.release(replayKey, { error }));
1044
+ else await Promise.all(claimedKeys.map((replayKey) => replayGuard.commit(replayKey)));
1045
+ throw error;
1046
+ }
1047
+ }
1048
+ function resolveRuntime(opts) {
1049
+ return opts.runtime ?? {
1050
+ log: console.log,
1051
+ error: console.error,
1052
+ exit: (code) => {
1053
+ throw new Error(`exit ${code}`);
1054
+ }
1055
+ };
1056
+ }
1057
+ function isSystemPost(post) {
1058
+ return normalizeOptionalString(post.type) !== void 0;
1059
+ }
1060
+ function channelChatType(kind) {
1061
+ if (kind === "direct") return "direct";
1062
+ if (kind === "group") return "group";
1063
+ return "channel";
1064
+ }
1065
+ function resolveMattermostReplyRootId(params) {
1066
+ if (params.kind === "direct") return;
1067
+ const threadRootId = normalizeOptionalString(params.threadRootId);
1068
+ if (threadRootId) return threadRootId;
1069
+ return normalizeOptionalString(params.replyToId);
1070
+ }
1071
+ function canFinalizeMattermostPreviewInPlace(params) {
1072
+ return resolveMattermostReplyRootId({
1073
+ kind: params.kind,
1074
+ threadRootId: params.threadRootId,
1075
+ replyToId: params.replyToId
1076
+ }) === params.previewRootId?.trim();
1077
+ }
1078
+ function createDisabledMattermostDraftStream() {
1079
+ const noopAsync = async () => {};
1080
+ return {
1081
+ update: () => {},
1082
+ flush: noopAsync,
1083
+ postId: () => void 0,
1084
+ clear: noopAsync,
1085
+ discardPending: noopAsync,
1086
+ seal: noopAsync,
1087
+ stop: noopAsync,
1088
+ forceNewMessage: () => {}
1089
+ };
1090
+ }
1091
+ async function deliverMattermostReplyWithDraftPreview(params) {
1092
+ if (isReasoningReplyPayload(params.payload)) return;
1093
+ await deliverWithFinalizableLivePreviewAdapter({
1094
+ kind: params.info.kind,
1095
+ payload: params.payload,
1096
+ adapter: defineFinalizableLivePreviewAdapter({
1097
+ draft: {
1098
+ flush: params.draftStream.flush,
1099
+ clear: params.draftStream.clear,
1100
+ discardPending: params.draftStream.discardPending,
1101
+ seal: params.draftStream.seal,
1102
+ id: params.draftStream.postId
1103
+ },
1104
+ buildFinalEdit: (payload) => {
1105
+ const hasMedia = Boolean(payload.mediaUrl) || (payload.mediaUrls?.length ?? 0) > 0;
1106
+ const ttsSupplement = getReplyPayloadTtsSupplement(payload);
1107
+ const previewFinalText = params.resolvePreviewFinalText(payload.text ?? ttsSupplement?.spokenText);
1108
+ if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
1109
+ kind: params.kind,
1110
+ previewRootId: params.effectiveReplyToId,
1111
+ threadRootId: params.effectiveReplyToId,
1112
+ replyToId: payload.replyToId
1113
+ })) return;
1114
+ return { message: previewFinalText };
1115
+ },
1116
+ editFinal: async (previewPostId, edit) => {
1117
+ await updateMattermostPost(params.client, previewPostId, edit);
1118
+ },
1119
+ onPreviewFinalized: () => {
1120
+ params.previewState.finalizedViaPreviewPost = true;
1121
+ params.recordThreadParticipation?.();
1122
+ },
1123
+ buildSupplementalPayload: (payload) => getReplyPayloadTtsSupplement(payload) ? buildTtsSupplementMediaPayload(payload) : void 0,
1124
+ deliverSupplemental: async (payload) => {
1125
+ await params.deliverPayload(payload);
1126
+ },
1127
+ logPreviewEditFailure: (err) => {
1128
+ params.logVerboseMessage(`mattermost preview final edit failed; falling back to normal send (${String(err)})`);
1129
+ }
1130
+ }),
1131
+ deliverNormally: async (payload) => {
1132
+ const supplement = getReplyPayloadTtsSupplement(payload);
1133
+ await params.deliverPayload(supplement && !payload.text?.trim() && supplement.visibleTextAlreadyDelivered !== true ? {
1134
+ ...payload,
1135
+ text: supplement.spokenText
1136
+ } : payload);
1137
+ }
1138
+ });
1139
+ }
1140
+ function formatMattermostFinalDeliveryOutcomeLog(params) {
1141
+ const violation = evaluateMattermostNoVisibleReply({
1142
+ outcome: params.outcome,
1143
+ payload: params.payload
1144
+ });
1145
+ if (violation) return formatMattermostNoVisibleReplyLog({
1146
+ violation,
1147
+ to: params.to,
1148
+ accountId: params.accountId,
1149
+ agentId: params.agentId
1150
+ });
1151
+ if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
1152
+ }
1153
+ function resolveMattermostEffectiveReplyToId(params) {
1154
+ if (params.kind === "direct") return;
1155
+ const threadRootId = normalizeOptionalString(params.threadRootId);
1156
+ if (threadRootId) return threadRootId;
1157
+ const postId = normalizeOptionalString(params.postId);
1158
+ if (!postId) return;
1159
+ return params.replyToMode === "all" || params.replyToMode === "first" || params.replyToMode === "batched" ? postId : void 0;
1160
+ }
1161
+ function resolveMattermostThreadSessionContext(params) {
1162
+ const effectiveReplyToId = resolveMattermostEffectiveReplyToId({
1163
+ kind: params.kind,
1164
+ postId: params.postId,
1165
+ replyToMode: params.replyToMode,
1166
+ threadRootId: params.threadRootId
1167
+ });
1168
+ const threadKeys = resolveThreadSessionKeys$1({
1169
+ baseSessionKey: params.baseSessionKey,
1170
+ threadId: effectiveReplyToId,
1171
+ parentSessionKey: effectiveReplyToId ? params.baseSessionKey : void 0
1172
+ });
1173
+ return {
1174
+ effectiveReplyToId,
1175
+ sessionKey: threadKeys.sessionKey,
1176
+ parentSessionKey: threadKeys.parentSessionKey
1177
+ };
1178
+ }
1179
+ function resolveMattermostReactionChannelId(payload) {
1180
+ return normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
1181
+ }
1182
+ function buildMattermostAttachmentPlaceholder(mediaList) {
1183
+ if (mediaList.length === 0) return "";
1184
+ if (mediaList.length === 1) return `<media:${mediaList[0].kind === "unknown" ? "document" : mediaList[0].kind}>`;
1185
+ const allImages = mediaList.every((media) => media.kind === "image");
1186
+ const label = allImages ? "image" : "file";
1187
+ const suffix = mediaList.length === 1 ? label : `${label}s`;
1188
+ return `${allImages ? "<media:image>" : "<media:document>"} (${mediaList.length} ${suffix})`;
1189
+ }
1190
+ function buildMattermostWsUrl(baseUrl) {
1191
+ const normalized = normalizeMattermostBaseUrl(baseUrl);
1192
+ if (!normalized) throw new Error("Mattermost baseUrl is required");
1193
+ return `${normalized.replace(/^http/i, "ws")}/api/v4/websocket`;
1194
+ }
1195
+ async function monitorMattermostProvider(opts = {}) {
1196
+ const core = getMattermostRuntime();
1197
+ const runtime = resolveRuntime(opts);
1198
+ const cfg = opts.config ?? core.config.current();
1199
+ const account = resolveMattermostAccount({
1200
+ cfg,
1201
+ accountId: opts.accountId
1202
+ });
1203
+ const pairing = createChannelPairingController({
1204
+ core,
1205
+ channel: "mattermost",
1206
+ accountId: account.accountId
1207
+ });
1208
+ const botToken = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
1209
+ if (!botToken) throw new Error(`Mattermost bot token missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.botToken or MATTERMOST_BOT_TOKEN for default).`);
1210
+ const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
1211
+ if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
1212
+ const client = createMattermostClient({
1213
+ baseUrl,
1214
+ botToken,
1215
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
1216
+ });
1217
+ let botUser;
1218
+ await runWithReconnect(async () => {
1219
+ botUser = await fetchMattermostMe(client);
1220
+ }, {
1221
+ abortSignal: opts.abortSignal,
1222
+ jitterRatio: .2,
1223
+ shouldReconnect: ({ outcome }) => outcome === "rejected",
1224
+ onError: (err) => {
1225
+ runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
1226
+ opts.statusSink?.({
1227
+ lastError: String(err),
1228
+ connected: false
1229
+ });
1230
+ },
1231
+ onReconnect: (delayMs) => {
1232
+ runtime.log?.(`mattermost: API not accessible, retrying in ${Math.round(delayMs / 1e3)}s`);
1233
+ }
1234
+ });
1235
+ if (opts.abortSignal?.aborted) return;
1236
+ const botUserId = botUser.id;
1237
+ const botUsername = normalizeOptionalString(botUser.username);
1238
+ runtime.log?.(`mattermost connected as ${botUsername ? `@${botUsername}` : botUserId}`);
1239
+ await registerMattermostMonitorSlashCommands({
1240
+ client,
1241
+ cfg,
1242
+ runtime,
1243
+ account,
1244
+ baseUrl,
1245
+ botUserId
1246
+ });
1247
+ const slashEnabled = getSlashCommandState(account.accountId) != null;
1248
+ setInteractionSecret(account.accountId, botToken);
1249
+ const interactionPath = resolveInteractionCallbackPath(account.accountId);
1250
+ const callbackUrl = computeInteractionCallbackUrl(account.accountId, {
1251
+ gateway: cfg.gateway,
1252
+ interactions: account.config.interactions
1253
+ });
1254
+ setInteractionCallbackUrl(account.accountId, callbackUrl);
1255
+ const allowedInteractionSourceIps = normalizeInteractionSourceIps(account.config.interactions?.allowedSourceIps);
1256
+ try {
1257
+ const mmHost = new URL(baseUrl).hostname;
1258
+ const callbackHost = new URL(callbackUrl).hostname;
1259
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} (loopback) while baseUrl is ${baseUrl}. This MAY be unreachable depending on your deployment. If button clicks don't work, set channels.mattermost.interactions.callbackBaseUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
1260
+ if (!isLoopbackHost(callbackHost) && allowedInteractionSourceIps.length === 0) runtime.error?.(`mattermost: interactions callbackUrl resolved to ${callbackUrl} without channels.mattermost.interactions.allowedSourceIps. For safety, non-loopback callback sources will be rejected until you allowlist the Mattermost server or trusted ingress IPs.`);
1261
+ } catch {}
1262
+ const effectiveInteractionSourceIps = allowedInteractionSourceIps.length > 0 ? allowedInteractionSourceIps : ["127.0.0.1", "::1"];
1263
+ const unregisterInteractions = registerPluginHttpRoute({
1264
+ path: interactionPath,
1265
+ fallbackPath: "/mattermost/interactions/default",
1266
+ auth: "plugin",
1267
+ handler: createMattermostInteractionHandler({
1268
+ client,
1269
+ botUserId,
1270
+ accountId: account.accountId,
1271
+ allowedSourceIps: effectiveInteractionSourceIps,
1272
+ trustedProxies: cfg.gateway?.trustedProxies,
1273
+ allowRealIpFallback: cfg.gateway?.allowRealIpFallback === true,
1274
+ handleInteraction: handleModelPickerInteraction,
1275
+ authorizeButtonClick: async ({ payload, post }) => {
1276
+ const channelInfo = await resolveChannelInfo(payload.channel_id);
1277
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1278
+ cfg,
1279
+ surface: "mattermost"
1280
+ });
1281
+ const decision = await authorizeMattermostCommandInvocation({
1282
+ account,
1283
+ cfg,
1284
+ senderId: payload.user_id,
1285
+ senderName: payload.user_name ?? "",
1286
+ channelId: payload.channel_id,
1287
+ channelInfo,
1288
+ readStoreAllowFrom: pairing.readAllowFromStore,
1289
+ allowTextCommands,
1290
+ hasControlCommand: false
1291
+ });
1292
+ if (decision.ok) return { ok: true };
1293
+ return {
1294
+ ok: false,
1295
+ response: {
1296
+ update: {
1297
+ message: post.message ?? "",
1298
+ props: post.props ?? void 0
1299
+ },
1300
+ ephemeral_text: `OpenClaw ignored this action for ${decision.roomLabel}.`
1301
+ }
1302
+ };
1303
+ },
1304
+ resolveSessionKey: async ({ channelId, userId, post }) => {
1305
+ const channelInfo = await resolveChannelInfo(channelId);
1306
+ if (!channelInfo?.type) {
1307
+ logVerboseMessage(`mattermost: drop interaction session event (cannot resolve channel type for ${channelId})`);
1308
+ throw new Error("Mattermost channel type could not be resolved");
1309
+ }
1310
+ const kind = mapMattermostChannelTypeToChatType(channelInfo.type);
1311
+ const teamId = channelInfo?.team_id ?? void 0;
1312
+ const route = core.channel.routing.resolveAgentRoute({
1313
+ cfg,
1314
+ channel: "mattermost",
1315
+ accountId: account.accountId,
1316
+ teamId,
1317
+ peer: {
1318
+ kind,
1319
+ id: kind === "direct" ? userId : channelId
1320
+ }
1321
+ });
1322
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1323
+ return resolveMattermostThreadSessionContext({
1324
+ baseSessionKey: route.sessionKey,
1325
+ kind,
1326
+ postId: post.id || void 0,
1327
+ replyToMode,
1328
+ threadRootId: post.root_id
1329
+ }).sessionKey;
1330
+ },
1331
+ dispatchButtonClick: async (optsLocal) => {
1332
+ const channelInfo = await resolveChannelInfo(optsLocal.channelId);
1333
+ if (!channelInfo?.type) {
1334
+ logVerboseMessage(`mattermost: drop interaction dispatch (cannot resolve channel type for ${optsLocal.channelId})`);
1335
+ return;
1336
+ }
1337
+ const kind = mapMattermostChannelTypeToChatType(channelInfo.type);
1338
+ const chatType = channelChatType(kind);
1339
+ const teamId = channelInfo?.team_id ?? void 0;
1340
+ const channelName = channelInfo?.name ?? void 0;
1341
+ const channelDisplay = channelInfo?.display_name ?? channelName ?? optsLocal.channelId;
1342
+ const route = core.channel.routing.resolveAgentRoute({
1343
+ cfg,
1344
+ channel: "mattermost",
1345
+ accountId: account.accountId,
1346
+ teamId,
1347
+ peer: {
1348
+ kind,
1349
+ id: kind === "direct" ? optsLocal.userId : optsLocal.channelId
1350
+ }
1351
+ });
1352
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1353
+ const threadContext = resolveMattermostThreadSessionContext({
1354
+ baseSessionKey: route.sessionKey,
1355
+ kind,
1356
+ postId: optsLocal.post.id || optsLocal.postId,
1357
+ replyToMode,
1358
+ threadRootId: optsLocal.post.root_id
1359
+ });
1360
+ const to = kind === "direct" ? `user:${optsLocal.userId}` : `channel:${optsLocal.channelId}`;
1361
+ const bodyText = `[Button click: user @${optsLocal.userName} selected "${optsLocal.actionName}"]`;
1362
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
1363
+ Body: bodyText,
1364
+ BodyForAgent: bodyText,
1365
+ RawBody: bodyText,
1366
+ CommandBody: bodyText,
1367
+ From: kind === "direct" ? `mattermost:${optsLocal.userId}` : kind === "group" ? `mattermost:group:${optsLocal.channelId}` : `mattermost:channel:${optsLocal.channelId}`,
1368
+ To: to,
1369
+ SessionKey: threadContext.sessionKey,
1370
+ ParentSessionKey: threadContext.parentSessionKey,
1371
+ AccountId: route.accountId,
1372
+ ChatType: chatType,
1373
+ ConversationLabel: `mattermost:${optsLocal.userName}`,
1374
+ GroupSubject: kind !== "direct" ? channelDisplay : void 0,
1375
+ GroupChannel: channelName ? `#${channelName}` : void 0,
1376
+ GroupSpace: teamId,
1377
+ SenderName: optsLocal.userName,
1378
+ SenderId: optsLocal.userId,
1379
+ Provider: "mattermost",
1380
+ Surface: "mattermost",
1381
+ MessageSid: `interaction:${optsLocal.postId}:${optsLocal.actionId}`,
1382
+ ReplyToId: threadContext.effectiveReplyToId,
1383
+ MessageThreadId: threadContext.effectiveReplyToId,
1384
+ WasMentioned: true,
1385
+ CommandAuthorized: false,
1386
+ OriginatingChannel: "mattermost",
1387
+ OriginatingTo: to
1388
+ });
1389
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
1390
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
1391
+ cfg,
1392
+ channel: "mattermost",
1393
+ accountId: account.accountId
1394
+ });
1395
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
1396
+ cfg,
1397
+ agentId: route.agentId,
1398
+ channel: "mattermost",
1399
+ accountId: account.accountId,
1400
+ typing: {
1401
+ start: () => sendTypingIndicator(optsLocal.channelId, threadContext.effectiveReplyToId),
1402
+ onStartError: (err) => {
1403
+ logTypingFailure({
1404
+ log: (message) => logger.debug?.(message),
1405
+ channel: "mattermost",
1406
+ target: optsLocal.channelId,
1407
+ error: err
1408
+ });
1409
+ }
1410
+ }
1411
+ });
1412
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
1413
+ isDirect: kind === "direct",
1414
+ dmRetryOptions: account.config.dmChannelRetry
1415
+ });
1416
+ const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
1417
+ ...replyPipeline,
1418
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1419
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1420
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
1421
+ deliver: async (payload) => {
1422
+ await deliverMattermostReplyPayload({
1423
+ core,
1424
+ cfg,
1425
+ payload,
1426
+ to,
1427
+ accountId: account.accountId,
1428
+ agentId: route.agentId,
1429
+ replyToId: resolveMattermostReplyRootId({
1430
+ kind,
1431
+ threadRootId: threadContext.effectiveReplyToId,
1432
+ replyToId: payload.replyToId
1433
+ }),
1434
+ textLimit,
1435
+ tableMode,
1436
+ sendMessage: sendMessageMattermost,
1437
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1438
+ });
1439
+ runtime.log?.(`delivered button-click reply to ${to}`);
1440
+ },
1441
+ onError: (err, info) => {
1442
+ runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
1443
+ },
1444
+ onReplyStart: typingCallbacks?.onReplyStart
1445
+ });
1446
+ await core.channel.reply.dispatchReplyFromConfig({
1447
+ ctx: ctxPayload,
1448
+ cfg,
1449
+ dispatcher,
1450
+ replyOptions: {
1451
+ ...replyOptions,
1452
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1453
+ onModelSelected
1454
+ }
1455
+ });
1456
+ markDispatchIdle();
1457
+ },
1458
+ log: (msg) => runtime.log?.(msg)
1459
+ }),
1460
+ pluginId: "mattermost",
1461
+ source: "mattermost-interactions",
1462
+ accountId: account.accountId,
1463
+ log: (msg) => runtime.log?.(msg)
1464
+ });
1465
+ const logger = core.logging.getChildLogger({ module: "mattermost" });
1466
+ const logVerboseMessage = (message) => {
1467
+ if (!core.logging.shouldLogVerbose()) return;
1468
+ logger.debug?.(message);
1469
+ };
1470
+ const mediaMaxBytes = resolveChannelMediaMaxBytes({
1471
+ cfg,
1472
+ resolveChannelLimitMb: () => void 0,
1473
+ accountId: account.accountId
1474
+ }) ?? 8388608;
1475
+ const historyLimit = Math.max(0, cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
1476
+ const channelHistories = /* @__PURE__ */ new Map();
1477
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
1478
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
1479
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
1480
+ providerConfigPresent: cfg.channels?.mattermost !== void 0,
1481
+ groupPolicy: account.config.groupPolicy,
1482
+ defaultGroupPolicy
1483
+ });
1484
+ warnMissingProviderGroupPolicyFallbackOnce({
1485
+ providerMissingFallbackApplied,
1486
+ providerKey: "mattermost",
1487
+ accountId: account.accountId,
1488
+ log: (message) => logVerboseMessage(message)
1489
+ });
1490
+ const { resolveMattermostMedia, sendTypingIndicator, resolveChannelInfo, resolveUserInfo, updateModelPickerPost } = createMattermostMonitorResources({
1491
+ accountId: account.accountId,
1492
+ callbackUrl,
1493
+ client,
1494
+ logger: { debug: (message) => logger.debug?.(String(message)) },
1495
+ mediaMaxBytes,
1496
+ saveRemoteMedia: (params) => core.channel.media.saveRemoteMedia(params),
1497
+ mediaKindFromMime: (contentType) => core.media.mediaKindFromMime(contentType)
1498
+ });
1499
+ const runModelPickerCommand = async (params) => {
1500
+ const to = params.kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
1501
+ const fromLabel = params.kind === "direct" ? `Mattermost DM from ${params.senderName}` : `Mattermost message in ${params.roomLabel} from ${params.senderName}`;
1502
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
1503
+ Body: params.commandText,
1504
+ BodyForAgent: params.commandText,
1505
+ RawBody: params.commandText,
1506
+ CommandBody: params.commandText,
1507
+ From: params.kind === "direct" ? `mattermost:${params.senderId}` : params.kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
1508
+ To: to,
1509
+ SessionKey: params.sessionKey,
1510
+ ParentSessionKey: params.parentSessionKey,
1511
+ AccountId: params.route.accountId,
1512
+ ChatType: params.chatType,
1513
+ ConversationLabel: fromLabel,
1514
+ GroupSubject: params.kind !== "direct" ? params.channelDisplay || params.roomLabel : void 0,
1515
+ GroupChannel: params.channelName ? `#${params.channelName}` : void 0,
1516
+ GroupSpace: params.teamId,
1517
+ SenderName: params.senderName,
1518
+ SenderId: params.senderId,
1519
+ Provider: "mattermost",
1520
+ Surface: "mattermost",
1521
+ MessageSid: params.messageSid ?? `interaction:${params.postId}:${Date.now()}`,
1522
+ ReplyToId: params.effectiveReplyToId,
1523
+ MessageThreadId: params.effectiveReplyToId,
1524
+ Timestamp: Date.now(),
1525
+ WasMentioned: true,
1526
+ CommandAuthorized: params.commandAuthorized,
1527
+ CommandSource: "native",
1528
+ OriginatingChannel: "mattermost",
1529
+ OriginatingTo: to
1530
+ });
1531
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
1532
+ cfg,
1533
+ channel: "mattermost",
1534
+ accountId: account.accountId
1535
+ });
1536
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
1537
+ const shouldDeliverReplies = params.deliverReplies === true;
1538
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
1539
+ cfg,
1540
+ agentId: params.route.agentId,
1541
+ channel: "mattermost",
1542
+ accountId: account.accountId,
1543
+ typing: shouldDeliverReplies ? {
1544
+ start: () => sendTypingIndicator(params.channelId, params.effectiveReplyToId),
1545
+ onStartError: (err) => {
1546
+ logTypingFailure({
1547
+ log: (message) => logger.debug?.(message),
1548
+ channel: "mattermost",
1549
+ target: params.channelId,
1550
+ error: err
1551
+ });
1552
+ }
1553
+ } : void 0
1554
+ });
1555
+ const capturedTexts = [];
1556
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
1557
+ isDirect: params.kind === "direct",
1558
+ dmRetryOptions: account.config.dmChannelRetry
1559
+ });
1560
+ const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
1561
+ ...replyPipeline,
1562
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1563
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1564
+ deliver: async (payload) => {
1565
+ const trimmedPayload = {
1566
+ ...payload,
1567
+ text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
1568
+ };
1569
+ if (!shouldDeliverReplies) {
1570
+ if (trimmedPayload.text) capturedTexts.push(trimmedPayload.text);
1571
+ return;
1572
+ }
1573
+ await deliverMattermostReplyPayload({
1574
+ core,
1575
+ cfg,
1576
+ payload: trimmedPayload,
1577
+ to,
1578
+ accountId: account.accountId,
1579
+ agentId: params.route.agentId,
1580
+ replyToId: resolveMattermostReplyRootId({
1581
+ kind: params.kind,
1582
+ threadRootId: params.effectiveReplyToId,
1583
+ replyToId: trimmedPayload.replyToId
1584
+ }),
1585
+ textLimit,
1586
+ tableMode: "off",
1587
+ sendMessage: sendMessageMattermost,
1588
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1589
+ });
1590
+ },
1591
+ onError: (err, info) => {
1592
+ runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
1593
+ },
1594
+ onReplyStart: typingCallbacks?.onReplyStart
1595
+ });
1596
+ await core.channel.reply.withReplyDispatcher({
1597
+ dispatcher,
1598
+ onSettled: () => {
1599
+ markDispatchIdle();
1600
+ },
1601
+ run: () => core.channel.reply.dispatchReplyFromConfig({
1602
+ ctx: ctxPayload,
1603
+ cfg,
1604
+ dispatcher,
1605
+ replyOptions: {
1606
+ ...replyOptions,
1607
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1608
+ onModelSelected
1609
+ }
1610
+ })
1611
+ });
1612
+ return capturedTexts.join("\n\n").trim();
1613
+ };
1614
+ async function handleModelPickerInteraction(params) {
1615
+ const pickerState = parseMattermostModelPickerContext(params.context);
1616
+ if (!pickerState) return null;
1617
+ if (pickerState.ownerUserId !== params.payload.user_id) return { ephemeral_text: "Only the person who opened this picker can use it." };
1618
+ const channelInfo = await resolveChannelInfo(params.payload.channel_id);
1619
+ const pickerCommandText = pickerState.action === "select" ? `/model ${pickerState.provider}/${pickerState.model}` : pickerState.action === "list" ? `/models ${pickerState.provider}` : "/models";
1620
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1621
+ cfg,
1622
+ surface: "mattermost"
1623
+ });
1624
+ const hasControlCommand = core.channel.text.hasControlCommand(pickerCommandText, cfg);
1625
+ const auth = await authorizeMattermostCommandInvocation({
1626
+ account,
1627
+ cfg,
1628
+ senderId: params.payload.user_id,
1629
+ senderName: params.userName,
1630
+ channelId: params.payload.channel_id,
1631
+ channelInfo,
1632
+ readStoreAllowFrom: pairing.readAllowFromStore,
1633
+ allowTextCommands,
1634
+ hasControlCommand
1635
+ });
1636
+ if (!auth.ok) {
1637
+ if (auth.denyReason === "dm-pairing") {
1638
+ const { code } = await pairing.upsertPairingRequest({
1639
+ id: params.payload.user_id,
1640
+ meta: { name: params.userName }
1641
+ });
1642
+ return { ephemeral_text: core.channel.pairing.buildPairingReply({
1643
+ channel: "mattermost",
1644
+ idLine: `Your Mattermost user id: ${params.payload.user_id}`,
1645
+ code
1646
+ }) };
1647
+ }
1648
+ return { ephemeral_text: auth.denyReason === "unknown-channel" ? "Temporary error: unable to determine channel type. Please try again." : auth.denyReason === "dm-disabled" ? "This bot is not accepting direct messages." : auth.denyReason === "channels-disabled" ? "Model picker actions are disabled in channels." : auth.denyReason === "channel-no-allowlist" ? "Model picker actions are not configured for this channel." : "Unauthorized." };
1649
+ }
1650
+ const kind = auth.kind;
1651
+ const chatType = auth.chatType;
1652
+ const teamId = auth.channelInfo.team_id ?? params.payload.team_id ?? void 0;
1653
+ const channelName = auth.channelName || void 0;
1654
+ const channelDisplay = auth.channelDisplay || auth.channelName || params.payload.channel_id;
1655
+ const roomLabel = auth.roomLabel;
1656
+ const route = core.channel.routing.resolveAgentRoute({
1657
+ cfg,
1658
+ channel: "mattermost",
1659
+ accountId: account.accountId,
1660
+ teamId,
1661
+ peer: {
1662
+ kind,
1663
+ id: kind === "direct" ? params.payload.user_id : params.payload.channel_id
1664
+ }
1665
+ });
1666
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1667
+ const threadContext = resolveMattermostThreadSessionContext({
1668
+ baseSessionKey: route.sessionKey,
1669
+ kind,
1670
+ postId: params.post.id || params.payload.post_id,
1671
+ replyToMode,
1672
+ threadRootId: params.post.root_id
1673
+ });
1674
+ const modelSessionRoute = {
1675
+ agentId: route.agentId,
1676
+ sessionKey: threadContext.sessionKey
1677
+ };
1678
+ const data = await buildModelsProviderData(cfg, route.agentId);
1679
+ if (data.providers.length === 0) return await updateModelPickerPost({
1680
+ channelId: params.payload.channel_id,
1681
+ postId: params.payload.post_id,
1682
+ message: "No models available."
1683
+ });
1684
+ if (pickerState.action === "providers" || pickerState.action === "back") {
1685
+ const currentModel = resolveMattermostModelPickerCurrentModel({
1686
+ cfg,
1687
+ route: modelSessionRoute,
1688
+ data
1689
+ });
1690
+ const view = renderMattermostProviderPickerView({
1691
+ ownerUserId: pickerState.ownerUserId,
1692
+ data,
1693
+ currentModel
1694
+ });
1695
+ return await updateModelPickerPost({
1696
+ channelId: params.payload.channel_id,
1697
+ postId: params.payload.post_id,
1698
+ message: view.text,
1699
+ buttons: view.buttons
1700
+ });
1701
+ }
1702
+ if (pickerState.action === "list") {
1703
+ const currentModel = resolveMattermostModelPickerCurrentModel({
1704
+ cfg,
1705
+ route: modelSessionRoute,
1706
+ data
1707
+ });
1708
+ const view = renderMattermostModelsPickerView({
1709
+ ownerUserId: pickerState.ownerUserId,
1710
+ data,
1711
+ provider: pickerState.provider,
1712
+ page: pickerState.page,
1713
+ currentModel
1714
+ });
1715
+ return await updateModelPickerPost({
1716
+ channelId: params.payload.channel_id,
1717
+ postId: params.payload.post_id,
1718
+ message: view.text,
1719
+ buttons: view.buttons
1720
+ });
1721
+ }
1722
+ const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
1723
+ if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
1724
+ (async () => {
1725
+ try {
1726
+ await runModelPickerCommand({
1727
+ commandText: `/model ${targetModelRef}`,
1728
+ commandAuthorized: auth.commandAuthorized,
1729
+ route,
1730
+ sessionKey: threadContext.sessionKey,
1731
+ parentSessionKey: threadContext.parentSessionKey,
1732
+ channelId: params.payload.channel_id,
1733
+ senderId: params.payload.user_id,
1734
+ senderName: params.userName,
1735
+ kind,
1736
+ chatType,
1737
+ channelName,
1738
+ channelDisplay,
1739
+ roomLabel,
1740
+ teamId,
1741
+ postId: params.payload.post_id,
1742
+ messageSid: buildMattermostModelPickerSelectMessageSid({
1743
+ postId: params.payload.post_id,
1744
+ provider: pickerState.provider,
1745
+ model: pickerState.model
1746
+ }),
1747
+ effectiveReplyToId: threadContext.effectiveReplyToId,
1748
+ deliverReplies: true
1749
+ });
1750
+ const updatedModel = resolveMattermostModelPickerCurrentModel({
1751
+ cfg,
1752
+ route: modelSessionRoute,
1753
+ data,
1754
+ readConsistency: "latest"
1755
+ });
1756
+ const view = renderMattermostModelsPickerView({
1757
+ ownerUserId: pickerState.ownerUserId,
1758
+ data,
1759
+ provider: pickerState.provider,
1760
+ page: pickerState.page,
1761
+ currentModel: updatedModel
1762
+ });
1763
+ await updateModelPickerPost({
1764
+ channelId: params.payload.channel_id,
1765
+ postId: params.payload.post_id,
1766
+ message: view.text,
1767
+ buttons: view.buttons
1768
+ });
1769
+ } catch (err) {
1770
+ runtime.error?.(`mattermost model picker select failed: ${String(err)}`);
1771
+ }
1772
+ })();
1773
+ return {};
1774
+ }
1775
+ const handlePost = async (post, payload, messageIds) => {
1776
+ const channelId = post.channel_id ?? payload.data?.channel_id ?? payload.broadcast?.channel_id;
1777
+ if (!channelId) {
1778
+ logVerboseMessage("mattermost: drop post (missing channel id)");
1779
+ return;
1780
+ }
1781
+ const allMessageIds = messageIds?.length ? messageIds : post.id ? [post.id] : [];
1782
+ if (allMessageIds.length === 0) {
1783
+ logVerboseMessage("mattermost: drop post (missing message id)");
1784
+ return;
1785
+ }
1786
+ if (await processMattermostReplayGuardedPost({
1787
+ accountId: account.accountId,
1788
+ messageIds: allMessageIds,
1789
+ handlePost: async () => {
1790
+ const senderId = post.user_id ?? payload.broadcast?.user_id;
1791
+ if (!senderId) {
1792
+ logVerboseMessage("mattermost: drop post (missing sender id)");
1793
+ return;
1794
+ }
1795
+ if (senderId === botUserId) {
1796
+ logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
1797
+ return;
1798
+ }
1799
+ if (isSystemPost(post)) {
1800
+ logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
1801
+ return;
1802
+ }
1803
+ const channelInfo = await resolveChannelInfo(channelId);
1804
+ const channelType = normalizeOptionalString(channelInfo?.type) ?? normalizeOptionalString(payload.data?.channel_type);
1805
+ if (!channelType) {
1806
+ logVerboseMessage(`mattermost: drop post (cannot resolve channel type for ${channelId})`);
1807
+ return;
1808
+ }
1809
+ const kind = resolveMattermostTrustedChatKind({ channelType });
1810
+ const chatType = channelChatType(kind);
1811
+ const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
1812
+ const rawPostText = typeof post.message === "string" ? post.message : "";
1813
+ const rawText = normalizeOptionalString(rawPostText) ?? "";
1814
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1815
+ cfg,
1816
+ surface: "mattermost"
1817
+ });
1818
+ const isControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(rawText, cfg);
1819
+ const accessDecision = await resolveMattermostMonitorInboundAccess({
1820
+ account,
1821
+ cfg,
1822
+ senderId,
1823
+ senderName,
1824
+ channelId,
1825
+ kind,
1826
+ groupPolicy,
1827
+ readStoreAllowFrom: pairing.readAllowFromStore,
1828
+ allowTextCommands,
1829
+ hasControlCommand: isControlCommand,
1830
+ eventKind: "message",
1831
+ mayPair: true
1832
+ });
1833
+ const commandAuthorized = accessDecision.commandAccess.authorized;
1834
+ if (accessDecision.ingress.decision !== "allow") {
1835
+ if (kind === "direct") {
1836
+ if (accessDecision.ingress.reasonCode === "dm_policy_disabled") {
1837
+ logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
1838
+ return;
1839
+ }
1840
+ if (accessDecision.ingress.decision === "pairing") {
1841
+ const { code, created } = await pairing.upsertPairingRequest({
1842
+ id: senderId,
1843
+ meta: { name: senderName }
1844
+ });
1845
+ logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
1846
+ if (created) try {
1847
+ await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
1848
+ channel: "mattermost",
1849
+ idLine: `Your Mattermost user id: ${senderId}`,
1850
+ code
1851
+ }), {
1852
+ cfg,
1853
+ accountId: account.accountId
1854
+ });
1855
+ opts.statusSink?.({ lastOutboundAt: Date.now() });
1856
+ } catch (err) {
1857
+ logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
1858
+ }
1859
+ return;
1860
+ }
1861
+ logVerboseMessage(formatMattermostDirectMessageDropLog({
1862
+ senderId,
1863
+ dmPolicy,
1864
+ reasonCode: accessDecision.senderAccess.reasonCode
1865
+ }));
1866
+ return;
1867
+ }
1868
+ if (accessDecision.ingress.reasonCode === "group_policy_disabled") {
1869
+ logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
1870
+ return;
1871
+ }
1872
+ if (accessDecision.ingress.reasonCode === "group_policy_empty_allowlist") {
1873
+ logVerboseMessage("mattermost: drop group message (no group allowlist)");
1874
+ return;
1875
+ }
1876
+ if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
1877
+ logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
1878
+ return;
1879
+ }
1880
+ logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
1881
+ return;
1882
+ }
1883
+ if (kind !== "direct" && accessDecision.commandAccess.shouldBlockControlCommand) {
1884
+ logInboundDrop({
1885
+ log: logVerboseMessage,
1886
+ channel: "mattermost",
1887
+ reason: "control command (unauthorized)",
1888
+ target: senderId
1889
+ });
1890
+ return;
1891
+ }
1892
+ const teamId = payload.data?.team_id ?? channelInfo?.team_id ?? void 0;
1893
+ const channelName = payload.data?.channel_name ?? channelInfo?.name ?? "";
1894
+ const channelDisplay = payload.data?.channel_display_name ?? channelInfo?.display_name ?? channelName;
1895
+ const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${channelId}`;
1896
+ const route = core.channel.routing.resolveAgentRoute({
1897
+ cfg,
1898
+ channel: "mattermost",
1899
+ accountId: account.accountId,
1900
+ teamId,
1901
+ peer: {
1902
+ kind,
1903
+ id: kind === "direct" ? senderId : channelId
1904
+ }
1905
+ });
1906
+ const baseSessionKey = route.sessionKey;
1907
+ const threadRootId = normalizeOptionalString(post.root_id);
1908
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
1909
+ const { effectiveReplyToId, sessionKey, parentSessionKey } = resolveMattermostThreadSessionContext({
1910
+ baseSessionKey,
1911
+ kind,
1912
+ postId: post.id,
1913
+ replyToMode,
1914
+ threadRootId
1915
+ });
1916
+ const historyKey = kind === "direct" ? null : sessionKey;
1917
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
1918
+ const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
1919
+ const pendingBody = rawText || (post.file_ids?.length ? `[Mattermost ${post.file_ids.length === 1 ? "file" : "files"}]` : "");
1920
+ const pendingSender = senderName;
1921
+ const recordPendingHistory = () => {
1922
+ const trimmed = pendingBody.trim();
1923
+ createChannelHistoryWindow({ historyMap: channelHistories }).record({
1924
+ limit: historyLimit,
1925
+ historyKey: historyKey ?? "",
1926
+ entry: historyKey && trimmed ? {
1927
+ sender: pendingSender,
1928
+ body: trimmed,
1929
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
1930
+ messageId: post.id ?? void 0
1931
+ } : null
1932
+ });
1933
+ };
1934
+ const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
1935
+ const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
1936
+ const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
1937
+ triggered: false,
1938
+ stripped: rawText
1939
+ };
1940
+ const oncharTriggered = oncharResult.triggered;
1941
+ const canDetectMention = Boolean(botUsername) || mentionRegexes.length > 0;
1942
+ const threadAlreadyEngaged = kind !== "direct" && effectiveReplyToId ? await hasMattermostThreadParticipationWithPersistence({
1943
+ accountId: account.accountId,
1944
+ channelId,
1945
+ threadRootId: effectiveReplyToId
1946
+ }) : false;
1947
+ const mentionDecision = evaluateMattermostMentionGate({
1948
+ kind,
1949
+ cfg,
1950
+ accountId: account.accountId,
1951
+ channelId,
1952
+ threadRootId,
1953
+ requireMentionOverride: account.requireMention,
1954
+ resolveRequireMention: core.channel.groups.resolveRequireMention,
1955
+ wasMentioned,
1956
+ threadAlreadyEngaged,
1957
+ isControlCommand,
1958
+ commandAuthorized,
1959
+ oncharEnabled,
1960
+ oncharTriggered,
1961
+ canDetectMention
1962
+ });
1963
+ const { shouldRequireMention, shouldBypassMention } = mentionDecision;
1964
+ if (mentionDecision.dropReason === "onchar-not-triggered") {
1965
+ logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
1966
+ recordPendingHistory();
1967
+ return;
1968
+ }
1969
+ if (mentionDecision.dropReason === "missing-mention") {
1970
+ logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
1971
+ recordPendingHistory();
1972
+ return;
1973
+ }
1974
+ const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
1975
+ const mediaList = await resolveMattermostMedia(fileIds);
1976
+ const mediaPlaceholder = buildMattermostAttachmentPlaceholder(mediaList);
1977
+ const bodyText = normalizeMention(formatMattermostInboundMediaText({
1978
+ body: [oncharTriggered ? oncharResult.stripped : rawText, mediaPlaceholder].filter(Boolean).join("\n").trim(),
1979
+ mediaPlaceholder,
1980
+ expectedCount: fileIds.length,
1981
+ mediaCount: mediaList.length
1982
+ }), botUsername);
1983
+ if (shouldDropEmptyMattermostBody({
1984
+ bodyText,
1985
+ rawText: rawPostText,
1986
+ botUsername
1987
+ })) {
1988
+ logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
1989
+ return;
1990
+ }
1991
+ const bodyForAgent = bodyText || rawText.trim();
1992
+ core.channel.activity.record({
1993
+ channel: "mattermost",
1994
+ accountId: account.accountId,
1995
+ direction: "inbound"
1996
+ });
1997
+ const fromLabel = formatInboundFromLabel$1({
1998
+ isGroup: kind !== "direct",
1999
+ groupLabel: channelDisplay || roomLabel,
2000
+ groupId: channelId,
2001
+ groupFallback: roomLabel || "Channel",
2002
+ directLabel: senderName,
2003
+ directId: senderId
2004
+ });
2005
+ const textWithId = `${bodyText}\n[mattermost message id: ${post.id ?? "unknown"} channel: ${channelId}]`;
2006
+ let combinedBody = core.channel.reply.formatInboundEnvelope({
2007
+ channel: "Mattermost",
2008
+ from: fromLabel,
2009
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2010
+ body: textWithId,
2011
+ chatType,
2012
+ sender: {
2013
+ name: senderName,
2014
+ id: senderId
2015
+ }
2016
+ });
2017
+ if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2018
+ historyKey,
2019
+ limit: historyLimit,
2020
+ currentMessage: combinedBody,
2021
+ formatEntry: (entry) => core.channel.reply.formatInboundEnvelope({
2022
+ channel: "Mattermost",
2023
+ from: fromLabel,
2024
+ timestamp: entry.timestamp,
2025
+ body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2026
+ chatType,
2027
+ senderLabel: entry.sender
2028
+ })
2029
+ });
2030
+ const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
2031
+ const mediaPayload = buildAgentMediaPayload(mediaList);
2032
+ const commandBody = rawText.trim();
2033
+ const inboundHistory = historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: channelHistories }).buildInboundHistory({
2034
+ historyKey,
2035
+ limit: historyLimit
2036
+ }) : void 0;
2037
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
2038
+ Body: combinedBody,
2039
+ BodyForAgent: bodyForAgent,
2040
+ InboundHistory: inboundHistory,
2041
+ RawBody: commandBody,
2042
+ CommandBody: commandBody,
2043
+ BodyForCommands: commandBody,
2044
+ From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
2045
+ To: to,
2046
+ SessionKey: sessionKey,
2047
+ ParentSessionKey: parentSessionKey,
2048
+ AccountId: route.accountId,
2049
+ ChatType: chatType,
2050
+ ConversationLabel: fromLabel,
2051
+ GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
2052
+ GroupChannel: channelName ? `#${channelName}` : void 0,
2053
+ GroupSpace: teamId,
2054
+ SenderName: senderName,
2055
+ SenderId: senderId,
2056
+ Provider: "mattermost",
2057
+ Surface: "mattermost",
2058
+ MessageSid: post.id ?? void 0,
2059
+ MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2060
+ MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2061
+ MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2062
+ ReplyToId: effectiveReplyToId,
2063
+ MessageThreadId: effectiveReplyToId,
2064
+ Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2065
+ WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2066
+ CommandAuthorized: commandAuthorized,
2067
+ CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2068
+ OriginatingChannel: "mattermost",
2069
+ OriginatingTo: to,
2070
+ ...mediaPayload
2071
+ });
2072
+ const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2073
+ dmScope: cfg.session?.dmScope,
2074
+ allowFrom: account.config.allowFrom,
2075
+ normalizeEntry: normalizeMattermostAllowEntry
2076
+ }) : null;
2077
+ const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
2078
+ const previewLine = truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n");
2079
+ logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
2080
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
2081
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2082
+ cfg,
2083
+ channel: "mattermost",
2084
+ accountId: account.accountId
2085
+ });
2086
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
2087
+ cfg,
2088
+ agentId: route.agentId,
2089
+ channel: "mattermost",
2090
+ accountId: account.accountId,
2091
+ typing: {
2092
+ start: () => sendTypingIndicator(channelId, effectiveReplyToId),
2093
+ onStartError: (err) => {
2094
+ logTypingFailure({
2095
+ log: (message) => logger.debug?.(message),
2096
+ channel: "mattermost",
2097
+ target: channelId,
2098
+ error: err
2099
+ });
2100
+ }
2101
+ }
2102
+ });
2103
+ const draftPreviewEnabled = account.streamingMode !== "off";
2104
+ const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
2105
+ const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
2106
+ const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
2107
+ client,
2108
+ channelId,
2109
+ rootId: effectiveReplyToId,
2110
+ throttleMs: 1200,
2111
+ log: logVerboseMessage,
2112
+ warn: logVerboseMessage
2113
+ }) : createDisabledMattermostDraftStream();
2114
+ let lastPartialText = "";
2115
+ const progressDraft = createChannelProgressDraftCompositor({
2116
+ entry: account.config,
2117
+ mode: account.streamingMode,
2118
+ active: draftPreviewEnabled,
2119
+ seed: `${account.accountId}:${channelId}`,
2120
+ update: async (previewText, options) => {
2121
+ draftStream.update(previewText);
2122
+ if (options?.flush) await draftStream.flush();
2123
+ }
2124
+ });
2125
+ const previewState = { finalizedViaPreviewPost: false };
2126
+ const resolvePreviewFinalText = (text) => {
2127
+ if (typeof text !== "string") return;
2128
+ const formatted = core.channel.text.convertMarkdownTables(text, tableMode);
2129
+ const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
2130
+ const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
2131
+ if (!chunks.length && formatted) chunks.push(formatted);
2132
+ if (chunks.length != 1) return;
2133
+ const trimmed = chunks[0]?.trim();
2134
+ if (!trimmed) return;
2135
+ if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
2136
+ return trimmed;
2137
+ };
2138
+ const updateDraftFromPartial = (text) => {
2139
+ const cleaned = text?.trim();
2140
+ if (!cleaned) return;
2141
+ if (cleaned === lastPartialText) return;
2142
+ if (lastPartialText && lastPartialText.startsWith(cleaned) && cleaned.length < lastPartialText.length) return;
2143
+ lastPartialText = cleaned;
2144
+ draftStream.update(cleaned);
2145
+ };
2146
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
2147
+ isDirect: kind === "direct",
2148
+ dmRetryOptions: account.config.dmChannelRetry
2149
+ });
2150
+ const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } = core.channel.reply.createReplyDispatcherWithTyping({
2151
+ ...replyPipeline,
2152
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
2153
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
2154
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
2155
+ typingCallbacks,
2156
+ deliver: async (payloadEntry, info) => {
2157
+ if (info.kind === "final") progressDraft.markFinalReplyStarted();
2158
+ const markThreadParticipation = () => {
2159
+ if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
2160
+ };
2161
+ await deliverMattermostReplyWithDraftPreview({
2162
+ payload: payloadEntry,
2163
+ info,
2164
+ kind,
2165
+ client,
2166
+ draftStream,
2167
+ effectiveReplyToId,
2168
+ resolvePreviewFinalText,
2169
+ previewState,
2170
+ logVerboseMessage,
2171
+ recordThreadParticipation: markThreadParticipation,
2172
+ deliverPayload: async (payloadToDeliver) => {
2173
+ const outcome = await deliverMattermostReplyPayload({
2174
+ core,
2175
+ cfg,
2176
+ payload: payloadToDeliver,
2177
+ to,
2178
+ accountId: account.accountId,
2179
+ agentId: route.agentId,
2180
+ replyToId: resolveMattermostReplyRootId({
2181
+ kind,
2182
+ threadRootId: effectiveReplyToId,
2183
+ replyToId: payloadToDeliver.replyToId
2184
+ }),
2185
+ textLimit,
2186
+ tableMode,
2187
+ sendMessage: sendMessageMattermost,
2188
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2189
+ });
2190
+ if (outcome === "text" || outcome === "media") markThreadParticipation();
2191
+ const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
2192
+ outcome,
2193
+ payload: payloadToDeliver,
2194
+ to,
2195
+ accountId: account.accountId,
2196
+ agentId: route.agentId
2197
+ });
2198
+ if (deliveryLog) runtime.log?.(deliveryLog);
2199
+ }
2200
+ });
2201
+ if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2202
+ },
2203
+ onError: (err, info) => {
2204
+ runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
2205
+ }
2206
+ });
2207
+ const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
2208
+ route,
2209
+ sessionKey: route.sessionKey
2210
+ });
2211
+ let dispatchSettledBeforeStart = false;
2212
+ try {
2213
+ await core.channel.inbound.run({
2214
+ channel: "mattermost",
2215
+ accountId: route.accountId,
2216
+ raw: post,
2217
+ adapter: {
2218
+ ingest: () => ({
2219
+ id: post.id ?? `${to}:${Date.now()}`,
2220
+ timestamp: post.create_at ?? void 0,
2221
+ rawText,
2222
+ textForAgent: ctxPayload.BodyForAgent,
2223
+ textForCommands: ctxPayload.CommandBody,
2224
+ raw: post
2225
+ }),
2226
+ resolveTurn: () => ({
2227
+ channel: "mattermost",
2228
+ accountId: route.accountId,
2229
+ routeSessionKey: route.sessionKey,
2230
+ storePath,
2231
+ ctxPayload,
2232
+ recordInboundSession: core.channel.session.recordInboundSession,
2233
+ record: {
2234
+ updateLastRoute: kind === "direct" ? {
2235
+ sessionKey: inboundLastRouteSessionKey,
2236
+ channel: "mattermost",
2237
+ to,
2238
+ accountId: route.accountId,
2239
+ mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
2240
+ ownerRecipient: pinnedMainDmOwner,
2241
+ senderRecipient: normalizeMattermostAllowEntry(senderId),
2242
+ onSkip: ({ ownerRecipient, senderRecipient }) => {
2243
+ logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
2244
+ }
2245
+ } : void 0
2246
+ } : void 0,
2247
+ onRecordError: (err) => {
2248
+ logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
2249
+ }
2250
+ },
2251
+ history: {
2252
+ isGroup: Boolean(historyKey),
2253
+ historyKey: historyKey ?? void 0,
2254
+ historyMap: channelHistories,
2255
+ limit: historyLimit
2256
+ },
2257
+ onPreDispatchFailure: async () => {
2258
+ dispatchSettledBeforeStart = true;
2259
+ await core.channel.reply.settleReplyDispatcher({
2260
+ dispatcher,
2261
+ onSettled: () => {
2262
+ markRunComplete();
2263
+ markDispatchIdle();
2264
+ }
2265
+ });
2266
+ },
2267
+ runDispatch: () => core.channel.reply.withReplyDispatcher({
2268
+ dispatcher,
2269
+ onSettled: () => {
2270
+ markDispatchIdle();
2271
+ },
2272
+ run: () => core.channel.reply.dispatchReplyFromConfig({
2273
+ ctx: ctxPayload,
2274
+ cfg,
2275
+ dispatcher,
2276
+ replyOptions: {
2277
+ ...replyOptions,
2278
+ allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
2279
+ onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
2280
+ disableBlockStreaming: true,
2281
+ ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2282
+ onModelSelected,
2283
+ onPartialReply: (payloadResult) => {
2284
+ if (account.streamingMode !== "progress") updateDraftFromPartial(payloadResult.text);
2285
+ },
2286
+ onAssistantMessageStart: () => {
2287
+ lastPartialText = "";
2288
+ progressDraft.resetReasoningProgress();
2289
+ if (account.streamingMode !== "progress") progressDraft.reset();
2290
+ },
2291
+ onReasoningEnd: () => {
2292
+ lastPartialText = "";
2293
+ progressDraft.resetReasoningProgress();
2294
+ if (account.streamingMode !== "progress") progressDraft.reset();
2295
+ },
2296
+ onReasoningStream: async (payloadResult) => {
2297
+ if (account.streamingMode === "progress") {
2298
+ await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2299
+ return;
2300
+ }
2301
+ if (!lastPartialText) draftStream.update("Thinking…");
2302
+ },
2303
+ onToolStart: async (payloadValue) => {
2304
+ if (!draftToolProgressEnabled) return;
2305
+ await progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2306
+ event: "tool",
2307
+ itemId: payloadValue.itemId,
2308
+ toolCallId: payloadValue.toolCallId,
2309
+ name: payloadValue.name,
2310
+ phase: payloadValue.phase,
2311
+ args: payloadValue.args
2312
+ }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
2313
+ },
2314
+ onItemEvent: async (payloadLocal) => {
2315
+ if (!draftToolProgressEnabled) return;
2316
+ await progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2317
+ event: "item",
2318
+ itemId: payloadLocal.itemId,
2319
+ itemKind: payloadLocal.kind,
2320
+ title: payloadLocal.title,
2321
+ name: payloadLocal.name,
2322
+ phase: payloadLocal.phase,
2323
+ status: payloadLocal.status,
2324
+ summary: payloadLocal.summary,
2325
+ progressText: payloadLocal.progressText,
2326
+ meta: payloadLocal.meta
2327
+ }), { startImmediately: true });
2328
+ }
2329
+ }
2330
+ })
2331
+ })
2332
+ })
2333
+ }
2334
+ });
2335
+ } finally {
2336
+ try {
2337
+ await draftStream.stop();
2338
+ } catch (err) {
2339
+ logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
2340
+ }
2341
+ if (!dispatchSettledBeforeStart) markRunComplete();
2342
+ }
2343
+ }
2344
+ }) === "duplicate") logVerboseMessage(`mattermost: drop post (dedupe account=${account.accountId} ids=${allMessageIds.length})`);
2345
+ };
2346
+ const handleReactionEvent = async (payload) => {
2347
+ const reactionData = payload.data?.reaction;
2348
+ if (!reactionData) return;
2349
+ let reaction = null;
2350
+ if (typeof reactionData === "string") try {
2351
+ reaction = JSON.parse(reactionData);
2352
+ } catch {
2353
+ return;
2354
+ }
2355
+ else if (typeof reactionData === "object") reaction = reactionData;
2356
+ if (!reaction) return;
2357
+ const userId = reaction.user_id?.trim();
2358
+ const postId = reaction.post_id?.trim();
2359
+ const emojiName = reaction.emoji_name?.trim();
2360
+ if (!userId || !postId || !emojiName) return;
2361
+ if (userId === botUserId) return;
2362
+ const action = payload.event === "reaction_removed" ? "removed" : "added";
2363
+ const senderInfo = await resolveUserInfo(userId);
2364
+ const senderName = normalizeOptionalString(senderInfo?.username) ?? userId;
2365
+ const channelId = resolveMattermostReactionChannelId(payload);
2366
+ if (!channelId) {
2367
+ logVerboseMessage(`mattermost: drop reaction (no channel_id in broadcast, cannot enforce policy)`);
2368
+ return;
2369
+ }
2370
+ const channelInfo = await resolveChannelInfo(channelId);
2371
+ if (!channelInfo?.type) {
2372
+ logVerboseMessage(`mattermost: drop reaction (cannot resolve channel type for ${channelId})`);
2373
+ return;
2374
+ }
2375
+ const kind = mapMattermostChannelTypeToChatType(channelInfo.type);
2376
+ const reactionAccess = await resolveMattermostMonitorInboundAccess({
2377
+ account,
2378
+ cfg,
2379
+ senderId: userId,
2380
+ senderName,
2381
+ channelId,
2382
+ kind,
2383
+ groupPolicy,
2384
+ readStoreAllowFrom: pairing.readAllowFromStore,
2385
+ allowTextCommands: false,
2386
+ hasControlCommand: false,
2387
+ eventKind: "reaction",
2388
+ mayPair: false
2389
+ });
2390
+ if (reactionAccess.ingress.decision !== "allow") {
2391
+ if (kind === "direct") logVerboseMessage(`mattermost: drop reaction (dmPolicy=${dmPolicy} sender=${userId} reason=${reactionAccess.senderAccess.reasonCode})`);
2392
+ else logVerboseMessage(`mattermost: drop reaction (groupPolicy=${groupPolicy} sender=${userId} reason=${reactionAccess.senderAccess.reasonCode} channel=${channelId})`);
2393
+ return;
2394
+ }
2395
+ const teamId = channelInfo?.team_id ?? void 0;
2396
+ const sessionKey = core.channel.routing.resolveAgentRoute({
2397
+ cfg,
2398
+ channel: "mattermost",
2399
+ accountId: account.accountId,
2400
+ teamId,
2401
+ peer: {
2402
+ kind,
2403
+ id: kind === "direct" ? userId : channelId
2404
+ }
2405
+ }).sessionKey;
2406
+ const eventText = `Mattermost reaction ${action}: :${emojiName}: by @${senderName} on post ${postId} in channel ${channelId}`;
2407
+ core.system.enqueueSystemEvent(eventText, {
2408
+ sessionKey,
2409
+ contextKey: `mattermost:reaction:${postId}:${emojiName}:${userId}:${action}`
2410
+ });
2411
+ logVerboseMessage(`mattermost reaction: ${action} :${emojiName}: by ${senderName} on ${postId}`);
2412
+ };
2413
+ const inboundDebounceMs = core.channel.debounce.resolveInboundDebounceMs({
2414
+ cfg,
2415
+ channel: "mattermost"
2416
+ });
2417
+ const debouncer = core.channel.debounce.createInboundDebouncer({
2418
+ debounceMs: inboundDebounceMs,
2419
+ buildKey: (entry) => {
2420
+ const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2421
+ if (!channelId) return null;
2422
+ const threadId = normalizeOptionalString(entry.post.root_id);
2423
+ const threadKey = threadId ? `thread:${threadId}` : "channel";
2424
+ return `mattermost:${account.accountId}:${channelId}:${threadKey}`;
2425
+ },
2426
+ shouldDebounce: (entry) => {
2427
+ if (entry.post.file_ids && entry.post.file_ids.length > 0) return false;
2428
+ const text = normalizeOptionalString(entry.post.message) ?? "";
2429
+ if (!text) return false;
2430
+ return !core.channel.commands.isControlCommandMessage(text, cfg);
2431
+ },
2432
+ onFlush: async (entries) => {
2433
+ const last = entries.at(-1);
2434
+ if (!last) return;
2435
+ if (entries.length === 1) {
2436
+ await handlePost(last.post, last.payload);
2437
+ return;
2438
+ }
2439
+ const combinedText = entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n");
2440
+ const mergedPost = {
2441
+ ...last.post,
2442
+ message: combinedText,
2443
+ file_ids: []
2444
+ };
2445
+ const ids = entries.map((entry) => entry.post.id).filter(Boolean);
2446
+ await handlePost(mergedPost, last.payload, ids.length > 0 ? ids : void 0);
2447
+ },
2448
+ onError: (err) => {
2449
+ runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
2450
+ }
2451
+ });
2452
+ const wsUrl = buildMattermostWsUrl(baseUrl);
2453
+ let seq = 1;
2454
+ const connectOnce = createMattermostConnectOnce({
2455
+ wsUrl,
2456
+ botToken,
2457
+ abortSignal: opts.abortSignal,
2458
+ statusSink: opts.statusSink,
2459
+ runtime,
2460
+ webSocketFactory: opts.webSocketFactory,
2461
+ nextSeq: () => seq++,
2462
+ getBotUpdateAt: async () => {
2463
+ return (await fetchMattermostMe(client)).update_at ?? 0;
2464
+ },
2465
+ onPosted: async (post, payload) => {
2466
+ await debouncer.enqueue({
2467
+ post,
2468
+ payload
2469
+ });
2470
+ },
2471
+ onReaction: async (payload) => {
2472
+ await handleReactionEvent(payload);
2473
+ }
2474
+ });
2475
+ let slashShutdownCleanup = null;
2476
+ if (slashEnabled) {
2477
+ const runAbortCleanup = () => {
2478
+ if (slashShutdownCleanup) return;
2479
+ const commands = getSlashCommandState(account.accountId)?.registeredCommands ?? [];
2480
+ deactivateSlashCommands(account.accountId);
2481
+ slashShutdownCleanup = cleanupSlashCommands({
2482
+ client,
2483
+ commands,
2484
+ log: (msg) => runtime.log?.(msg)
2485
+ }).catch((err) => {
2486
+ runtime.error?.(`mattermost: slash cleanup failed: ${String(err)}`);
2487
+ });
2488
+ };
2489
+ if (opts.abortSignal?.aborted) runAbortCleanup();
2490
+ else opts.abortSignal?.addEventListener("abort", runAbortCleanup, { once: true });
2491
+ }
2492
+ try {
2493
+ await runWithReconnect(connectOnce, {
2494
+ abortSignal: opts.abortSignal,
2495
+ jitterRatio: .2,
2496
+ onError: (err) => {
2497
+ runtime.error?.(`mattermost connection failed: ${String(err)}`);
2498
+ opts.statusSink?.({
2499
+ lastError: String(err),
2500
+ connected: false
2501
+ });
2502
+ },
2503
+ onReconnect: (delayMs) => {
2504
+ runtime.log?.(`mattermost reconnecting in ${Math.round(delayMs / 1e3)}s`);
2505
+ }
2506
+ });
2507
+ } finally {
2508
+ unregisterInteractions?.();
2509
+ }
2510
+ const slashShutdownCleanupPromise = slashShutdownCleanup;
2511
+ if (slashShutdownCleanupPromise) await Promise.resolve(slashShutdownCleanupPromise);
2512
+ }
2513
+ //#endregion
2514
+ //#region extensions/mattermost/src/mattermost/probe.ts
2515
+ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivateNetwork = false) {
2516
+ const normalized = normalizeMattermostBaseUrl(baseUrl);
2517
+ if (!normalized) return {
2518
+ ok: false,
2519
+ error: "baseUrl missing"
2520
+ };
2521
+ const url = `${normalized}/api/v4/users/me`;
2522
+ const start = Date.now();
2523
+ const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : 0;
2524
+ const controller = resolvedTimeoutMs > 0 ? new AbortController() : void 0;
2525
+ let timer = null;
2526
+ if (controller) timer = setTimeout(() => controller.abort(), resolvedTimeoutMs);
2527
+ try {
2528
+ const { response: res, release } = await fetchWithSsrFGuard({
2529
+ url,
2530
+ init: {
2531
+ headers: { Authorization: `Bearer ${botToken}` },
2532
+ signal: controller?.signal
2533
+ },
2534
+ auditContext: "mattermost-probe",
2535
+ policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork)
2536
+ });
2537
+ try {
2538
+ const elapsedMs = Date.now() - start;
2539
+ if (!res.ok) {
2540
+ const detail = await readMattermostError(res);
2541
+ return {
2542
+ ok: false,
2543
+ status: res.status,
2544
+ error: detail || res.statusText,
2545
+ elapsedMs
2546
+ };
2547
+ }
2548
+ const bot = await readProviderJsonResponse(res, "Mattermost probe /users/me");
2549
+ return {
2550
+ ok: true,
2551
+ status: res.status,
2552
+ elapsedMs,
2553
+ bot
2554
+ };
2555
+ } finally {
2556
+ await release();
2557
+ }
2558
+ } catch (err) {
2559
+ return {
2560
+ ok: false,
2561
+ status: null,
2562
+ error: formatErrorMessage(err),
2563
+ elapsedMs: Date.now() - start
2564
+ };
2565
+ } finally {
2566
+ if (timer) clearTimeout(timer);
2567
+ }
2568
+ }
2569
+ //#endregion
2570
+ //#region extensions/mattermost/src/mattermost/reactions.ts
2571
+ const BOT_USER_CACHE_TTL_MS = 6e5;
2572
+ const botUserIdCache = /* @__PURE__ */ new Map();
2573
+ async function resolveBotUserId(client, cacheKey) {
2574
+ const rawNow = Date.now();
2575
+ const now = asDateTimestampMs(rawNow);
2576
+ const cached = botUserIdCache.get(cacheKey);
2577
+ if (cached) {
2578
+ if (now !== void 0 && cached.expiresAt > now) return cached.userId;
2579
+ botUserIdCache.delete(cacheKey);
2580
+ }
2581
+ const userId = (await fetchMattermostMe(client))?.id?.trim();
2582
+ if (!userId) return null;
2583
+ const expiresAt = resolveExpiresAtMsFromDurationMs(BOT_USER_CACHE_TTL_MS, { nowMs: rawNow });
2584
+ if (expiresAt !== void 0) botUserIdCache.set(cacheKey, {
2585
+ userId,
2586
+ expiresAt
2587
+ });
2588
+ return userId;
2589
+ }
2590
+ async function addMattermostReaction(params) {
2591
+ return runMattermostReaction(params, {
2592
+ action: "add",
2593
+ mutation: createReaction
2594
+ });
2595
+ }
2596
+ async function removeMattermostReaction(params) {
2597
+ return runMattermostReaction(params, {
2598
+ action: "remove",
2599
+ mutation: deleteReaction
2600
+ });
2601
+ }
2602
+ async function runMattermostReaction(params, options) {
2603
+ const resolved = resolveMattermostAccount({
2604
+ cfg: params.cfg,
2605
+ accountId: params.accountId
2606
+ });
2607
+ const baseUrl = resolved.baseUrl?.trim();
2608
+ const botToken = resolved.botToken?.trim();
2609
+ if (!baseUrl || !botToken) return {
2610
+ ok: false,
2611
+ error: "Mattermost botToken/baseUrl missing."
2612
+ };
2613
+ const client = createMattermostClient({
2614
+ baseUrl,
2615
+ botToken,
2616
+ fetchImpl: params.fetchImpl,
2617
+ allowPrivateNetwork: isPrivateNetworkOptInEnabled(resolved.config)
2618
+ });
2619
+ const userId = await resolveBotUserId(client, `${baseUrl}:${botToken}`);
2620
+ if (!userId) return {
2621
+ ok: false,
2622
+ error: "Mattermost reactions failed: could not resolve bot user id."
2623
+ };
2624
+ try {
2625
+ await options.mutation(client, {
2626
+ userId,
2627
+ postId: params.postId,
2628
+ emojiName: params.emojiName
2629
+ });
2630
+ } catch (err) {
2631
+ return {
2632
+ ok: false,
2633
+ error: `Mattermost ${options.action} reaction failed: ${String(err)}`
2634
+ };
2635
+ }
2636
+ return { ok: true };
2637
+ }
2638
+ async function createReaction(client, params) {
2639
+ await client.request("/reactions", {
2640
+ method: "POST",
2641
+ body: JSON.stringify({
2642
+ user_id: params.userId,
2643
+ post_id: params.postId,
2644
+ emoji_name: params.emojiName
2645
+ })
2646
+ });
2647
+ }
2648
+ async function deleteReaction(client, params) {
2649
+ const emoji = encodeURIComponent(params.emojiName);
2650
+ await client.request(`/users/${params.userId}/posts/${params.postId}/reactions/${emoji}`, { method: "DELETE" });
2651
+ }
2652
+ //#endregion
2653
+ export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };