@openclaw/mattermost 2026.8.1-beta.2 → 2026.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
1
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
2
- import { a as createMattermostPost, d as fetchMattermostUser, g as readMattermostError, l as fetchMattermostChannelPosts, m as normalizeMattermostBaseUrl, n as buildMattermostApiUrl, o as deleteMattermostPost, p as fetchMattermostUserTeams, r as createMattermostClient, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostMe, v as sendMattermostTyping, y as updateMattermostPost } from "./client-B_hd-kwM.js";
3
- import { S as resolveChannelMediaMaxBytes, T as warnMissingProviderGroupPolicyFallbackOnce, _ as logInboundDrop, b as registerPluginHttpRoute, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as resolveMattermostTrustedChatKind, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, w as resolveDefaultGroupPolicy, x as resolveAllowlistProviderRuntimeGroupPolicy$1 } from "./monitor-auth-CVd_4FPD.js";
4
- import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-Du_EJMeN.js";
5
- import { a as resolveMattermostReplyToMode, i as resolveMattermostAccount, n as listMattermostAccountIds, t as inspectMattermostAccount } from "./accounts-DspH-NMT.js";
6
- import { i as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-Dxt8Zv1j.js";
7
- import { _ as isSlashCommandsEnabled, a as sendMessageMattermost, b as resolveSlashCommandConfig, c as deliverMattermostReplyPayload, d as parseMattermostModelPickerContext, f as renderMattermostModelsPickerView, g as cleanupSlashCommands, h as DEFAULT_COMMAND_SPECS, l as joinMattermostVisibleContent, m as resolveMattermostModelPickerCurrentModel, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as renderMattermostProviderPickerView, r as getSlashCommandState, s as createMattermostReplyDeliveryBarrier, t as activateSlashCommands, u as buildMattermostAllowedModelRefs, v as registerSlashCommands, y as resolveCallbackUrl } from "./slash-state-DUowGLl4.js";
2
+ import { _ as sendMattermostTyping, a as createMattermostPost, d as fetchMattermostUser, g as readMattermostError, l as fetchMattermostChannelPosts, m as normalizeMattermostBaseUrl, n as buildMattermostApiUrl, o as deleteMattermostPost, p as fetchMattermostUserTeams, r as createMattermostClient, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostMe, v as updateMattermostPost } from "./client-DAIry9-2.js";
3
+ import { C as resolveDefaultGroupPolicy, _ as logTypingFailure, a as resolveMattermostMonitorInboundAccess, b as resolveAllowlistProviderRuntimeGroupPolicy$1, c as buildPreparedModelsProviderData, d as createChannelPairingController, g as logInboundDrop, l as createChannelHistoryWindow, m as listSkillCommandsForAgents, n as formatMattermostDirectMessageDropLog, o as resolveMattermostTrustedChatKind, s as DEFAULT_GROUP_HISTORY_LIMIT, t as authorizeMattermostCommandInvocation, u as createChannelMessageReplyPipeline, w as warnMissingProviderGroupPolicyFallbackOnce, x as resolveChannelMediaMaxBytes, y as registerPluginHttpRoute } from "./monitor-auth-CACk1Hos.js";
4
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-LnudXdqD.js";
5
+ import { n as normalizeMattermostAllowEntry } from "./ingress-identity-DNl4yQSc.js";
6
+ import { a as inspectMattermostAccount, c as resolveMattermostAccount, l as resolveMattermostReplyToMode, n as normalizeMattermostMessagingTarget, o as listMattermostAccountIds } from "./normalize-DoleH0bY.js";
7
+ import { _ as registerSlashCommands, a as sendMessageMattermost, c as joinMattermostVisibleContent, d as renderMattermostModelsPickerView, f as renderMattermostProviderPickerView, g as isSlashCommandsEnabled, h as cleanupSlashCommands, l as buildMattermostAllowedModelRefs, m as DEFAULT_COMMAND_SPECS, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as resolveMattermostModelPickerCurrentModel, r as getSlashCommandState, s as deliverMattermostReplyPayload, t as activateSlashCommands, u as parseMattermostModelPickerContext, v as resolveCallbackUrl, y as resolveSlashCommandConfig } from "./slash-state-CPIuJQj2.js";
8
8
  import { randomUUID } from "node:crypto";
9
- import { resolveGatewayPort } from "openclaw/plugin-sdk/core";
10
- import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
9
+ import { resolveGatewayPort } from "openclaw/plugin-sdk/gateway-config-runtime";
10
+ import { resolvePinnedMainDmOwnerFromAllowlist, sanitizeUntrustedFileName } from "openclaw/plugin-sdk/security-runtime";
11
11
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
12
12
  import { buildChannelInboundMediaPayload, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContext, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
13
13
  import { formatErrorMessage, toErrorObject } from "openclaw/plugin-sdk/error-runtime";
@@ -24,9 +24,9 @@ import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsS
24
24
  import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
25
25
  import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
26
26
  import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
27
+ import { escapeRegExp, runChannelProbe, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
27
28
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
28
29
  import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
29
- import { runChannelProbe, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
30
30
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
31
31
  import { channelReadyPatch, isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
32
32
  import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
@@ -50,17 +50,10 @@ function buildClient(params) {
50
50
  allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
51
51
  });
52
52
  }
53
- /**
54
- * Build clients from ALL enabled accounts (deduplicated by token).
55
- *
56
- * We always scan every account because:
57
- * - Private channels are only visible to bots that are members
58
- * - The requesting agent's account may have an expired/invalid token
59
- *
60
- * This means a single healthy bot token is enough for directory discovery.
61
- */
53
+ /** Build the requested account client, or aggregate accounts for an explicitly unscoped lookup. */
62
54
  function buildClients(params) {
63
- const accountIds = listMattermostAccountIds(params.cfg);
55
+ const requestedAccountId = params.accountId?.trim();
56
+ const accountIds = requestedAccountId ? [requestedAccountId] : listMattermostAccountIds(params.cfg);
64
57
  const seen = /* @__PURE__ */ new Set();
65
58
  const clients = [];
66
59
  for (const id of accountIds) {
@@ -182,22 +175,32 @@ function resolveThreadSessionKeys$1(params) {
182
175
  normalizeThreadId: (threadId) => threadId
183
176
  });
184
177
  }
178
+ function buildMattermostBotMentionPattern(username) {
179
+ return `(?<![a-z0-9_])@${escapeRegExp(username)}(?![a-z0-9_]|[.:-]+[a-z0-9_])`;
180
+ }
181
+ function matchesMattermostBotMention(text, botUsername) {
182
+ if (!botUsername) return false;
183
+ return new RegExp(buildMattermostBotMentionPattern(botUsername), "i").test(text);
184
+ }
185
185
  /**
186
186
  * Strip bot mention from message text while preserving newlines and
187
187
  * block-level Markdown formatting (headings, lists, blockquotes).
188
188
  */
189
189
  function normalizeMention(text, mention) {
190
190
  if (!mention) return text.trim();
191
- const escaped = mention.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
192
- const hasMentionRe = new RegExp(`@${escaped}\\b`, "i");
193
- const leadingMentionRe = new RegExp(`^([\\t ]*)@${escaped}\\b[\\t ]*`, "i");
194
- const trailingMentionRe = new RegExp(`[\\t ]*@${escaped}\\b[\\t ]*$`, "i");
191
+ const pattern = buildMattermostBotMentionPattern(mention);
192
+ const hasMentionRe = new RegExp(pattern, "i");
193
+ const leadingMentionRe = new RegExp(`^([\\t ]*)${pattern}[\\t ]*`, "i");
194
+ const trailingMentionRe = new RegExp(`[\\t ]*${pattern}[\\t ]*$`, "i");
195
195
  const normalizedLines = text.split("\n").map((line) => {
196
- const hadMention = hasMentionRe.test(line);
197
- const normalizedLine = line.replace(leadingMentionRe, "$1").replace(trailingMentionRe, "").replace(new RegExp(`@${escaped}\\b`, "gi"), "").replace(/(\S)[ \t]{2,}/g, "$1 ");
196
+ if (!hasMentionRe.test(line)) return {
197
+ text: line,
198
+ mentionOnlyBlank: false
199
+ };
200
+ const normalizedLine = line.replace(leadingMentionRe, "$1").replace(trailingMentionRe, "").replace(new RegExp(pattern, "gi"), "").replace(/(\S)[ \t]{2,}/g, "$1 ");
198
201
  return {
199
202
  text: normalizedLine,
200
- mentionOnlyBlank: hadMention && normalizedLine.trim() === ""
203
+ mentionOnlyBlank: normalizedLine.trim() === ""
201
204
  };
202
205
  });
203
206
  while (normalizedLines[0]?.mentionOnlyBlank) normalizedLines.shift();
@@ -214,6 +217,7 @@ function shouldDropEmptyMattermostBody(params) {
214
217
  //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
215
218
  const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
216
219
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
220
+ const MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS = 3e4;
217
221
  const MattermostEventPayloadSchema = z.object({
218
222
  event: z.string().optional(),
219
223
  status: z.string().optional(),
@@ -249,6 +253,14 @@ var WebSocketClosedBeforeOpenError = class extends Error {
249
253
  this.name = "WebSocketClosedBeforeOpenError";
250
254
  }
251
255
  };
256
+ var WebSocketClosedBeforeAuthenticationError = class extends Error {
257
+ constructor(code, reason) {
258
+ super(`websocket closed before authentication completed (code ${code}) — either the bot token was rejected or the connection dropped (server restart, proxy reset); check the Mattermost bot token if this repeats`);
259
+ this.code = code;
260
+ this.reason = reason;
261
+ this.name = "WebSocketClosedBeforeAuthenticationError";
262
+ }
263
+ };
252
264
  const defaultMattermostWebSocketFactory = (url, options) => {
253
265
  const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
254
266
  return new WebSocket(url, {
@@ -273,6 +285,7 @@ function createMattermostConnectOnce(opts) {
273
285
  try {
274
286
  return await new Promise((resolve, reject) => {
275
287
  let opened = false;
288
+ let authenticated = false;
276
289
  let settled = false;
277
290
  let healthCheckEnabled = getBotUpdateAt != null;
278
291
  let healthCheckInFlight = false;
@@ -282,11 +295,16 @@ function createMattermostConnectOnce(opts) {
282
295
  let protocolPongTimer;
283
296
  let initialUpdateAt;
284
297
  let authenticationSeq;
298
+ let authTimer;
285
299
  const clearTimers = () => {
286
300
  if (healthCheckTimer !== void 0) {
287
301
  clearTimeout(healthCheckTimer);
288
302
  healthCheckTimer = void 0;
289
303
  }
304
+ if (authTimer !== void 0) {
305
+ clearTimeout(authTimer);
306
+ authTimer = void 0;
307
+ }
290
308
  if (protocolPingTimer !== void 0) {
291
309
  clearTimeout(protocolPingTimer);
292
310
  protocolPingTimer = void 0;
@@ -401,6 +419,13 @@ function createMattermostConnectOnce(opts) {
401
419
  }
402
420
  });
403
421
  ws.send(authPayload);
422
+ authTimer = setTimeout(() => {
423
+ authTimer = void 0;
424
+ if (settled) return;
425
+ opts.runtime.error?.("mattermost websocket authentication timed out — reconnecting");
426
+ stopHealthChecks();
427
+ ws.terminate();
428
+ }, MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS);
404
429
  scheduleProtocolPing();
405
430
  if (getBotUpdateAt) runHealthCheck();
406
431
  });
@@ -412,18 +437,23 @@ function createMattermostConnectOnce(opts) {
412
437
  scheduleProtocolPing();
413
438
  });
414
439
  ws.on("message", async (data) => {
440
+ const raw = rawDataToString(data);
415
441
  captureWsEvent({
416
442
  url: opts.wsUrl,
417
443
  direction: "inbound",
418
444
  kind: "ws-frame",
419
445
  flowId,
420
- payload: Buffer.from(rawDataToString(data)),
446
+ payload: Buffer.from(raw),
421
447
  meta: { subsystem: "mattermost-websocket" }
422
448
  });
423
- const raw = rawDataToString(data);
424
449
  const payload = parseMattermostEventPayload(raw);
425
450
  if (!payload) return;
426
451
  if (payload.status === "OK" && payload.seq_reply === authenticationSeq) {
452
+ authenticated = true;
453
+ if (authTimer !== void 0) {
454
+ clearTimeout(authTimer);
455
+ authTimer = void 0;
456
+ }
427
457
  opts.statusSink?.(channelReadyPatch());
428
458
  return;
429
459
  }
@@ -465,10 +495,14 @@ function createMattermostConnectOnce(opts) {
465
495
  error: message || void 0
466
496
  }
467
497
  });
468
- if (opened) {
498
+ if (opened && authenticated) {
469
499
  resolveOnce();
470
500
  return;
471
501
  }
502
+ if (opened) {
503
+ rejectOnce(new WebSocketClosedBeforeAuthenticationError(code, message || void 0));
504
+ return;
505
+ }
472
506
  rejectOnce(new WebSocketClosedBeforeOpenError(code, message || void 0));
473
507
  });
474
508
  ws.on("error", (err) => {
@@ -531,6 +565,7 @@ function inspectMattermostIngressEvent(rawEvent) {
531
565
  const data = isRecord(envelope.data) ? envelope.data : null;
532
566
  const post = parseRawPost(data?.post);
533
567
  const eventId = requiredString(post.id, "post.id");
568
+ requiredString(post.user_id, "post.user_id");
534
569
  const broadcast = isRecord(envelope.broadcast) ? envelope.broadcast : null;
535
570
  return {
536
571
  eventId,
@@ -542,9 +577,13 @@ function parseClaimedEvent(rawEvent, eventId) {
542
577
  if (!payload || payload.event !== "posted") throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} is not a posted event.`);
543
578
  const post = parseMattermostPost(payload.data?.post);
544
579
  const claimedChannelId = post?.channel_id?.trim() || payload.data?.channel_id?.trim() || payload.broadcast?.channel_id?.trim();
545
- if (!post || post.id !== eventId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} has invalid post identity.`);
580
+ const senderId = post?.user_id?.trim();
581
+ if (!post || post.id !== eventId || !senderId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} has invalid post identity.`);
546
582
  return {
547
- post,
583
+ post: {
584
+ ...post,
585
+ user_id: senderId
586
+ },
548
587
  payload
549
588
  };
550
589
  }
@@ -601,7 +640,14 @@ function createMattermostIngressMonitor(options) {
601
640
  });
602
641
  monitor.start();
603
642
  return {
604
- receive: (rawEvent) => monitor.admit(rawEvent).then(() => void 0),
643
+ receive: async (rawEvent) => {
644
+ try {
645
+ await monitor.admit(rawEvent);
646
+ } catch (error) {
647
+ if (!(error instanceof MattermostIngressPermanentError) || error.reason !== "invalid-event") throw error;
648
+ options.runtime.error?.(`mattermost ingress rejected invalid event: ${error.message}`);
649
+ }
650
+ },
605
651
  stop: monitor.stop,
606
652
  waitForIdle: monitor.waitForIdle
607
653
  };
@@ -774,6 +820,8 @@ async function buildMattermostEventPlan(monitor, params) {
774
820
  ParentSessionKey: thread.parentSessionKey,
775
821
  AccountId: route.accountId,
776
822
  ChatType: kind,
823
+ ConversationRouteContextObserved: true,
824
+ ConversationRoutePeerId: kind === "direct" ? params.senderId : params.channelId,
777
825
  GroupChannel: channelName ? `#${channelName}` : void 0,
778
826
  GroupSpace: teamId,
779
827
  SenderId: params.senderId,
@@ -781,36 +829,31 @@ async function buildMattermostEventPlan(monitor, params) {
781
829
  Surface: "mattermost",
782
830
  ReplyToId: thread.effectiveReplyToId,
783
831
  MessageThreadId: thread.effectiveReplyToId,
832
+ NativeChannelId: params.channelId,
833
+ InboundAccessAuthorized: true,
784
834
  OriginatingChannel: "mattermost",
785
835
  OriginatingTo: to
786
836
  }),
787
- createReplyPlan: () => {
788
- const deliveryBarrier = createMattermostReplyDeliveryBarrier({
789
- isDirect: kind === "direct",
790
- dmRetryOptions: monitor.account.config.dmChannelRetry
791
- });
792
- return {
793
- textLimit: monitor.core.channel.text.resolveTextChunkLimit(monitor.cfg, "mattermost", monitor.account.accountId, { fallbackLimit: monitor.account.textChunkLimit ?? 4e3 }),
794
- tableMode: monitor.core.channel.text.resolveMarkdownTableMode({
795
- cfg: monitor.cfg,
796
- channel: "mattermost",
797
- accountId: monitor.account.accountId
798
- }),
799
- deliveryBarrier,
800
- replyPipeline: { typing: {
801
- start: () => monitor.resources.sendTypingIndicator(params.channelId, thread.effectiveReplyToId),
802
- onStartError: (error) => {
803
- logTypingFailure({
804
- log: monitor.logDebugMessage,
805
- channel: "mattermost",
806
- target: params.channelId,
807
- error
808
- });
809
- }
810
- } },
811
- replyOptions: { disableBlockStreaming: typeof monitor.account.blockStreaming === "boolean" ? !monitor.account.blockStreaming : void 0 }
812
- };
813
- }
837
+ createReplyPlan: () => ({
838
+ textLimit: monitor.core.channel.text.resolveTextChunkLimit(monitor.cfg, "mattermost", monitor.account.accountId, { fallbackLimit: monitor.account.textChunkLimit ?? 4e3 }),
839
+ tableMode: monitor.core.channel.text.resolveMarkdownTableMode({
840
+ cfg: monitor.cfg,
841
+ channel: "mattermost",
842
+ accountId: monitor.account.accountId
843
+ }),
844
+ replyPipeline: { typing: {
845
+ start: () => monitor.resources.sendTypingIndicator(params.channelId, thread.effectiveReplyToId),
846
+ onStartError: (error) => {
847
+ logTypingFailure({
848
+ log: monitor.logDebugMessage,
849
+ channel: "mattermost",
850
+ target: params.channelId,
851
+ error
852
+ });
853
+ }
854
+ } },
855
+ replyOptions: { disableBlockStreaming: typeof monitor.account.blockStreaming === "boolean" ? !monitor.account.blockStreaming : void 0 }
856
+ })
814
857
  };
815
858
  }
816
859
  //#endregion
@@ -885,7 +928,7 @@ function registerMattermostInteractions(params) {
885
928
  dropLabel: "interaction dispatch"
886
929
  });
887
930
  if (!eventPlan) return;
888
- const { channelDisplay, kind, route, thread, to } = eventPlan;
931
+ const { channelDisplay, channelId, kind, route, thread, to } = eventPlan;
889
932
  const bodyText = `[Button click: user @${button.userName} selected "${button.actionName}"]`;
890
933
  const ctxPayload = eventPlan.finalizeContext({
891
934
  Body: bodyText,
@@ -899,7 +942,7 @@ function registerMattermostInteractions(params) {
899
942
  WasMentioned: true,
900
943
  CommandAuthorized: false
901
944
  });
902
- const { deliveryBarrier, replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
945
+ const { replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
903
946
  await core.channel.inbound.dispatch({
904
947
  cfg,
905
948
  channel: "mattermost",
@@ -917,7 +960,7 @@ function registerMattermostInteractions(params) {
917
960
  core,
918
961
  cfg,
919
962
  payload,
920
- to,
963
+ channelId,
921
964
  accountId: account.accountId,
922
965
  agentId: route.agentId,
923
966
  replyToId: resolveMattermostInteractionReplyRootId({
@@ -929,8 +972,7 @@ function registerMattermostInteractions(params) {
929
972
  }),
930
973
  textLimit,
931
974
  tableMode,
932
- sendMessage: sendMessageMattermost,
933
- onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
975
+ sendMessage: sendMessageMattermost
934
976
  });
935
977
  if (result.visibleReplySent) runtime.log?.(`delivered button-click reply to ${to}`);
936
978
  return result;
@@ -940,11 +982,7 @@ function registerMattermostInteractions(params) {
940
982
  }
941
983
  },
942
984
  replyPipeline,
943
- dispatcherOptions: {
944
- resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
945
- onDeliverySettled: deliveryBarrier.markDeliverySettled,
946
- humanDelay: resolveHumanDelayConfig(cfg, route.agentId)
947
- },
985
+ dispatcherOptions: { humanDelay: resolveHumanDelayConfig(cfg, route.agentId) },
948
986
  replyOptions
949
987
  });
950
988
  },
@@ -954,7 +992,6 @@ function registerMattermostInteractions(params) {
954
992
  source: "mattermost-interactions",
955
993
  accountId: account.accountId,
956
994
  log: (message) => runtime.log?.(message),
957
- replaceExisting: true,
958
995
  throwOnFailure: true
959
996
  });
960
997
  }
@@ -964,7 +1001,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
964
1001
  const { account, cfg, core, pairing, resources, runtime } = monitor;
965
1002
  const { resolveChannelInfo, updateModelPickerPost } = resources;
966
1003
  const runModelPickerCommand = async (params) => {
967
- const { channelDisplay, kind, roomLabel, route, thread, to } = params.eventPlan;
1004
+ const { channelDisplay, channelId, kind, roomLabel, route, thread } = params.eventPlan;
968
1005
  const fromLabel = kind === "direct" ? `Mattermost DM from ${params.senderName}` : `Mattermost message in ${roomLabel} from ${params.senderName}`;
969
1006
  const ctxPayload = params.eventPlan.finalizeContext({
970
1007
  Body: params.commandText,
@@ -980,7 +1017,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
980
1017
  CommandAuthorized: params.commandAuthorized,
981
1018
  CommandSource: "native"
982
1019
  });
983
- const { deliveryBarrier, replyOptions, replyPipeline, tableMode, textLimit } = params.eventPlan.createReplyPlan();
1020
+ const { replyOptions, replyPipeline, tableMode, textLimit } = params.eventPlan.createReplyPlan();
984
1021
  await core.channel.inbound.dispatch({
985
1022
  cfg,
986
1023
  channel: "mattermost",
@@ -1002,7 +1039,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1002
1039
  core,
1003
1040
  cfg,
1004
1041
  payload: trimmedPayload,
1005
- to,
1042
+ channelId,
1006
1043
  accountId: account.accountId,
1007
1044
  agentId: route.agentId,
1008
1045
  replyToId: resolveMattermostInteractionReplyRootId({
@@ -1014,8 +1051,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1014
1051
  }),
1015
1052
  textLimit,
1016
1053
  tableMode: "off",
1017
- sendMessage: sendMessageMattermost,
1018
- onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1054
+ sendMessage: sendMessageMattermost
1019
1055
  });
1020
1056
  },
1021
1057
  onError: (err, info) => {
@@ -1023,10 +1059,6 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1023
1059
  }
1024
1060
  },
1025
1061
  replyPipeline,
1026
- dispatcherOptions: {
1027
- resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1028
- onDeliverySettled: deliveryBarrier.markDeliverySettled
1029
- },
1030
1062
  replyOptions
1031
1063
  });
1032
1064
  };
@@ -1088,7 +1120,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1088
1120
  agentId: eventPlan.route.agentId,
1089
1121
  sessionKey: eventPlan.thread.sessionKey
1090
1122
  };
1091
- const data = await buildModelsProviderData(cfg, eventPlan.route.agentId);
1123
+ const data = await buildPreparedModelsProviderData(cfg, eventPlan.route.agentId);
1092
1124
  if (data.providers.length === 0) return await updatePickerPost("No models available.");
1093
1125
  if (pickerState.action === "providers" || pickerState.action === "back") {
1094
1126
  const currentModel = resolveMattermostModelPickerCurrentModel({
@@ -1215,9 +1247,11 @@ function formatMattermostInboundMediaText(params) {
1215
1247
  const materializedCount = params.materializedMedia.filter((media) => Boolean(media.path) || Boolean(media.url)).length;
1216
1248
  const unavailableCount = Math.max(0, params.nativeMedia.length - materializedCount);
1217
1249
  if (unavailableCount === 0) return params.body;
1250
+ const unavailableFileNames = params.materializedMedia.filter((media) => !media.path && !media.url && media.fileName).map((media) => sanitizeUntrustedFileName(media.fileName ?? "", "")).filter(Boolean).join(", ");
1251
+ const fileNameNotice = unavailableFileNames ? ` ${JSON.stringify(truncateUtf16Safe(unavailableFileNames, 512))}` : "";
1218
1252
  return formatInboundMediaUnavailableText({
1219
1253
  body: params.body,
1220
- notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]`
1254
+ notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]${fileNameNotice}`
1221
1255
  });
1222
1256
  }
1223
1257
  const CHANNEL_CACHE_TTL_MS = 5 * 6e4;
@@ -1273,18 +1307,22 @@ function createMattermostMonitorResources(params) {
1273
1307
  out.push({
1274
1308
  path: saved.path,
1275
1309
  contentType,
1310
+ ...saved.fileName ? { fileName: saved.fileName } : {},
1276
1311
  kind: mediaKindFromMime(contentType) ?? "unknown"
1277
1312
  });
1278
1313
  } catch (err) {
1279
1314
  logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
1280
- let contentType;
1315
+ let info;
1281
1316
  try {
1282
- contentType = (await client.request(`/files/${fileId}/info`)).mime_type?.trim() || void 0;
1317
+ info = await client.request(`/files/${fileId}/info`);
1283
1318
  } catch (infoErr) {
1284
1319
  logger.debug?.(`mattermost: failed to resolve metadata for file ${fileId}: ${String(infoErr)}`);
1285
1320
  }
1321
+ const contentType = info?.mime_type?.trim() || void 0;
1322
+ const fileName = info?.name?.trim();
1286
1323
  out.push({
1287
1324
  contentType,
1325
+ ...fileName ? { fileName } : {},
1288
1326
  kind: mediaKindFromMime(contentType) ?? "unknown"
1289
1327
  });
1290
1328
  }
@@ -1710,9 +1748,9 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1710
1748
  confirmedPreviewDelivery = previewFinalResolution?.confirmedDelivery;
1711
1749
  previewFinalDeliveryText = previewFinalResolution?.deliveryText;
1712
1750
  previewFinalTextAlreadyDelivered = previewFinalResolution?.alreadyDelivered === true && payload.isError !== true;
1713
- useConfirmedPreviewAsWholeFinal = previewFinalTextAlreadyDelivered && !resolveSendableOutboundReplyParts(payload).hasMedia;
1751
+ useConfirmedPreviewAsWholeFinal = previewFinalTextAlreadyDelivered && !resolveSendableOutboundReplyParts(payload).hasMedia && !payload.presentation;
1714
1752
  const previewFinalText = previewFinalResolution?.editText;
1715
- if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || !canFinalizeMattermostPreviewInPlace({
1753
+ if (hasMedia && !ttsSupplement || typeof previewFinalText !== "string" || payload.isError || payload.presentation || !canFinalizeMattermostPreviewInPlace({
1716
1754
  kind: params.kind,
1717
1755
  previewRootId: params.effectiveReplyToId,
1718
1756
  threadRootId: params.effectiveReplyToId,
@@ -1858,7 +1896,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1858
1896
  const { channelHistories, ctxPayload, eventPlan, historyKey, historyLimit, pinnedMainDmOwner, post, rawText, turnAdoptionLifecycle } = params;
1859
1897
  const { channelId, kind, route, senderId, thread, to } = eventPlan;
1860
1898
  const { effectiveReplyToId } = thread;
1861
- const { deliveryBarrier, replyOptions, replyPipeline: baseReplyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
1899
+ const { replyOptions, replyPipeline: baseReplyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
1862
1900
  const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
1863
1901
  const { onModelSelected, typingCallbacks, resolveResponsePrefix, ...dispatcherPipeline } = createChannelMessageReplyPipeline({
1864
1902
  cfg,
@@ -1980,8 +2018,6 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1980
2018
  };
1981
2019
  const dispatcherOptions = {
1982
2020
  ...dispatcherPipeline,
1983
- resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1984
- onDeliverySettled: deliveryBarrier.markDeliverySettled,
1985
2021
  humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
1986
2022
  typingCallbacks
1987
2023
  };
@@ -2021,7 +2057,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2021
2057
  core,
2022
2058
  cfg,
2023
2059
  payload: resolvedPayload,
2024
- to,
2060
+ channelId,
2025
2061
  accountId: account.accountId,
2026
2062
  agentId: route.agentId,
2027
2063
  replyToId: resolveMattermostReplyRootId({
@@ -2031,8 +2067,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2031
2067
  }),
2032
2068
  textLimit,
2033
2069
  tableMode,
2034
- sendMessage: sendMessageMattermost,
2035
- onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2070
+ sendMessage: sendMessageMattermost
2036
2071
  }).catch((error) => {
2037
2072
  if (isChannelPartialDeliveryError(error)) markThreadParticipation();
2038
2073
  throw error;
@@ -2205,7 +2240,7 @@ function createMattermostPostHandler(monitor) {
2205
2240
  const { account, botUserId, botUsername, cfg, core, groupPolicy, pairing, resources } = monitor;
2206
2241
  const { resolveMattermostMedia, resolveUserInfo } = resources;
2207
2242
  const channelHistories = /* @__PURE__ */ new Map();
2208
- const historyLimit = Math.max(0, cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
2243
+ const historyLimit = Math.max(0, account.config.historyLimit ?? cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
2209
2244
  return async (post, payload, turnAdoptionLifecycle, messageIds) => {
2210
2245
  const channelId = post.channel_id ?? payload.data?.channel_id ?? payload.broadcast?.channel_id;
2211
2246
  if (!channelId) {
@@ -2217,11 +2252,7 @@ function createMattermostPostHandler(monitor) {
2217
2252
  return;
2218
2253
  }
2219
2254
  const allMessageIds = messageIds?.length ? messageIds : [post.id];
2220
- const senderId = post.user_id ?? payload.broadcast?.user_id;
2221
- if (!senderId) {
2222
- monitor.logVerboseMessage("mattermost: drop post (missing sender id)");
2223
- return;
2224
- }
2255
+ const senderId = post.user_id;
2225
2256
  if (senderId === botUserId) {
2226
2257
  monitor.logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
2227
2258
  return;
@@ -2308,7 +2339,7 @@ function createMattermostPostHandler(monitor) {
2308
2339
  });
2309
2340
  monitor.logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
2310
2341
  if (created) try {
2311
- await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
2342
+ await sendMessageMattermost(`channel:${channelId}`, core.channel.pairing.buildPairingReply({
2312
2343
  channel: "mattermost",
2313
2344
  idLine: `Your Mattermost user id: ${senderId}`,
2314
2345
  code
@@ -2363,7 +2394,7 @@ function createMattermostPostHandler(monitor) {
2363
2394
  return;
2364
2395
  }
2365
2396
  const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
2366
- const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
2397
+ const wasMentioned = kind !== "direct" && (matchesMattermostBotMention(rawText, botUsername) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
2367
2398
  const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
2368
2399
  const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
2369
2400
  const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
@@ -2837,7 +2868,7 @@ async function monitorMattermostProvider(opts = {}) {
2837
2868
  };
2838
2869
  const mediaMaxBytes = resolveChannelMediaMaxBytes({
2839
2870
  cfg,
2840
- resolveChannelLimitMb: () => void 0,
2871
+ resolveChannelLimitMb: () => account.config.mediaMaxMb,
2841
2872
  accountId: account.accountId
2842
2873
  }) ?? 8 * 1024 * 1024;
2843
2874
  const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy$1({
@@ -2903,12 +2934,12 @@ async function monitorMattermostProvider(opts = {}) {
2903
2934
  }),
2904
2935
  buildKey: (entry) => {
2905
2936
  const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2906
- if (!channelId) return null;
2937
+ if (!channelId || !entry.post.user_id) return null;
2907
2938
  const threadId = normalizeOptionalString(entry.post.root_id);
2908
- return `mattermost:${account.accountId}:${channelId}:${threadId ? `thread:${threadId}` : "channel"}`;
2939
+ return `mattermost:${account.accountId}:${channelId}:${threadId ? `thread:${threadId}` : "channel"}:${entry.post.user_id}`;
2909
2940
  },
2910
2941
  shouldDebounce: (entry) => {
2911
- if (entry.post.file_ids?.length) return false;
2942
+ if (normalizeOptionalString(entry.post.type) !== void 0 || entry.post.file_ids?.length) return false;
2912
2943
  const text = normalizeOptionalString(entry.post.message) ?? "";
2913
2944
  return Boolean(text) && !core.channel.commands.isControlCommandMessage(text, cfg);
2914
2945
  },
@@ -197,19 +197,6 @@ async function createMattermostDirectChannel(client, userIds, signal, timeoutMs)
197
197
  timeoutMs
198
198
  });
199
199
  }
200
- const DM_REPLY_DELIVERY_BARRIER_SLACK_MS = 6e4;
201
- /** Covers DM creation retries without extending channel-delivery stalls. */
202
- function resolveMattermostReplyDeliveryBarrierTimeoutMs(params) {
203
- if (!params.isDirect) return;
204
- const deliveryCount = Object.values(params.queuedCounts).reduce((sum, count) => sum + count, 0);
205
- if (deliveryCount === 0) return;
206
- const maxRetries = params.dmRetryOptions?.maxRetries ?? 3;
207
- const maxDelayMs = params.dmRetryOptions?.maxDelayMs ?? 1e4;
208
- const timeoutMs = params.dmRetryOptions?.timeoutMs ?? 3e4;
209
- const perDeliveryTimeoutMs = (maxRetries + 1) * timeoutMs + maxRetries * maxDelayMs + DM_REPLY_DELIVERY_BARRIER_SLACK_MS;
210
- const totalTimeoutMs = perDeliveryTimeoutMs * deliveryCount + Math.max(0, params.humanDelayBudgetMs ?? 0);
211
- return resolveTimerTimeoutMs(Number.isFinite(totalTimeoutMs) ? totalTimeoutMs : Number.MAX_SAFE_INTEGER, perDeliveryTimeoutMs);
212
- }
213
200
  const RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
214
201
  "ECONNRESET",
215
202
  "ECONNREFUSED",
@@ -382,4 +369,4 @@ async function uploadMattermostFile(client, params) {
382
369
  return info;
383
370
  }
384
371
  //#endregion
385
- export { resolveMattermostReplyDeliveryBarrierTimeoutMs as _, createMattermostPost as a, uploadMattermostFile as b, fetchMattermostChannelByName as c, fetchMattermostUser as d, fetchMattermostUserByUsername as f, readMattermostError as g, parseMattermostApiStatus as h, createMattermostDirectChannelWithRetry as i, fetchMattermostChannelPosts as l, normalizeMattermostBaseUrl as m, buildMattermostApiUrl as n, deleteMattermostPost as o, fetchMattermostUserTeams as p, createMattermostClient as r, fetchMattermostChannel as s, MattermostPostSchema as t, fetchMattermostMe as u, sendMattermostTyping as v, updateMattermostPost as y };
372
+ export { sendMattermostTyping as _, createMattermostPost as a, fetchMattermostChannelByName as c, fetchMattermostUser as d, fetchMattermostUserByUsername as f, readMattermostError as g, parseMattermostApiStatus as h, createMattermostDirectChannelWithRetry as i, fetchMattermostChannelPosts as l, normalizeMattermostBaseUrl as m, buildMattermostApiUrl as n, deleteMattermostPost as o, fetchMattermostUserTeams as p, createMattermostClient as r, fetchMattermostChannel as s, MattermostPostSchema as t, fetchMattermostMe as u, updateMattermostPost as v, uploadMattermostFile as y };
@@ -0,0 +1,27 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
2
+ import { parseAccessGroupAllowFromEntry } from "openclaw/plugin-sdk/access-groups";
3
+ const mattermostIngressIdentity = {
4
+ key: "sender-id",
5
+ authentication: "verified",
6
+ normalize: normalizeMattermostAllowEntry,
7
+ aliases: [{
8
+ key: "sender-name",
9
+ kind: "plugin:mattermost-user-name",
10
+ normalizeEntry: normalizeMattermostAllowEntry,
11
+ normalizeSubject: normalizeMattermostAllowEntry,
12
+ authentication: "mutable"
13
+ }],
14
+ isWildcardEntry: (entry) => normalizeMattermostAllowEntry(entry) === "*",
15
+ resolveEntryId: ({ entryIndex, fieldKey }) => `mattermost-entry-${entryIndex + 1}:${fieldKey === "sender-name" ? "name" : "user"}`
16
+ };
17
+ function normalizeMattermostAllowEntry(entry) {
18
+ const trimmed = entry.trim();
19
+ if (!trimmed) return "";
20
+ if (trimmed === "*") return "*";
21
+ const accessGroupName = parseAccessGroupAllowFromEntry(trimmed);
22
+ if (accessGroupName) return `accessGroup:${accessGroupName}`;
23
+ const normalized = trimmed.replace(/^(mattermost|user):/i, "").replace(/^@/, "").trim();
24
+ return normalized ? normalizeLowercaseStringOrEmpty(normalized) : "";
25
+ }
26
+ //#endregion
27
+ export { normalizeMattermostAllowEntry as n, mattermostIngressIdentity as t };
@@ -1,8 +1,8 @@
1
1
  import { t as getMattermostRuntime } from "./runtime-CNB4YGqJ.js";
2
- import { y as updateMattermostPost } from "./client-B_hd-kwM.js";
3
- import { C as resolveClientIp, m as isTrustedProxyAddress, y as readRequestBodyWithLimit } from "./monitor-auth-CVd_4FPD.js";
2
+ import { v as updateMattermostPost } from "./client-DAIry9-2.js";
3
+ import { S as resolveClientIp, p as isTrustedProxyAddress, v as readRequestBodyWithLimit } from "./monitor-auth-CACk1Hos.js";
4
4
  import { createHmac } from "node:crypto";
5
- import { resolveGatewayPort } from "openclaw/plugin-sdk/core";
5
+ import { resolveGatewayPort } from "openclaw/plugin-sdk/gateway-config-runtime";
6
6
  import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
7
7
  import { normalizeOptionalString, normalizeStringifiedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
8
8
  //#region extensions/mattermost/src/mattermost/interactions.ts