@openclaw/mattermost 2026.10.10 → 2026.11.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/.setup/channel-plugin-api-C5kL5jd0.mjs +1 -0
  2. package/dist/.setup/{channel-plugin-runtime-CLBgUA35.mjs → channel-plugin-api-CC8EU4bs.mjs} +147 -130
  3. package/dist/.setup/{channel.runtime-BBMzxlPB.mjs → channel.runtime-ukouI9k4.mjs} +37 -37
  4. package/dist/.setup/{client-VHp4VYIf.mjs → client-CVipK0N2.mjs} +11 -84
  5. package/dist/.setup/{interactions-7eWssSf1.mjs → interactions-cgV9-piH.mjs} +23 -36
  6. package/dist/.setup/{monitor-agLGA4lV.mjs → monitor-Bn-I4iu7.mjs} +292 -398
  7. package/dist/.setup/{monitor-auth-0gZXtoHv.mjs → monitor-auth-D7Fl9CyF.mjs} +5 -11
  8. package/dist/.setup/{normalize-C_DYEHki.mjs → normalize-DuLSV4tT.mjs} +21 -7
  9. package/dist/.setup/secret-contract-BkDCURCE.mjs +19 -0
  10. package/dist/.setup/{secret-contract-api-CmBND3cW.mjs → secret-contract-api-DydsmAPQ.mjs} +1 -1
  11. package/dist/.setup/{send-3ye1gFt3.mjs → send-CoWXMKnY.mjs} +100 -198
  12. package/dist/.setup/{slash-state-V13EaHX9.mjs → slash-state-CwLVacYg.mjs} +361 -408
  13. package/dist/.source-module-urls/8fb0cb1067b83fd2cf3f3ba0f7a23e627c27e8e3adf1a4ea18753ddb884ff71e.json +1 -0
  14. package/dist/api.js +2 -2
  15. package/dist/channel-plugin-api.js +1 -1
  16. package/dist/policy-api.js +1 -1
  17. package/dist/secret-contract-api.js +1 -1
  18. package/dist/setup-entry.js +2 -2
  19. package/dist/slash-route-api.js +1 -1
  20. package/node_modules/zod/package.json +1 -1
  21. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  22. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  23. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  24. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  25. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  26. package/node_modules/zod/src/v4/core/util.ts +13 -0
  27. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  28. package/node_modules/zod/v4/core/compile.cjs +8 -0
  29. package/node_modules/zod/v4/core/compile.js +8 -0
  30. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  31. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  32. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  33. package/node_modules/zod/v4/core/schemas.js +30 -0
  34. package/node_modules/zod/v4/core/util.cjs +15 -0
  35. package/node_modules/zod/v4/core/util.d.cts +2 -0
  36. package/node_modules/zod/v4/core/util.d.ts +2 -0
  37. package/node_modules/zod/v4/core/util.js +14 -0
  38. package/node_modules/zod/v4/core/versions.cjs +1 -1
  39. package/node_modules/zod/v4/core/versions.js +1 -1
  40. package/openclaw.plugin.json +172 -0
  41. package/package.json +5 -5
  42. package/dist/.setup/channel-plugin-api-Vq9imWd1.mjs +0 -2
  43. package/dist/.setup/secret-contract-H9g0kHHQ.mjs +0 -11
  44. package/dist/.source-module-urls/9b327bbbce22c2cbef393c115f9a63999afd57e223aad992389710cb3f1e29cc.json +0 -1
  45. package/dist/channel-plugin-runtime.js +0 -1
@@ -1,41 +1,43 @@
1
- import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, l as gateway_config_runtime_exports, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-7eWssSf1.mjs";
1
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, l as gateway_config_runtime_exports, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-cgV9-piH.mjs";
2
2
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-y_L8jPMH.mjs";
3
- import { a as createMattermostPost, d as fetchMattermostUser, h as normalizeMattermostBaseUrl, l as fetchMattermostChannelPosts, m as isRetryableError, 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-VHp4VYIf.mjs";
4
- import { C as registerPluginHttpRoute, D as resolveDefaultGroupPolicy, T as resolveChannelMediaMaxBytes, b as logTypingFailure, c as shouldRetainMattermostSenderHistory, d as createChannelHistoryWindow, f as createChannelMessageReplyPipeline, h as isDangerousNameMatchingEnabled, k as warnMissingProviderGroupPolicyFallbackOnce, l as DEFAULT_GROUP_HISTORY_LIMIT, n as authorizeMattermostCommandInvocation, o as resolveMattermostMonitorInboundAccess, p as createChannelPairingController, r as formatMattermostDirectMessageDropLog, s as resolveMattermostTrustedChatKind, t as MATTERMOST_PAIRING_QUEUE_FULL_TEXT, u as buildPreparedModelsProviderData, w as resolveAllowlistProviderRuntimeGroupPolicy, x as prepareSkillCommandsForAgents, y as logInboundDrop } from "./monitor-auth-0gZXtoHv.mjs";
3
+ import { a as createMattermostPost, d as fetchMattermostUser, h as normalizeMattermostBaseUrl, l as fetchMattermostChannelPosts, m as isRetryableError, n as buildMattermostApiUrl, o as deleteMattermostPost, p as fetchMattermostUserTeams, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostMe, v as sendMattermostTyping, y as updateMattermostPost } from "./client-CVipK0N2.mjs";
4
+ import { C as registerPluginHttpRoute, D as resolveDefaultGroupPolicy, T as resolveChannelMediaMaxBytes, b as logTypingFailure, c as shouldRetainMattermostSenderHistory, d as createChannelHistoryWindow, f as createChannelMessageReplyPipeline, h as isDangerousNameMatchingEnabled, k as warnMissingProviderGroupPolicyFallbackOnce, l as DEFAULT_GROUP_HISTORY_LIMIT, n as authorizeMattermostCommandInvocation, o as resolveMattermostMonitorInboundAccess, p as createChannelPairingController, r as formatMattermostDirectMessageDropLog, s as resolveMattermostTrustedChatKind, t as MATTERMOST_PAIRING_QUEUE_FULL_TEXT, u as buildPreparedModelsProviderData, w as resolveAllowlistProviderRuntimeGroupPolicy, x as prepareSkillCommandsForAgents, y as logInboundDrop } from "./monitor-auth-D7Fl9CyF.mjs";
5
5
  import { n as normalizeMattermostAllowEntry } from "./ingress-identity-CtHiOUDu.mjs";
6
- import { d as resolveMattermostReplyToMode, r as parseMattermostQuestionContext, u as resolveMattermostAccount } from "./normalize-C_DYEHki.mjs";
7
- import { _ as resolveSlashCommandConfig, a as deliverMattermostReplyPayload, c as parseMattermostModelPickerContext, d as resolveMattermostModelPickerCurrentModel, f as DEFAULT_COMMAND_SPECS, g as resolveCallbackUrl, h as registerSlashCommands, l as renderMattermostModelsPickerView, m as isSlashCommandsEnabled, n as deactivateSlashCommands, o as joinMattermostVisibleContent, p as cleanupSlashCommands, r as getSlashCommandState, s as buildMattermostAllowedModelRefs, t as activateSlashCommands, u as renderMattermostProviderPickerView } from "./slash-state-V13EaHX9.mjs";
8
- import { t as sendMessageMattermost } from "./send-3ye1gFt3.mjs";
6
+ import { d as resolveMattermostAccount, f as resolveMattermostReplyToMode, o as createMattermostAccountClient, r as parseMattermostQuestionContext } from "./normalize-DuLSV4tT.mjs";
7
+ import { C as resolveSlashCommandConfig, S as resolveCallbackUrl, _ as resolveMattermostModelPickerCurrentModel, a as deliverMattermostReplyPayload, b as isSlashCommandsEnabled, c as canFinalizeMattermostPreviewInPlace, d as resolveMattermostReplyRootId, f as resolveMattermostThreadSessionContext, g as renderMattermostProviderPickerView, h as renderMattermostModelsPickerView, l as formatMattermostFinalDeliveryOutcomeLog, m as parseMattermostModelPickerContext, n as deactivateSlashCommands, o as joinMattermostVisibleContent, p as shouldUpdateMattermostDraftToolProgress, r as getSlashCommandState, s as buildMattermostButtonInteractionMessageSid, t as activateSlashCommands, u as resolveMattermostInteractionReplyRootId, v as DEFAULT_COMMAND_SPECS, x as registerSlashCommands, y as cleanupSlashCommands } from "./slash-state-CwLVacYg.mjs";
8
+ import { t as sendMessageMattermost } from "./send-CoWXMKnY.mjs";
9
9
  import { randomUUID } from "node:crypto";
10
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
- import { escapeRegExp, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
12
+ import { escapeRegExp, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
13
+ import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
13
14
  import { createAcceptedChannelDeliveryResult, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContextAsync, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
14
15
  import { formatErrorMessage, toErrorObject } from "openclaw/plugin-sdk/error-runtime";
15
- import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
16
16
  import { resolvePromptHistoryLimit } from "openclaw/plugin-sdk/number-runtime";
17
17
  import { z } from "zod";
18
- import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createLivePreviewLifecycle, createMessageReceiptFromOutboundResults, createPreviewMessageReceipt, listMessageReceiptPlatformIds, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
18
+ import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createLivePreviewLifecycle, createMessageReceiptFromOutboundResults, createPreviewMessageReceipt, listMessageReceiptPlatformIds } from "openclaw/plugin-sdk/channel-outbound";
19
19
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
20
- import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
21
20
  import { fanInChannelIngressLifecycles, resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
22
21
  import { resolveChannelGroups, resolveChannelGroupsConfigPath } from "openclaw/plugin-sdk/channel-policy";
23
- import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
22
+ import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
23
+ import { buildTtsSupplementMediaPayload, getReplyPayloadTtsSupplement, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
24
24
  import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
25
25
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
26
26
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
27
27
  import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
28
28
  import { getSessionEntryAsync, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
29
29
  import { recordDeliveredCommandExchange, scopeCommandTranscriptId } from "openclaw/plugin-sdk/session-transcript-runtime";
30
+ import { resolveInboundLastRouteSessionKey } from "openclaw/plugin-sdk/routing";
30
31
  import { channelReadyPatch, isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
31
32
  import { createRuntimeConfigReader } from "openclaw/plugin-sdk/runtime-config-snapshot";
32
33
  import { captureWsEventAsync, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
33
34
  import { WebSocket } from "openclaw/plugin-sdk/websocket-runtime";
34
35
  import { questionGatewayRuntime } from "openclaw/plugin-sdk/question-gateway-runtime";
35
- import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
36
+ import { mergePairLoopGuardConfig } from "openclaw/plugin-sdk/pair-loop-guard-runtime";
36
37
  import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
37
38
  import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime";
38
39
  import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
40
+ import { truncateWithMarker } from "openclaw/plugin-sdk/string-normalization-runtime";
39
41
  import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
40
42
  import { createPluginStateErrorReporter } from "openclaw/plugin-sdk/plugin-state-runtime";
41
43
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
@@ -82,6 +84,9 @@ function shouldDropEmptyMattermostBody(params) {
82
84
  const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16777216;
83
85
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
84
86
  const MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS = 3e4;
87
+ const MATTERMOST_WEBSOCKET_HEALTH_CHECK_INTERVAL_MS = 3e4;
88
+ const MATTERMOST_WEBSOCKET_PING_INTERVAL_MS = 3e4;
89
+ const MATTERMOST_WEBSOCKET_PONG_TIMEOUT_MS = 1e4;
85
90
  const MattermostEventPayloadSchema = z.object({
86
91
  event: z.string().optional(),
87
92
  status: z.string().optional(),
@@ -109,34 +114,7 @@ function parseMattermostPost(value) {
109
114
  if (typeof value === "string") return safeParseJsonWithSchema(MattermostPostSchema, value);
110
115
  return safeParseWithSchema(MattermostPostSchema, value);
111
116
  }
112
- var WebSocketClosedBeforeOpenError = class extends Error {
113
- constructor(code, reason) {
114
- super(`websocket closed before open (code ${code})`);
115
- this.code = code;
116
- this.reason = reason;
117
- this.name = "WebSocketClosedBeforeOpenError";
118
- }
119
- };
120
- var WebSocketClosedBeforeAuthenticationError = class extends Error {
121
- constructor(code, reason) {
122
- 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`);
123
- this.code = code;
124
- this.reason = reason;
125
- this.name = "WebSocketClosedBeforeAuthenticationError";
126
- }
127
- };
128
- const defaultMattermostWebSocketFactory = (url, options) => {
129
- const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
130
- return new WebSocket(url, {
131
- ...options,
132
- ...agent ? { agent } : {}
133
- });
134
- };
135
117
  function createMattermostConnectOnce(opts) {
136
- const webSocketFactory = opts.webSocketFactory ?? defaultMattermostWebSocketFactory;
137
- const healthCheckIntervalMs = opts.healthCheckIntervalMs ?? 3e4;
138
- const pingIntervalMs = opts.pingIntervalMs ?? 3e4;
139
- const pongTimeoutMs = opts.pongTimeoutMs ?? 1e4;
140
118
  return async () => {
141
119
  const flowId = randomUUID();
142
120
  const captureEvent = (event) => {
@@ -150,13 +128,14 @@ function createMattermostConnectOnce(opts) {
150
128
  }
151
129
  }).catch(() => {});
152
130
  };
153
- const ws = webSocketFactory(opts.wsUrl, {
131
+ const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
132
+ const ws = new WebSocket(opts.wsUrl, {
154
133
  maxPayload: MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES,
155
- handshakeTimeout: MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS
134
+ handshakeTimeout: MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS,
135
+ ...agent ? { agent } : {}
156
136
  });
157
137
  const onAbort = () => ws.terminate();
158
138
  opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
159
- const getBotUpdateAt = opts.getBotUpdateAt;
160
139
  try {
161
140
  return await new Promise((resolve, reject) => {
162
141
  let opened = false;
@@ -183,7 +162,7 @@ function createMattermostConnectOnce(opts) {
183
162
  opts.runtime.error?.("mattermost websocket pong timeout — reconnecting");
184
163
  stopHealthChecks();
185
164
  ws.terminate();
186
- }, pongTimeoutMs);
165
+ }, MATTERMOST_WEBSOCKET_PONG_TIMEOUT_MS);
187
166
  try {
188
167
  ws.ping();
189
168
  } catch (err) {
@@ -197,19 +176,19 @@ function createMattermostConnectOnce(opts) {
197
176
  protocolPingTimer = setTimeout(() => {
198
177
  protocolPingTimer = void 0;
199
178
  sendProtocolPing();
200
- }, pingIntervalMs);
179
+ }, MATTERMOST_WEBSOCKET_PING_INTERVAL_MS);
201
180
  };
202
181
  const scheduleHealthCheck = () => {
203
- if (!getBotUpdateAt || stopped) return;
182
+ if (stopped) return;
204
183
  healthCheckTimer = setTimeout(() => {
205
184
  healthCheckTimer = void 0;
206
185
  runHealthCheck();
207
- }, healthCheckIntervalMs);
186
+ }, MATTERMOST_WEBSOCKET_HEALTH_CHECK_INTERVAL_MS);
208
187
  };
209
188
  const runHealthCheck = async () => {
210
- if (!getBotUpdateAt || stopped) return;
189
+ if (stopped) return;
211
190
  try {
212
- const current = await getBotUpdateAt();
191
+ const current = await opts.getBotUpdateAt();
213
192
  if (stopped) return;
214
193
  if (initialUpdateAt === void 0) {
215
194
  initialUpdateAt = current;
@@ -258,14 +237,14 @@ function createMattermostConnectOnce(opts) {
258
237
  ws.terminate();
259
238
  }, MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS);
260
239
  scheduleProtocolPing();
261
- if (getBotUpdateAt) runHealthCheck();
240
+ runHealthCheck();
262
241
  });
263
242
  ws.on("pong", () => {
264
243
  clearTimeout(protocolPongTimer);
265
244
  protocolPongTimer = void 0;
266
245
  scheduleProtocolPing();
267
246
  });
268
- ws.on("message", async (data) => {
247
+ const onMessage = async (data) => {
269
248
  const raw = rawDataToString(data);
270
249
  captureEvent({
271
250
  direction: "inbound",
@@ -282,7 +261,6 @@ function createMattermostConnectOnce(opts) {
282
261
  return;
283
262
  }
284
263
  if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
285
- if (!opts.onReaction) return;
286
264
  try {
287
265
  await opts.onReaction(payload);
288
266
  } catch (err) {
@@ -297,6 +275,9 @@ function createMattermostConnectOnce(opts) {
297
275
  opts.runtime.error?.(`mattermost durable admission failed; terminating websocket: ${String(err)}`);
298
276
  ws.terminate();
299
277
  }
278
+ };
279
+ ws.on("message", (data) => {
280
+ onMessage(data);
300
281
  });
301
282
  ws.on("close", (code, reason) => {
302
283
  captureEvent({
@@ -320,11 +301,12 @@ function createMattermostConnectOnce(opts) {
320
301
  resolve();
321
302
  return;
322
303
  }
323
- if (opened) {
324
- reject(new WebSocketClosedBeforeAuthenticationError(code, message || void 0));
325
- return;
326
- }
327
- reject(new WebSocketClosedBeforeOpenError(code, message || void 0));
304
+ const error = /* @__PURE__ */ new Error(opened ? `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` : `websocket closed before open (code ${code})`);
305
+ reject(Object.assign(error, {
306
+ code,
307
+ reason: message || void 0,
308
+ name: opened ? "WebSocketClosedBeforeAuthenticationError" : "WebSocketClosedBeforeOpenError"
309
+ }));
328
310
  });
329
311
  ws.on("error", (err) => {
330
312
  captureEvent({
@@ -384,21 +366,6 @@ function inspectMattermostIngressEvent(rawEvent) {
384
366
  laneKey: `channel:${typeof post.channel_id === "string" && post.channel_id.trim() ? post.channel_id.trim() : typeof data?.channel_id === "string" && data.channel_id.trim() ? data.channel_id.trim() : requiredString(broadcast?.channel_id, "channel_id")}`
385
367
  };
386
368
  }
387
- function parseClaimedEvent(rawEvent, eventId) {
388
- const payload = parseMattermostEventPayload(rawEvent);
389
- if (!payload || payload.event !== "posted") throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} is not a posted event.`);
390
- const post = parseMattermostPost(payload.data?.post);
391
- const claimedChannelId = post?.channel_id?.trim() || payload.data?.channel_id?.trim() || payload.broadcast?.channel_id?.trim();
392
- const senderId = post?.user_id?.trim();
393
- if (!post || post.id !== eventId || !senderId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} has invalid post identity.`);
394
- return {
395
- post: {
396
- ...post,
397
- user_id: senderId
398
- },
399
- payload
400
- };
401
- }
402
369
  function resolveMattermostIngressNonRetryableFailure(error) {
403
370
  if (error instanceof MattermostIngressPermanentError) return {
404
371
  reason: error.reason,
@@ -435,15 +402,23 @@ function createMattermostIngressMonitor(options) {
435
402
  createClaimError: (kind, claim) => new MattermostIngressPermanentError("invalid-event", kind === "invalid-version" ? `Mattermost ingress row ${claim.id} has an unsupported version.` : `Mattermost ingress row ${claim.id} has invalid post identity.`)
436
403
  },
437
404
  deliver: async (rawEvent, lifecycle, claim) => {
438
- const { post, payload } = parseClaimedEvent(rawEvent, claim.id);
439
- return await options.dispatch(post, payload, lifecycle);
405
+ const payload = parseMattermostEventPayload(rawEvent);
406
+ if (!payload || payload.event !== "posted") throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${claim.id} is not a posted event.`);
407
+ const post = parseMattermostPost(payload.data?.post);
408
+ const claimedChannelId = post?.channel_id?.trim() || payload.data?.channel_id?.trim() || payload.broadcast?.channel_id?.trim();
409
+ const senderId = post?.user_id?.trim();
410
+ if (!post || post.id !== claim.id || !senderId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${claim.id} has invalid post identity.`);
411
+ return await options.dispatch({
412
+ ...post,
413
+ user_id: senderId
414
+ }, payload, lifecycle);
440
415
  },
441
416
  pollIntervalMs: options.pollIntervalMs ?? MATTERMOST_INGRESS_POLL_INTERVAL_MS,
442
- waitForDeliveryIdleBeforeRepump: true,
443
417
  retention: "standard",
444
418
  drain: {
419
+ deferredLaneOccupancy: "release",
445
420
  resolveNonRetryableFailure: resolveMattermostIngressNonRetryableFailure,
446
- ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
421
+ adoptionStallTimeoutMs: options.adoptionStallTimeoutMs,
447
422
  onLog: (message) => options.runtime.log?.(`mattermost ${message}`)
448
423
  },
449
424
  ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
@@ -464,69 +439,6 @@ function createMattermostIngressMonitor(options) {
464
439
  waitForIdle: monitor.waitForIdle
465
440
  };
466
441
  }
467
- // extensions/mattermost/src/mattermost/monitor-context.ts
468
- function shouldUpdateMattermostDraftToolProgress(account) {
469
- return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config, account.streamingMode !== "progress", account.streamingMode);
470
- }
471
- function buildMattermostModelPickerSelectMessageSid(params) {
472
- const provider = normalizeLowercaseStringOrEmpty(params.provider);
473
- const model = normalizeLowercaseStringOrEmpty(params.model);
474
- return `interaction:${params.postId}:select:${provider}/${model}`;
475
- }
476
- function buildMattermostButtonInteractionMessageSid(params) {
477
- return `interaction:${params.postId}:${params.actionId}`;
478
- }
479
- function resolveMattermostReplyRootId(params) {
480
- const threadRootId = normalizeOptionalString(params.threadRootId);
481
- if (params.kind === "direct" && !threadRootId) return;
482
- if (threadRootId) return threadRootId;
483
- return normalizeOptionalString(params.replyToId);
484
- }
485
- function resolveMattermostInteractionReplyRootId(params) {
486
- const interactionMessageSid = normalizeOptionalString(params.interactionMessageSid);
487
- const replyToId = normalizeOptionalString(params.replyToId);
488
- const providerReplyToId = replyToId === interactionMessageSid ? normalizeOptionalString(params.sourcePostId) : replyToId;
489
- return resolveMattermostReplyRootId({
490
- kind: params.kind,
491
- threadRootId: params.threadRootId,
492
- replyToId: providerReplyToId
493
- });
494
- }
495
- function canFinalizeMattermostPreviewInPlace(params) {
496
- return resolveMattermostReplyRootId({
497
- kind: params.kind,
498
- threadRootId: params.threadRootId,
499
- replyToId: params.replyToId
500
- }) === params.previewRootId?.trim();
501
- }
502
- function formatMattermostFinalDeliveryOutcomeLog(params) {
503
- if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
504
- if (params.outcome === "empty") {
505
- const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
506
- const mediaUrlCount = countOutboundMedia(params.payload);
507
- if (finalText.length > 0 || mediaUrlCount > 0) return `mattermost no-visible-reply: no-visible-reply-after-final-delivery to=${params.to} accountId=${params.accountId} agentId=${params.agentId ?? "unknown"} outcome=${params.outcome} finalTextLength=${finalText.length} mediaUrlCount=${mediaUrlCount}`;
508
- }
509
- }
510
- function resolveMattermostThreadSessionContext(params) {
511
- const effectiveReplyToId = params.kind === "direct" && params.replyToMode === "off" ? void 0 : normalizeOptionalString(params.threadRootId) ?? (params.replyToMode !== "off" ? normalizeOptionalString(params.postId) : void 0);
512
- const threadKeys = resolveThreadSessionKeys({
513
- baseSessionKey: params.baseSessionKey,
514
- threadId: effectiveReplyToId,
515
- normalizeThreadId: (threadId) => threadId,
516
- parentSessionKey: effectiveReplyToId && params.kind !== "direct" ? params.baseSessionKey : void 0
517
- });
518
- return {
519
- effectiveReplyToId,
520
- sessionKey: threadKeys.sessionKey,
521
- parentSessionKey: threadKeys.parentSessionKey
522
- };
523
- }
524
- function resolveMattermostPendingHistoryKey(params) {
525
- return params.kind === "direct" && !params.threadRootId ? null : params.sessionKey;
526
- }
527
- function resolveMattermostReactionChannelId(payload) {
528
- return normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
529
- }
530
442
  // extensions/mattermost/src/mattermost/monitor-event-plan.ts
531
443
  async function buildMattermostEventPlan(monitor, params) {
532
444
  const channelInfo = params.channelInfo ?? await monitor.resources.resolveChannelInfo(params.channelId);
@@ -558,23 +470,18 @@ async function buildMattermostEventPlan(monitor, params) {
558
470
  threadRootId: params.threadRootId
559
471
  });
560
472
  const to = kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
561
- const from = kind === "direct" ? `mattermost:${params.senderId}` : kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`;
562
473
  return {
563
474
  channelId: params.channelId,
564
475
  senderId: params.senderId,
565
- channelInfo,
566
476
  kind,
567
- teamId,
568
- channelName,
569
477
  channelDisplay,
570
478
  roomLabel,
571
479
  route,
572
480
  thread,
573
481
  to,
574
- from,
575
482
  finalizeContext: (context) => finalizeInboundContext({
576
483
  ...context,
577
- From: from,
484
+ From: kind === "direct" ? `mattermost:${params.senderId}` : kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
578
485
  To: to,
579
486
  SessionKey: thread.sessionKey,
580
487
  DmScope: route.dmScope,
@@ -613,7 +520,7 @@ async function buildMattermostEventPlan(monitor, params) {
613
520
  });
614
521
  }
615
522
  } },
616
- replyOptions: { disableBlockStreaming: typeof monitor.account.blockStreaming === "boolean" ? !monitor.account.blockStreaming : void 0 }
523
+ replyOptions: { disableBlockStreaming: monitor.account.blockStreaming === void 0 ? void 0 : !monitor.account.blockStreaming }
617
524
  })
618
525
  };
619
526
  }
@@ -671,65 +578,10 @@ async function dispatchMattermostInteractionReply(monitor, eventPlan, params) {
671
578
  });
672
579
  }
673
580
  // extensions/mattermost/src/mattermost/monitor-interactions.ts
674
- /**
675
- * Answer an ask_user question from the button its own prompt offered.
676
- *
677
- * The Gateway owns the answer, so this consumes the click instead of letting it
678
- * fall through to the synthetic `[Button click: ...]` message the generic path
679
- * sends; that message would reach the agent as prose while the question stayed
680
- * open.
681
- */
682
- function createMattermostQuestionInteractionHandler(monitor) {
683
- const { account, cfg, core, pairing, resources, runtime } = monitor;
684
- return async (interaction) => {
685
- const selection = parseMattermostQuestionContext(interaction.context);
686
- if (!selection) return null;
687
- const channelInfo = await resources.resolveChannelInfo(interaction.payload.channel_id);
688
- const decide = async () => await authorizeMattermostCommandInvocation({
689
- account,
690
- cfg,
691
- senderId: interaction.payload.user_id,
692
- senderName: interaction.userName,
693
- channelId: interaction.payload.channel_id,
694
- channelInfo,
695
- readStoreAllowFrom: pairing.readAllowFromStore,
696
- allowTextCommands: core.channel.commands.shouldHandleTextCommands({
697
- cfg,
698
- surface: "mattermost"
699
- }),
700
- hasControlCommand: false
701
- });
702
- const auth = await decide();
703
- if (!auth.ok) return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
704
- try {
705
- const result = await questionGatewayRuntime.resolveOption({
706
- cfg,
707
- questionId: selection.questionId,
708
- optionIndex: selection.optionIndex,
709
- senderId: interaction.payload.user_id,
710
- clientDisplayName: `Mattermost question (${account.accountId})`,
711
- authorize: async () => (await decide()).ok
712
- });
713
- if (result.status === "denied") return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
714
- if (result.status !== "answered") return { ephemeral_text: "This question was already answered." };
715
- } catch (err) {
716
- runtime.error?.(`mattermost question interaction failed: ${String(err)}`);
717
- return { ephemeral_text: "Could not submit this answer." };
718
- }
719
- return {
720
- update: {
721
- message: interaction.post.message ?? "",
722
- props: { attachments: [{ text: `✓ **${interaction.actionName}** selected by @${interaction.userName}` }] }
723
- },
724
- ephemeral_text: "Answer submitted."
725
- };
726
- };
727
- }
728
581
  function registerMattermostInteractions(params) {
729
582
  const { monitor } = params;
730
583
  const { account, cfg, client, core, pairing, resources, runtime } = monitor;
731
584
  const { resolveChannelInfo } = resources;
732
- const handleQuestionInteraction = createMattermostQuestionInteractionHandler(monitor);
733
585
  return registerPluginHttpRoute({
734
586
  path: params.interactionPath,
735
587
  fallbackPath: "/mattermost/interactions/default",
@@ -740,7 +592,57 @@ function registerMattermostInteractions(params) {
740
592
  allowedSourceIps: params.allowedSourceIps,
741
593
  trustedProxies: cfg.gateway?.trustedProxies,
742
594
  allowRealIpFallback: cfg.gateway?.allowRealIpFallback === true,
743
- handleInteraction: async (interaction) => await handleQuestionInteraction(interaction) ?? await params.handleModelPickerInteraction(interaction),
595
+ /**
596
+ * Answer an ask_user question from the button its own prompt offered.
597
+ *
598
+ * The Gateway owns the answer, so this consumes the click instead of letting it
599
+ * fall through to the synthetic `[Button click: ...]` message the generic path
600
+ * sends; that message would reach the agent as prose while the question stayed
601
+ * open.
602
+ */
603
+ handleInteraction: async (interaction) => {
604
+ const selection = parseMattermostQuestionContext(interaction.context);
605
+ if (!selection) return await params.handleModelPickerInteraction(interaction);
606
+ const channelInfo = await resources.resolveChannelInfo(interaction.payload.channel_id);
607
+ const decide = async () => await authorizeMattermostCommandInvocation({
608
+ account,
609
+ cfg,
610
+ senderId: interaction.payload.user_id,
611
+ senderName: interaction.userName,
612
+ channelId: interaction.payload.channel_id,
613
+ channelInfo,
614
+ readStoreAllowFrom: pairing.readAllowFromStore,
615
+ allowTextCommands: core.channel.commands.shouldHandleTextCommands({
616
+ cfg,
617
+ surface: "mattermost"
618
+ }),
619
+ hasControlCommand: false
620
+ });
621
+ const auth = await decide();
622
+ if (!auth.ok) return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
623
+ try {
624
+ const result = await questionGatewayRuntime.resolveOption({
625
+ cfg,
626
+ questionId: selection.questionId,
627
+ optionIndex: selection.optionIndex,
628
+ senderId: interaction.payload.user_id,
629
+ clientDisplayName: `Mattermost question (${account.accountId})`,
630
+ authorize: async () => (await decide()).ok
631
+ });
632
+ if (result.status === "denied") return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
633
+ if (result.status !== "answered") return { ephemeral_text: "This question was already answered." };
634
+ } catch (err) {
635
+ runtime.error?.(`mattermost question interaction failed: ${String(err)}`);
636
+ return { ephemeral_text: "Could not submit this answer." };
637
+ }
638
+ return {
639
+ update: {
640
+ message: interaction.post.message ?? "",
641
+ props: { attachments: [{ text: `✓ **${interaction.actionName}** selected by @${interaction.userName}` }] }
642
+ },
643
+ ephemeral_text: "Answer submitted."
644
+ };
645
+ },
744
646
  authorizeButtonClick: async ({ payload }) => {
745
647
  const channelInfo = await resolveChannelInfo(payload.channel_id);
746
648
  const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
@@ -883,11 +785,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
883
785
  });
884
786
  const data = await buildPreparedModelsProviderData(cfg, eventPlan.route.agentId, { sessionEntry });
885
787
  const interactionId = params.payload.trigger_id ?? `${params.payload.post_id}:${params.payload.user_id}:${pickerCommandText}:${"page" in pickerState ? pickerState.page : 1}`;
886
- const messageSid = pickerState.action === "select" ? buildMattermostModelPickerSelectMessageSid({
887
- postId: params.payload.post_id,
888
- provider: pickerState.provider,
889
- model: pickerState.model
890
- }) : interactionId;
788
+ const messageSid = pickerState.action === "select" ? `interaction:${params.payload.post_id}:select:${normalizeLowercaseStringOrEmpty(pickerState.provider)}/${normalizeLowercaseStringOrEmpty(pickerState.model)}` : interactionId;
891
789
  const commandId = pickerState.action === "select" ? scopeCommandTranscriptId(messageSid, {
892
790
  channelId: "mattermost",
893
791
  accountId: account.accountId,
@@ -933,7 +831,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
933
831
  return await updatePickerPost(view.text, view.buttons);
934
832
  }
935
833
  const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
936
- if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
834
+ if (!data.providers.includes(pickerState.provider) || !data.byProvider.get(pickerState.provider)?.has(pickerState.model)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
937
835
  runDetachedWebhookWork(async () => {
938
836
  const commandText = `/model ${targetModelRef}`;
939
837
  const sourcePostId = params.post.id || params.payload.post_id;
@@ -994,29 +892,6 @@ function resolveBotThreadMentionPolicy(params) {
994
892
  implicitMentionKinds: params.requireMentionInBotThreads ? params.implicitMentionKinds?.filter((kind) => kind === "native") : params.implicitMentionKinds
995
893
  };
996
894
  }
997
- // extensions/mattermost/src/mattermost/monitor-activation.ts
998
- function resolveMattermostInboundMentionDecision(params) {
999
- const implicitMentions = resolveChannelImplicitMentions({
1000
- cfg: params.cfg,
1001
- channel: "mattermost",
1002
- accountId: params.accountId
1003
- });
1004
- return resolveInboundMentionDecision({
1005
- facts: {
1006
- canDetectMention: params.canDetectMention,
1007
- wasMentioned: params.wasMentioned,
1008
- implicitMentionKinds: params.implicitMentionKinds
1009
- },
1010
- policy: {
1011
- isGroup: params.kind !== "direct",
1012
- requireMention: params.requireMention,
1013
- implicitMentions,
1014
- allowTextCommands: params.allowTextCommands,
1015
- hasControlCommand: params.hasControlCommand,
1016
- commandAuthorized: params.commandAuthorized
1017
- }
1018
- });
1019
- }
1020
895
  // extensions/mattermost/src/mattermost/monitor-onchar.ts
1021
896
  const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
1022
897
  function resolveOncharPrefixes(prefixes) {
@@ -1110,7 +985,7 @@ function createMattermostMonitorResources(params) {
1110
985
  responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
1111
986
  readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
1112
987
  });
1113
- const contentType = saved.contentType ?? void 0;
988
+ const contentType = saved.contentType;
1114
989
  out.push({
1115
990
  path: saved.path,
1116
991
  contentType,
@@ -1353,23 +1228,8 @@ function createMattermostThreadBackfill(params) {
1353
1228
  }
1354
1229
  // extensions/mattermost/src/mattermost/draft-stream.ts
1355
1230
  const MATTERMOST_STREAM_MAX_CHARS = 4e3;
1356
- const DEFAULT_THROTTLE_MS = 1e3;
1357
- function normalizeMattermostDraftText(text, maxChars) {
1358
- const trimmed = text.trim();
1359
- if (!trimmed) return "";
1360
- if (trimmed.length <= maxChars) return trimmed;
1361
- return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
1362
- }
1363
- function consumeMattermostPublishedChunk(params) {
1364
- const chunk = params.chunk.trim();
1365
- if (!chunk) return params.offset;
1366
- let offset = params.offset;
1367
- while (offset < params.source.length && /\s/.test(params.source[offset] ?? "")) offset += 1;
1368
- return params.source.startsWith(chunk, offset) ? offset + chunk.length : void 0;
1369
- }
1231
+ const THROTTLE_MS = 1200;
1370
1232
  function createMattermostDraftStream(params) {
1371
- const maxChars = Math.min(params.maxChars ?? MATTERMOST_STREAM_MAX_CHARS, MATTERMOST_STREAM_MAX_CHARS);
1372
- const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
1373
1233
  const streamState = {
1374
1234
  stopped: false,
1375
1235
  final: false
@@ -1395,7 +1255,12 @@ function createMattermostDraftStream(params) {
1395
1255
  const publishedAssistantParts = /* @__PURE__ */ new Map();
1396
1256
  const sendOrEditStreamMessage = async (text) => {
1397
1257
  const target = currentGeneration;
1398
- const normalized = normalizeMattermostDraftText(params.renderText?.(text) ?? text, maxChars);
1258
+ const trimmed = text.trim();
1259
+ const normalized = trimmed ? truncateWithMarker(trimmed, MATTERMOST_STREAM_MAX_CHARS, {
1260
+ marker: "...",
1261
+ reserve: 3,
1262
+ trimEnd: true
1263
+ }) : "";
1399
1264
  if (!normalized) return false;
1400
1265
  await target.ready;
1401
1266
  if (streamState.stopped && !streamState.final) return false;
@@ -1422,7 +1287,7 @@ function createMattermostDraftStream(params) {
1422
1287
  }
1423
1288
  };
1424
1289
  const { loop, update: updateLifecycle, stop: stopLifecycle, stopForClear, clearWithStop, seal: sealLifecycle } = createFinalizableDraftLifecycle({
1425
- throttleMs,
1290
+ throttleMs: THROTTLE_MS,
1426
1291
  coalesceInFlight: true,
1427
1292
  state: streamState,
1428
1293
  sendOrEditStreamMessage,
@@ -1449,11 +1314,10 @@ function createMattermostDraftStream(params) {
1449
1314
  messageId,
1450
1315
  content
1451
1316
  });
1452
- publishedAssistantOffset = consumeMattermostPublishedChunk({
1453
- source: assistantText,
1454
- offset,
1455
- chunk: content
1456
- }) ?? offset;
1317
+ const chunk = content.trim();
1318
+ let nextOffset = offset;
1319
+ if (chunk) while (nextOffset < assistantText.length && /\s/.test(assistantText[nextOffset] ?? "")) nextOffset += 1;
1320
+ publishedAssistantOffset = !chunk || assistantText.startsWith(chunk, nextOffset) ? nextOffset + chunk.length : offset;
1457
1321
  };
1458
1322
  const boundary = (async () => {
1459
1323
  try {
@@ -1462,9 +1326,8 @@ function createMattermostDraftStream(params) {
1462
1326
  await inFlightAtBoundary;
1463
1327
  assertNoAcceptedDeliveryFailure();
1464
1328
  if (streamState.stopped && !streamState.final) return;
1465
- const sourceText = pendingText.trim() ? pendingText : sealed.latestSourceText;
1466
- const finalizedText = (params.renderText?.(sourceText) ?? sourceText).trim();
1467
- const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, maxChars, "length");
1329
+ const finalizedText = (pendingText.trim() ? pendingText : sealed.latestSourceText).trim();
1330
+ const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, MATTERMOST_STREAM_MAX_CHARS, "length");
1468
1331
  const firstChunk = chunks[0];
1469
1332
  if (!firstChunk) return;
1470
1333
  if (sealed.postId) {
@@ -1612,7 +1475,7 @@ function createMattermostDraftStream(params) {
1612
1475
  });
1613
1476
  return messages.find((post) => !post.type?.startsWith("system_") && (!params.rootId || post.root_id === params.rootId))?.id;
1614
1477
  };
1615
- params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
1478
+ params.log?.(`mattermost stream preview ready (maxChars=${MATTERMOST_STREAM_MAX_CHARS}, throttleMs=${THROTTLE_MS})`);
1616
1479
  return {
1617
1480
  update,
1618
1481
  updateAssistantText,
@@ -1630,17 +1493,6 @@ function createMattermostDraftStream(params) {
1630
1493
  };
1631
1494
  }
1632
1495
  // extensions/mattermost/src/mattermost/monitor-draft-delivery.ts
1633
- function combineMattermostVisibleDeliveryResults(results, outcome) {
1634
- const visibleResults = results.filter((result) => result?.visibleReplySent === true);
1635
- if (visibleResults.length === 0) return;
1636
- return {
1637
- outcome,
1638
- ...createAcceptedChannelDeliveryResult({
1639
- deliveryResults: visibleResults,
1640
- content: joinMattermostVisibleContent(visibleResults.map((result) => result.content))
1641
- })
1642
- };
1643
- }
1644
1496
  async function deliverMattermostReplyWithDraftPreview(params) {
1645
1497
  if (isReasoningReplyPayload(params.payload)) return {
1646
1498
  outcome: "reasoning_skipped",
@@ -1664,7 +1516,7 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1664
1516
  });
1665
1517
  }
1666
1518
  try {
1667
- return combineMattermostVisibleDeliveryResults([confirmedPreviewDelivery, (await params.previewLifecycle.deliver({
1519
+ const visibleResults = [confirmedPreviewDelivery, (await params.previewLifecycle.deliver({
1668
1520
  kind: params.info.kind,
1669
1521
  payload: params.payload,
1670
1522
  isError: params.payload.isError,
@@ -1718,7 +1570,7 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1718
1570
  const deliveryPayload = payload.isError !== true && supplement && (previewFinalTextAlreadyDelivered || !payloadText && supplement.visibleTextAlreadyDelivered === true) ? buildTtsSupplementMediaPayload(payload) : payload.isError !== true && supplement && !payloadText ? {
1719
1571
  ...payload,
1720
1572
  text: resolvedDeliveryText?.trim() ? resolvedDeliveryText : supplement.spokenText
1721
- } : payload.isError !== true && typeof resolvedDeliveryText === "string" ? {
1573
+ } : payload.isError !== true && resolvedDeliveryText !== void 0 ? {
1722
1574
  ...payload,
1723
1575
  text: resolvedDeliveryText
1724
1576
  } : payload;
@@ -1727,11 +1579,19 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1727
1579
  return delivered;
1728
1580
  },
1729
1581
  onNormalDelivered: params.recordThreadParticipation
1730
- })).deliveryResult], outcome) ?? {
1582
+ })).deliveryResult].filter((result) => result?.visibleReplySent === true);
1583
+ if (visibleResults.length === 0) return {
1731
1584
  outcome: "empty",
1732
1585
  visibleReplySent: false,
1733
1586
  suppression: { reason: "no_visible_result" }
1734
1587
  };
1588
+ return {
1589
+ outcome,
1590
+ ...createAcceptedChannelDeliveryResult({
1591
+ deliveryResults: visibleResults,
1592
+ content: joinMattermostVisibleContent(visibleResults.map((result) => result.content))
1593
+ })
1594
+ };
1735
1595
  } catch (error) {
1736
1596
  if (!confirmedPreviewDelivery?.visibleReplySent) throw error;
1737
1597
  const failedPartial = isChannelPartialDeliveryError(error) ? error.deliveryResult : void 0;
@@ -1757,12 +1617,9 @@ const threadParticipation = createPersistentDedupeCache({
1757
1617
  function makeKey(accountId, channelId, threadRootId) {
1758
1618
  return `${accountId}:${channelId}:${threadRootId}`;
1759
1619
  }
1760
- async function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
1620
+ async function recordMattermostThreadParticipation(accountId, channelId, threadRootId) {
1761
1621
  if (!accountId || !channelId || !threadRootId) return;
1762
- await threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
1763
- ...opts?.agentId ? { agentId: opts.agentId } : {},
1764
- repliedAt: Date.now()
1765
- });
1622
+ await threadParticipation.register(makeKey(accountId, channelId, threadRootId), { repliedAt: Date.now() });
1766
1623
  }
1767
1624
  async function hasMattermostThreadParticipationWithPersistence(params) {
1768
1625
  if (!params.accountId || !params.channelId || !params.threadRootId) return false;
@@ -1771,7 +1628,7 @@ async function hasMattermostThreadParticipationWithPersistence(params) {
1771
1628
  // extensions/mattermost/src/mattermost/monitor-turn.ts
1772
1629
  async function dispatchMattermostInboundTurn(monitor, params) {
1773
1630
  const { account, cfg, client, core, runtime } = monitor;
1774
- const { channelHistories, ctxPayload, eventPlan, historyKey, historyLimit, pinnedMainDmOwner, post, rawText, turnAdoptionLifecycle } = params;
1631
+ const { botLoopProtection, channelHistories, ctxPayload, eventPlan, historyKey, historyLimit, pinnedMainDmOwner, post, rawText, turnAdoptionLifecycle } = params;
1775
1632
  const { channelId, kind, route, senderId, thread, to } = eventPlan;
1776
1633
  const { effectiveReplyToId } = thread;
1777
1634
  const { replyOptions, replyPipeline: baseReplyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
@@ -1790,7 +1647,6 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1790
1647
  client,
1791
1648
  channelId,
1792
1649
  rootId: effectiveReplyToId,
1793
- throttleMs: 1200,
1794
1650
  chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(core.channel.text.convertMarkdownTables(value, tableMode), textLimit, chunkMode),
1795
1651
  log: monitor.logVerboseMessage,
1796
1652
  warn: monitor.logVerboseMessage
@@ -1844,7 +1700,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1844
1700
  onCleanupFailure: (err) => monitor.logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`)
1845
1701
  });
1846
1702
  const resolvePreviewFinalText = (text) => {
1847
- const finalText = typeof text === "string" ? text : "";
1703
+ const finalText = text ?? "";
1848
1704
  const resolution = draftStream?.resolveFinalText(finalText) ?? {
1849
1705
  kind: "full",
1850
1706
  text: finalText,
@@ -1923,7 +1779,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1923
1779
  const markThreadParticipation = async () => {
1924
1780
  if (!threadParticipationRecorded && kind !== "direct" && effectiveReplyToId) {
1925
1781
  threadParticipationRecorded = true;
1926
- await recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
1782
+ await recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId);
1927
1783
  }
1928
1784
  };
1929
1785
  const result = await deliverMattermostReplyWithDraftPreview({
@@ -1938,7 +1794,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1938
1794
  recordThreadParticipation: markThreadParticipation,
1939
1795
  findPostAfterPreview: draftStream?.findPostAfter,
1940
1796
  deliverPayload: async (payloadToDeliver) => {
1941
- const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && typeof payloadToDeliver.text === "string" ? draftStream?.resolveFinalText(payloadToDeliver.text) : void 0;
1797
+ const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && payloadToDeliver.text !== void 0 ? draftStream?.resolveFinalText(payloadToDeliver.text) : void 0;
1942
1798
  const resolvedPayload = finalTextResolution ? {
1943
1799
  ...payloadToDeliver,
1944
1800
  text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
@@ -1989,6 +1845,9 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1989
1845
  channel: "mattermost",
1990
1846
  accountId: route.accountId,
1991
1847
  raw: post,
1848
+ log: (event) => {
1849
+ if (event.reason === "bot-loop-protection") runtime.log?.(`mattermost: drop bot post (bot-loop-protection channel=${channelId} sender=${senderId})`);
1850
+ },
1992
1851
  adapter: {
1993
1852
  ingest: () => ({
1994
1853
  id: post.id ?? `${to}:${Date.now()}`,
@@ -2008,6 +1867,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2008
1867
  sessionKey: route.sessionKey
2009
1868
  },
2010
1869
  ctxPayload,
1870
+ botLoopProtection,
2011
1871
  record: {
2012
1872
  updateLastRoute: kind === "direct" ? {
2013
1873
  sessionKey: inboundLastRouteSessionKey,
@@ -2151,8 +2011,16 @@ function createMattermostPostHandler(monitor) {
2151
2011
  });
2152
2012
  if (!eventPlan) return;
2153
2013
  const { channelDisplay, kind, roomLabel, route, thread } = eventPlan;
2014
+ const isBotPost = post.props?.from_bot === "true";
2015
+ const channelBotConfig = kind === "direct" ? void 0 : account.config.groups?.[channelId];
2016
+ const wildcardBotConfig = kind === "direct" ? void 0 : account.config.groups?.["*"];
2017
+ const allowBots = channelBotConfig?.allowBots ?? wildcardBotConfig?.allowBots ?? account.config.allowBots ?? true;
2018
+ if (isBotPost && allowBots === false) {
2019
+ monitor.logVerboseMessage(`mattermost: drop bot post (allowBots=false sender=${senderId})`);
2020
+ return;
2021
+ }
2154
2022
  const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
2155
- const rawPostText = typeof post.message === "string" ? post.message : "";
2023
+ const rawPostText = post.message ?? "";
2156
2024
  const rawText = normalizeOptionalString(rawPostText) ?? "";
2157
2025
  const commandBody = normalizeMention(rawText, botUsername).trim();
2158
2026
  const { effectiveReplyToId, sessionKey } = thread;
@@ -2161,11 +2029,7 @@ function createMattermostPostHandler(monitor) {
2161
2029
  agentId: route.agentId,
2162
2030
  sessionKey
2163
2031
  });
2164
- const historyKey = resolveMattermostPendingHistoryKey({
2165
- kind,
2166
- sessionKey,
2167
- threadRootId: effectiveReplyToId
2168
- });
2032
+ const historyKey = kind === "direct" && !effectiveReplyToId ? null : sessionKey;
2169
2033
  const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2170
2034
  const nativeMedia = fileIds.map(() => ({}));
2171
2035
  const pendingBody = formatMattermostPendingMediaText({
@@ -2180,7 +2044,7 @@ function createMattermostPostHandler(monitor) {
2180
2044
  entry: historyKey && trimmed ? {
2181
2045
  sender: senderName,
2182
2046
  body: trimmed,
2183
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2047
+ timestamp: post.create_at ?? void 0,
2184
2048
  messageId: post.id
2185
2049
  } : null
2186
2050
  });
@@ -2307,17 +2171,25 @@ function createMattermostPostHandler(monitor) {
2307
2171
  implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged)
2308
2172
  });
2309
2173
  const botThreadMentionRequired = isBotOwnedThread && requireMentionInBotThreads === true;
2310
- const mentionDecision = resolveMattermostInboundMentionDecision({
2174
+ const implicitMentions = resolveChannelImplicitMentions({
2311
2175
  cfg,
2312
- accountId: account.accountId,
2313
- kind,
2314
- requireMention: botThreadPolicy.requireMention,
2315
- canDetectMention: canDetectMention || oncharEnabled || botThreadMentionRequired,
2316
- wasMentioned: wasMentioned || oncharTriggered,
2317
- implicitMentionKinds: botThreadPolicy.implicitMentionKinds,
2318
- allowTextCommands,
2319
- hasControlCommand: isControlCommand,
2320
- commandAuthorized
2176
+ channel: "mattermost",
2177
+ accountId: account.accountId
2178
+ });
2179
+ const mentionDecision = resolveInboundMentionDecision({
2180
+ facts: {
2181
+ canDetectMention: canDetectMention || oncharEnabled || botThreadMentionRequired,
2182
+ wasMentioned: wasMentioned || oncharTriggered,
2183
+ implicitMentionKinds: botThreadPolicy.implicitMentionKinds
2184
+ },
2185
+ policy: {
2186
+ isGroup: kind !== "direct",
2187
+ requireMention: botThreadPolicy.requireMention,
2188
+ implicitMentions,
2189
+ allowTextCommands,
2190
+ hasControlCommand: isControlCommand,
2191
+ commandAuthorized
2192
+ }
2321
2193
  });
2322
2194
  const { shouldBypassMention } = mentionDecision;
2323
2195
  if (mentionDecision.shouldSkip && oncharEnabled && !oncharTriggered && !wasMentioned && !shouldBypassMention) {
@@ -2337,6 +2209,11 @@ function createMattermostPostHandler(monitor) {
2337
2209
  recordPendingHistory();
2338
2210
  return;
2339
2211
  }
2212
+ if (isBotPost && allowBots === "mentions" && kind !== "direct" && !wasMentioned && !oncharTriggered) {
2213
+ monitor.logVerboseMessage(`mattermost: drop bot post (allowBots=mentions, missing mention channel=${channelId} sender=${senderId})`);
2214
+ recordPendingHistory();
2215
+ return;
2216
+ }
2340
2217
  const mediaList = await resolveMattermostMedia(fileIds);
2341
2218
  const bodyText = normalizeMention(formatMattermostInboundMediaText({
2342
2219
  body: oncharTriggered ? oncharResult.stripped : rawText,
@@ -2369,7 +2246,7 @@ function createMattermostPostHandler(monitor) {
2369
2246
  const body = formatInboundEnvelope({
2370
2247
  channel: "Mattermost",
2371
2248
  from: fromLabel,
2372
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2249
+ timestamp: post.create_at ?? void 0,
2373
2250
  body: textWithId,
2374
2251
  chatType: kind,
2375
2252
  sender: {
@@ -2422,7 +2299,7 @@ function createMattermostPostHandler(monitor) {
2422
2299
  MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2423
2300
  MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2424
2301
  MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2425
- Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2302
+ Timestamp: post.create_at ?? void 0,
2426
2303
  WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2427
2304
  CommandAuthorized: commandAuthorized,
2428
2305
  CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
@@ -2434,6 +2311,17 @@ function createMattermostPostHandler(monitor) {
2434
2311
  normalizeEntry: normalizeMattermostAllowEntry
2435
2312
  }) : null;
2436
2313
  monitor.logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} id=${post.id} len=${bodyText.length}`);
2314
+ const botLoopProtection = isBotPost ? {
2315
+ scopeId: account.accountId,
2316
+ conversationId: channelId,
2317
+ senderId,
2318
+ receiverId: botUserId,
2319
+ eventId: post.id,
2320
+ config: mergePairLoopGuardConfig(account.config.botLoopProtection, wildcardBotConfig?.botLoopProtection, channelBotConfig?.botLoopProtection),
2321
+ defaultsConfig: cfg.channels?.defaults?.botLoopProtection,
2322
+ defaultEnabled: true,
2323
+ nowMs: post.create_at ?? void 0
2324
+ } : void 0;
2437
2325
  await dispatchMattermostInboundTurn(monitor, {
2438
2326
  post,
2439
2327
  rawText,
@@ -2443,6 +2331,7 @@ function createMattermostPostHandler(monitor) {
2443
2331
  historyLimit,
2444
2332
  channelHistories,
2445
2333
  pinnedMainDmOwner,
2334
+ botLoopProtection,
2446
2335
  turnAdoptionLifecycle
2447
2336
  });
2448
2337
  };
@@ -2467,7 +2356,7 @@ function createMattermostReactionHandler(monitor) {
2467
2356
  if (!userId || !postId || !emojiName || userId === botUserId) return;
2468
2357
  const action = payload.event === "reaction_removed" ? "removed" : "added";
2469
2358
  const senderName = normalizeOptionalString((await resolveUserInfo(userId))?.username) ?? userId;
2470
- const channelId = resolveMattermostReactionChannelId(payload);
2359
+ const channelId = normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
2471
2360
  if (!channelId) {
2472
2361
  monitor.logVerboseMessage("mattermost: drop reaction (no channel_id in broadcast, cannot enforce policy)");
2473
2362
  return;
@@ -2511,49 +2400,6 @@ function createMattermostReactionHandler(monitor) {
2511
2400
  };
2512
2401
  }
2513
2402
  // extensions/mattermost/src/mattermost/monitor-slash.ts
2514
- async function buildSlashCommands(params) {
2515
- const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
2516
- if (!params.nativeSkills) return commandsToRegister;
2517
- try {
2518
- const skillCommands = await prepareSkillCommandsForAgents({ cfg: params.cfg });
2519
- for (const spec of skillCommands) {
2520
- const name = typeof spec.name === "string" ? spec.name.trim() : "";
2521
- if (!name) continue;
2522
- const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
2523
- commandsToRegister.push({
2524
- trigger,
2525
- description: spec.description || `Run skill ${name}`,
2526
- autoComplete: true,
2527
- autoCompleteHint: "[args]",
2528
- originalName: name
2529
- });
2530
- }
2531
- } catch (err) {
2532
- params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
2533
- }
2534
- return commandsToRegister;
2535
- }
2536
- function dedupeSlashCommands(commands) {
2537
- const seen = /* @__PURE__ */ new Set();
2538
- return commands.filter((cmd) => {
2539
- const key = cmd.trigger.trim();
2540
- if (!key || seen.has(key)) return false;
2541
- seen.add(key);
2542
- return true;
2543
- });
2544
- }
2545
- function buildTriggerMap(commands) {
2546
- const triggerMap = /* @__PURE__ */ new Map();
2547
- for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
2548
- return triggerMap;
2549
- }
2550
- function warnOnSuspiciousCallbackUrl(params) {
2551
- try {
2552
- const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
2553
- const callbackHost = new URL(params.callbackUrl).hostname;
2554
- 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).`);
2555
- } catch {}
2556
- }
2557
2403
  async function registerMattermostMonitorSlashCommands(params) {
2558
2404
  const commandsRaw = params.account.config.commands;
2559
2405
  const slashConfig = resolveSlashCommandConfig(commandsRaw);
@@ -2563,18 +2409,40 @@ async function registerMattermostMonitorSlashCommands(params) {
2563
2409
  const slashCallbackUrl = resolveCallbackUrl({
2564
2410
  config: slashConfig,
2565
2411
  gatewayPort: (0, gateway_config_runtime_exports.resolveGatewayPort)(params.cfg),
2566
- gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
2412
+ gatewayHost: params.cfg.gateway?.customBindHost
2567
2413
  });
2568
- warnOnSuspiciousCallbackUrl({
2569
- runtime: params.runtime,
2570
- baseUrl: params.baseUrl,
2571
- callbackUrl: slashCallbackUrl
2414
+ try {
2415
+ const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
2416
+ const callbackHost = new URL(slashCallbackUrl).hostname;
2417
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${slashCallbackUrl} (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).`);
2418
+ } catch {}
2419
+ const cfg = params.cfg;
2420
+ const runtime = params.runtime;
2421
+ const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
2422
+ if (slashConfig.nativeSkills === true) try {
2423
+ const skillCommands = await prepareSkillCommandsForAgents({ cfg });
2424
+ for (const spec of skillCommands) {
2425
+ const name = spec.name.trim();
2426
+ if (!name) continue;
2427
+ const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
2428
+ commandsToRegister.push({
2429
+ trigger,
2430
+ description: spec.description || `Run skill ${name}`,
2431
+ autoComplete: true,
2432
+ autoCompleteHint: "[args]",
2433
+ originalName: name
2434
+ });
2435
+ }
2436
+ } catch (err) {
2437
+ runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
2438
+ }
2439
+ const seen = /* @__PURE__ */ new Set();
2440
+ const dedupedCommands = commandsToRegister.filter((cmd) => {
2441
+ const key = cmd.trigger.trim();
2442
+ if (!key || seen.has(key)) return false;
2443
+ seen.add(key);
2444
+ return true;
2572
2445
  });
2573
- const dedupedCommands = dedupeSlashCommands(await buildSlashCommands({
2574
- cfg: params.cfg,
2575
- runtime: params.runtime,
2576
- nativeSkills: slashConfig.nativeSkills === true
2577
- }));
2578
2446
  const registered = [];
2579
2447
  let teamRegistrationFailures = 0;
2580
2448
  for (const team of teams) try {
@@ -2596,11 +2464,12 @@ async function registerMattermostMonitorSlashCommands(params) {
2596
2464
  return;
2597
2465
  }
2598
2466
  if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
2467
+ const triggerMap = /* @__PURE__ */ new Map();
2468
+ for (const cmd of dedupedCommands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
2599
2469
  activateSlashCommands({
2600
2470
  account: params.account,
2601
- commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
2602
2471
  registeredCommands: registered,
2603
- triggerMap: buildTriggerMap(dedupedCommands),
2472
+ triggerMap,
2604
2473
  api: {
2605
2474
  cfg: params.cfg,
2606
2475
  runtime: params.runtime
@@ -2614,10 +2483,7 @@ async function registerMattermostMonitorSlashCommands(params) {
2614
2483
  }
2615
2484
  // extensions/mattermost/src/mattermost/reconnect.ts
2616
2485
  async function runWithReconnect(connectFn, opts = {}) {
2617
- const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
2618
- const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
2619
- const random = opts.random ?? Math.random;
2620
- let retryDelay = initialDelayMs;
2486
+ let retryDelay = 2e3;
2621
2487
  while (!opts.abortSignal?.aborted) {
2622
2488
  let failed = false;
2623
2489
  try {
@@ -2628,8 +2494,9 @@ async function runWithReconnect(connectFn, opts = {}) {
2628
2494
  opts.onError?.(err);
2629
2495
  }
2630
2496
  if (opts.abortSignal?.aborted) return;
2631
- if (!failed) retryDelay = initialDelayMs;
2632
- const delayMs = withJitter(retryDelay, jitterRatio, random);
2497
+ if (!failed) retryDelay = 2e3;
2498
+ const spread = retryDelay * .2;
2499
+ const delayMs = Math.round(retryDelay - spread + Math.random() * spread * 2);
2633
2500
  if (!failed && opts.reconnectAfterClose === false) return;
2634
2501
  opts.onReconnect?.(delayMs);
2635
2502
  try {
@@ -2637,15 +2504,9 @@ async function runWithReconnect(connectFn, opts = {}) {
2637
2504
  } catch (delayError) {
2638
2505
  if (!opts.abortSignal?.aborted) throw delayError;
2639
2506
  }
2640
- if (failed) retryDelay = Math.min(retryDelay * 2, maxDelayMs);
2507
+ if (failed) retryDelay = Math.min(retryDelay * 2, 6e4);
2641
2508
  }
2642
2509
  }
2643
- function withJitter(baseMs, jitterRatio, random) {
2644
- if (jitterRatio <= 0) return baseMs;
2645
- const normalized = Math.max(0, Math.min(1, random()));
2646
- const spread = baseMs * jitterRatio;
2647
- return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
2648
- }
2649
2510
  // extensions/mattermost/src/mattermost/monitor.ts
2650
2511
  function publishMattermostRecoveringStatus(statusSink, error) {
2651
2512
  statusSink?.({
@@ -2678,21 +2539,12 @@ async function monitorMattermostProvider(opts = {}) {
2678
2539
  channel: "mattermost",
2679
2540
  accountId: account.accountId
2680
2541
  });
2681
- const botToken = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
2682
- 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).`);
2683
- const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
2684
- if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
2685
- const client = createMattermostClient({
2686
- baseUrl,
2687
- botToken,
2688
- allowPrivateNetwork: account.config.network?.dangerouslyAllowPrivateNetwork === true
2689
- });
2542
+ const { client, baseUrl, botToken } = createMattermostAccountClient(account, opts);
2690
2543
  let botUser;
2691
2544
  await runWithReconnect(async () => {
2692
2545
  botUser = await fetchMattermostMe(client);
2693
2546
  }, {
2694
2547
  abortSignal: opts.abortSignal,
2695
- jitterRatio: .2,
2696
2548
  reconnectAfterClose: false,
2697
2549
  onError: (err) => {
2698
2550
  runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
@@ -2785,44 +2637,63 @@ async function monitorMattermostProvider(opts = {}) {
2785
2637
  const slashEnabled = getSlashCommandState(account.accountId) != null;
2786
2638
  const handlePost = createMattermostPostHandler(monitor);
2787
2639
  const handleReactionEvent = createMattermostReactionHandler(monitor);
2640
+ const pendingPosts = /* @__PURE__ */ new Set();
2641
+ const cancellationSettlements = [];
2642
+ const shutdown = new AbortController();
2643
+ const buildDebounceKey = (entry) => {
2644
+ const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2645
+ return channelId && entry.post.user_id ? `mattermost:${account.accountId}:${channelId}` : null;
2646
+ };
2788
2647
  const debouncer = core.channel.debounce.createInboundDebouncer({
2789
2648
  debounceMs: resolveDebounceMs(),
2790
2649
  resolveDebounceMs,
2791
- buildKey: (entry) => {
2792
- const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2793
- if (!channelId || !entry.post.user_id) return null;
2794
- const threadId = normalizeOptionalString(entry.post.root_id);
2795
- return `mattermost:${account.accountId}:${channelId}:${threadId ? `thread:${threadId}` : "channel"}:${entry.post.user_id}`;
2650
+ buildKey: buildDebounceKey,
2651
+ canAppend: (entry, pending) => {
2652
+ const last = pending.at(-1);
2653
+ return last?.post.user_id === entry.post.user_id && normalizeOptionalString(last.post.root_id) === normalizeOptionalString(entry.post.root_id);
2796
2654
  },
2655
+ serializeImmediate: true,
2797
2656
  shouldDebounce: (entry) => {
2798
2657
  if (normalizeOptionalString(entry.post.type) !== void 0 || entry.post.file_ids?.length) return false;
2799
2658
  const text = normalizeOptionalString(entry.post.message) ?? "";
2800
2659
  return Boolean(text) && !core.channel.commands.isControlCommandMessage(normalizeMention(text, botUsername), cfg);
2801
2660
  },
2802
2661
  onFlush: (entries, createFlush) => {
2662
+ for (const entry of entries) pendingPosts.delete(entry);
2803
2663
  const last = entries.at(-1);
2804
- const { lifecycle, settle } = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle));
2664
+ const { lifecycle, settle, cancel } = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle));
2805
2665
  return createFlush({
2806
2666
  lifecycle,
2807
2667
  dispatch: async (admissionLifecycle) => {
2668
+ if (shutdown.signal.aborted || admissionLifecycle.abortSignal.aborted) {
2669
+ await cancel();
2670
+ return;
2671
+ }
2808
2672
  if (!last) return;
2809
- try {
2810
- const mergedPost = entries.length === 1 ? last.post : {
2673
+ if (entries.length === 1) await handlePost(last.post, last.payload, admissionLifecycle);
2674
+ else {
2675
+ const mergedPost = {
2811
2676
  ...last.post,
2812
2677
  message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
2813
2678
  file_ids: []
2814
2679
  };
2815
2680
  await handlePost(mergedPost, last.payload, admissionLifecycle, entries.length > 1 ? entries.map((entry) => entry.post.id) : void 0);
2816
- await settle();
2817
- } catch (error) {
2818
- await admissionLifecycle.onAbandoned();
2819
- throw error;
2820
2681
  }
2682
+ if (shutdown.signal.aborted || admissionLifecycle.abortSignal.aborted) await cancel();
2683
+ else await settle();
2821
2684
  }
2822
2685
  });
2823
2686
  },
2824
2687
  onError: (err) => {
2825
2688
  runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
2689
+ },
2690
+ onCancel: (entries) => {
2691
+ for (const entry of entries) pendingPosts.delete(entry);
2692
+ const settlement = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle)).cancel();
2693
+ cancellationSettlements.push(settlement);
2694
+ settlement.catch((error) => {
2695
+ runtime.error?.(`mattermost ingress cancellation failed: ${String(error)}`);
2696
+ });
2826
2697
  }
2827
2698
  });
2828
2699
  const ingress = createMattermostIngressMonitor({
@@ -2830,11 +2701,22 @@ async function monitorMattermostProvider(opts = {}) {
2830
2701
  runtime,
2831
2702
  abortSignal: opts.abortSignal,
2832
2703
  dispatch: async (post, payload, turnAdoptionLifecycle) => {
2833
- await debouncer.enqueue({
2704
+ if (shutdown.signal.aborted || turnAdoptionLifecycle.abortSignal.aborted) {
2705
+ await fanInChannelIngressLifecycles([turnAdoptionLifecycle]).cancel();
2706
+ return { kind: "deferred" };
2707
+ }
2708
+ const entry = {
2834
2709
  post,
2835
2710
  payload,
2836
2711
  turnAdoptionLifecycle
2837
- });
2712
+ };
2713
+ pendingPosts.add(entry);
2714
+ try {
2715
+ await debouncer.enqueue(entry);
2716
+ } catch (error) {
2717
+ pendingPosts.delete(entry);
2718
+ throw error;
2719
+ }
2838
2720
  return { kind: "deferred" };
2839
2721
  }
2840
2722
  });
@@ -2845,7 +2727,6 @@ async function monitorMattermostProvider(opts = {}) {
2845
2727
  abortSignal: opts.abortSignal,
2846
2728
  statusSink: opts.statusSink,
2847
2729
  runtime,
2848
- webSocketFactory: opts.webSocketFactory,
2849
2730
  nextSeq: () => sequence++,
2850
2731
  getBotUpdateAt: async () => (await fetchMattermostMe(client)).update_at ?? 0,
2851
2732
  onPosted: ingress.receive,
@@ -2868,10 +2749,11 @@ async function monitorMattermostProvider(opts = {}) {
2868
2749
  if (opts.abortSignal?.aborted) runAbortCleanup();
2869
2750
  else opts.abortSignal?.addEventListener("abort", runAbortCleanup, { once: true });
2870
2751
  }
2752
+ let connectionFailure;
2753
+ let shutdownFailures = [];
2871
2754
  try {
2872
2755
  await runWithReconnect(connectOnce, {
2873
2756
  abortSignal: opts.abortSignal,
2874
- jitterRatio: .2,
2875
2757
  onError: (err) => {
2876
2758
  runtime.error?.(`mattermost connection failed: ${String(err)}`);
2877
2759
  publishMattermostRecoveringStatus(opts.statusSink, err);
@@ -2880,10 +2762,22 @@ async function monitorMattermostProvider(opts = {}) {
2880
2762
  runtime.log?.(`mattermost reconnecting in ${Math.round(delayMs / 1e3)}s`);
2881
2763
  }
2882
2764
  });
2765
+ } catch (error) {
2766
+ connectionFailure = { error };
2883
2767
  } finally {
2884
- await ingress.stop();
2885
- unregisterInteractions();
2768
+ shutdown.abort();
2769
+ const pendingKeys = new Set([...pendingPosts].map(buildDebounceKey));
2770
+ for (const key of pendingKeys) if (key) debouncer.cancelKey(key);
2771
+ try {
2772
+ const stopped = await Promise.allSettled([ingress.stop(), debouncer.drain()]);
2773
+ const cancelled = await Promise.allSettled(cancellationSettlements);
2774
+ shutdownFailures = [...stopped, ...cancelled].flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2775
+ } finally {
2776
+ unregisterInteractions();
2777
+ }
2886
2778
  }
2887
2779
  await Promise.resolve(slashShutdownCleanup);
2780
+ if (shutdownFailures.length > 0) throw new AggregateError(shutdownFailures, "Mattermost monitor shutdown failed.", { cause: connectionFailure?.error });
2781
+ if (connectionFailure) throw connectionFailure.error;
2888
2782
  }
2889
2783
  export { monitorMattermostProvider };