@openclaw/mattermost 2026.11.3 → 2026.11.5-beta.2

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 (46) hide show
  1. package/dist/.setup/channel-plugin-api-ClU67Wyc.mjs +1 -0
  2. package/dist/.setup/{channel-plugin-runtime-DJgVmmbD.mjs → channel-plugin-api-CuxSSPV8.mjs} +146 -130
  3. package/dist/.setup/{channel.runtime-Cl_09ZUI.mjs → channel.runtime-B3RvYLQi.mjs} +28 -34
  4. package/dist/.setup/{client-B_4C9q6z.mjs → client-CR-hGmGr.mjs} +11 -84
  5. package/dist/.setup/{interactions-LQ_rJSdf.mjs → interactions-D5hhyPam.mjs} +23 -36
  6. package/dist/.setup/{monitor-CmsQnrEk.mjs → monitor-Bw_pTSF8.mjs} +292 -400
  7. package/dist/.setup/{monitor-auth-rr4M-8gH.mjs → monitor-auth-BxpEUfvc.mjs} +5 -11
  8. package/dist/.setup/{normalize-Dli2PK7k.mjs → normalize-CNFRtT1O.mjs} +21 -7
  9. package/dist/.setup/secret-contract-api-Drz4m5pq.mjs +2 -0
  10. package/dist/.setup/{send-C_-GT5iF.mjs → send-BSae9PKV.mjs} +100 -198
  11. package/dist/.setup/{slash-state-DJN_cER0.mjs → slash-state-DpZH2wr6.mjs} +362 -409
  12. package/dist/.source-module-urls/8fb0cb1067b83fd2cf3f3ba0f7a23e627c27e8e3adf1a4ea18753ddb884ff71e.json +1 -0
  13. package/dist/api.js +2 -2
  14. package/dist/channel-plugin-api.js +1 -2
  15. package/dist/doctor-contract-api.js +1 -2
  16. package/dist/gateway-auth-api.js +1 -2
  17. package/dist/policy-api.js +1 -2
  18. package/dist/runtime-api.js +1 -2
  19. package/dist/secret-contract-api.js +1 -2
  20. package/dist/setup-entry.js +2 -2
  21. package/dist/slash-route-api.js +1 -2
  22. package/node_modules/zod/package.json +1 -1
  23. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  24. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  25. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  26. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  27. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  28. package/node_modules/zod/src/v4/core/util.ts +13 -0
  29. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  30. package/node_modules/zod/v4/core/compile.cjs +8 -0
  31. package/node_modules/zod/v4/core/compile.js +8 -0
  32. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  33. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  34. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  35. package/node_modules/zod/v4/core/schemas.js +30 -0
  36. package/node_modules/zod/v4/core/util.cjs +15 -0
  37. package/node_modules/zod/v4/core/util.d.cts +2 -0
  38. package/node_modules/zod/v4/core/util.d.ts +2 -0
  39. package/node_modules/zod/v4/core/util.js +14 -0
  40. package/node_modules/zod/v4/core/versions.cjs +1 -1
  41. package/node_modules/zod/v4/core/versions.js +1 -1
  42. package/openclaw.plugin.json +172 -0
  43. package/package.json +5 -5
  44. package/dist/.setup/channel-plugin-api-BKpd51G7.mjs +0 -3
  45. package/dist/.setup/secret-contract-api-BGz5_6WD.mjs +0 -3
  46. package/dist/channel-plugin-runtime.js +0 -2
@@ -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-LQ_rJSdf.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-D5hhyPam.mjs";
2
2
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.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-B_4C9q6z.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-rr4M-8gH.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-CR-hGmGr.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-BxpEUfvc.mjs";
5
5
  import { n as normalizeMattermostAllowEntry } from "./ingress-identity-D6hxfxvo.mjs";
6
- import { d as resolveMattermostReplyToMode, r as parseMattermostQuestionContext, u as resolveMattermostAccount } from "./normalize-Dli2PK7k.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-DJN_cER0.mjs";
8
- import { t as sendMessageMattermost } from "./send-C_-GT5iF.mjs";
6
+ import { d as resolveMattermostAccount, f as resolveMattermostReplyToMode, o as createMattermostAccountClient, r as parseMattermostQuestionContext } from "./normalize-CNFRtT1O.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-DpZH2wr6.mjs";
8
+ import { t as sendMessageMattermost } from "./send-BSae9PKV.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";
@@ -83,6 +85,9 @@ function shouldDropEmptyMattermostBody(params) {
83
85
  const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16777216;
84
86
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
85
87
  const MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS = 3e4;
88
+ const MATTERMOST_WEBSOCKET_HEALTH_CHECK_INTERVAL_MS = 3e4;
89
+ const MATTERMOST_WEBSOCKET_PING_INTERVAL_MS = 3e4;
90
+ const MATTERMOST_WEBSOCKET_PONG_TIMEOUT_MS = 1e4;
86
91
  const MattermostEventPayloadSchema = z.object({
87
92
  event: z.string().optional(),
88
93
  status: z.string().optional(),
@@ -110,34 +115,7 @@ function parseMattermostPost(value) {
110
115
  if (typeof value === "string") return safeParseJsonWithSchema(MattermostPostSchema, value);
111
116
  return safeParseWithSchema(MattermostPostSchema, value);
112
117
  }
113
- var WebSocketClosedBeforeOpenError = class extends Error {
114
- constructor(code, reason) {
115
- super(`websocket closed before open (code ${code})`);
116
- this.code = code;
117
- this.reason = reason;
118
- this.name = "WebSocketClosedBeforeOpenError";
119
- }
120
- };
121
- var WebSocketClosedBeforeAuthenticationError = class extends Error {
122
- constructor(code, reason) {
123
- 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`);
124
- this.code = code;
125
- this.reason = reason;
126
- this.name = "WebSocketClosedBeforeAuthenticationError";
127
- }
128
- };
129
- const defaultMattermostWebSocketFactory = (url, options) => {
130
- const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
131
- return new WebSocket(url, {
132
- ...options,
133
- ...agent ? { agent } : {}
134
- });
135
- };
136
118
  function createMattermostConnectOnce(opts) {
137
- const webSocketFactory = opts.webSocketFactory ?? defaultMattermostWebSocketFactory;
138
- const healthCheckIntervalMs = opts.healthCheckIntervalMs ?? 3e4;
139
- const pingIntervalMs = opts.pingIntervalMs ?? 3e4;
140
- const pongTimeoutMs = opts.pongTimeoutMs ?? 1e4;
141
119
  return async () => {
142
120
  const flowId = randomUUID();
143
121
  const captureEvent = (event) => {
@@ -151,13 +129,14 @@ function createMattermostConnectOnce(opts) {
151
129
  }
152
130
  }).catch(() => {});
153
131
  };
154
- const ws = webSocketFactory(opts.wsUrl, {
132
+ const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
133
+ const ws = new WebSocket(opts.wsUrl, {
155
134
  maxPayload: MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES,
156
- handshakeTimeout: MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS
135
+ handshakeTimeout: MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS,
136
+ ...agent ? { agent } : {}
157
137
  });
158
138
  const onAbort = () => ws.terminate();
159
139
  opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
160
- const getBotUpdateAt = opts.getBotUpdateAt;
161
140
  try {
162
141
  return await new Promise((resolve, reject) => {
163
142
  let opened = false;
@@ -184,7 +163,7 @@ function createMattermostConnectOnce(opts) {
184
163
  opts.runtime.error?.("mattermost websocket pong timeout — reconnecting");
185
164
  stopHealthChecks();
186
165
  ws.terminate();
187
- }, pongTimeoutMs);
166
+ }, MATTERMOST_WEBSOCKET_PONG_TIMEOUT_MS);
188
167
  try {
189
168
  ws.ping();
190
169
  } catch (err) {
@@ -198,19 +177,19 @@ function createMattermostConnectOnce(opts) {
198
177
  protocolPingTimer = setTimeout(() => {
199
178
  protocolPingTimer = void 0;
200
179
  sendProtocolPing();
201
- }, pingIntervalMs);
180
+ }, MATTERMOST_WEBSOCKET_PING_INTERVAL_MS);
202
181
  };
203
182
  const scheduleHealthCheck = () => {
204
- if (!getBotUpdateAt || stopped) return;
183
+ if (stopped) return;
205
184
  healthCheckTimer = setTimeout(() => {
206
185
  healthCheckTimer = void 0;
207
186
  runHealthCheck();
208
- }, healthCheckIntervalMs);
187
+ }, MATTERMOST_WEBSOCKET_HEALTH_CHECK_INTERVAL_MS);
209
188
  };
210
189
  const runHealthCheck = async () => {
211
- if (!getBotUpdateAt || stopped) return;
190
+ if (stopped) return;
212
191
  try {
213
- const current = await getBotUpdateAt();
192
+ const current = await opts.getBotUpdateAt();
214
193
  if (stopped) return;
215
194
  if (initialUpdateAt === void 0) {
216
195
  initialUpdateAt = current;
@@ -259,14 +238,14 @@ function createMattermostConnectOnce(opts) {
259
238
  ws.terminate();
260
239
  }, MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS);
261
240
  scheduleProtocolPing();
262
- if (getBotUpdateAt) runHealthCheck();
241
+ runHealthCheck();
263
242
  });
264
243
  ws.on("pong", () => {
265
244
  clearTimeout(protocolPongTimer);
266
245
  protocolPongTimer = void 0;
267
246
  scheduleProtocolPing();
268
247
  });
269
- ws.on("message", async (data) => {
248
+ const onMessage = async (data) => {
270
249
  const raw = rawDataToString(data);
271
250
  captureEvent({
272
251
  direction: "inbound",
@@ -283,7 +262,6 @@ function createMattermostConnectOnce(opts) {
283
262
  return;
284
263
  }
285
264
  if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
286
- if (!opts.onReaction) return;
287
265
  try {
288
266
  await opts.onReaction(payload);
289
267
  } catch (err) {
@@ -298,6 +276,9 @@ function createMattermostConnectOnce(opts) {
298
276
  opts.runtime.error?.(`mattermost durable admission failed; terminating websocket: ${String(err)}`);
299
277
  ws.terminate();
300
278
  }
279
+ };
280
+ ws.on("message", (data) => {
281
+ onMessage(data);
301
282
  });
302
283
  ws.on("close", (code, reason) => {
303
284
  captureEvent({
@@ -321,11 +302,12 @@ function createMattermostConnectOnce(opts) {
321
302
  resolve();
322
303
  return;
323
304
  }
324
- if (opened) {
325
- reject(new WebSocketClosedBeforeAuthenticationError(code, message || void 0));
326
- return;
327
- }
328
- reject(new WebSocketClosedBeforeOpenError(code, message || void 0));
305
+ 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})`);
306
+ reject(Object.assign(error, {
307
+ code,
308
+ reason: message || void 0,
309
+ name: opened ? "WebSocketClosedBeforeAuthenticationError" : "WebSocketClosedBeforeOpenError"
310
+ }));
329
311
  });
330
312
  ws.on("error", (err) => {
331
313
  captureEvent({
@@ -386,21 +368,6 @@ function inspectMattermostIngressEvent(rawEvent) {
386
368
  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")}`
387
369
  };
388
370
  }
389
- function parseClaimedEvent(rawEvent, eventId) {
390
- const payload = parseMattermostEventPayload(rawEvent);
391
- if (!payload || payload.event !== "posted") throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} is not a posted event.`);
392
- const post = parseMattermostPost(payload.data?.post);
393
- const claimedChannelId = post?.channel_id?.trim() || payload.data?.channel_id?.trim() || payload.broadcast?.channel_id?.trim();
394
- const senderId = post?.user_id?.trim();
395
- if (!post || post.id !== eventId || !senderId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} has invalid post identity.`);
396
- return {
397
- post: {
398
- ...post,
399
- user_id: senderId
400
- },
401
- payload
402
- };
403
- }
404
371
  function resolveMattermostIngressNonRetryableFailure(error) {
405
372
  if (error instanceof MattermostIngressPermanentError) return {
406
373
  reason: error.reason,
@@ -437,15 +404,23 @@ function createMattermostIngressMonitor(options) {
437
404
  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.`)
438
405
  },
439
406
  deliver: async (rawEvent, lifecycle, claim) => {
440
- const { post, payload } = parseClaimedEvent(rawEvent, claim.id);
441
- return await options.dispatch(post, payload, lifecycle);
407
+ const payload = parseMattermostEventPayload(rawEvent);
408
+ if (!payload || payload.event !== "posted") throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${claim.id} is not a posted event.`);
409
+ const post = parseMattermostPost(payload.data?.post);
410
+ const claimedChannelId = post?.channel_id?.trim() || payload.data?.channel_id?.trim() || payload.broadcast?.channel_id?.trim();
411
+ const senderId = post?.user_id?.trim();
412
+ if (!post || post.id !== claim.id || !senderId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${claim.id} has invalid post identity.`);
413
+ return await options.dispatch({
414
+ ...post,
415
+ user_id: senderId
416
+ }, payload, lifecycle);
442
417
  },
443
418
  pollIntervalMs: options.pollIntervalMs ?? MATTERMOST_INGRESS_POLL_INTERVAL_MS,
444
- waitForDeliveryIdleBeforeRepump: true,
445
419
  retention: "standard",
446
420
  drain: {
421
+ deferredLaneOccupancy: "release",
447
422
  resolveNonRetryableFailure: resolveMattermostIngressNonRetryableFailure,
448
- ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
423
+ adoptionStallTimeoutMs: options.adoptionStallTimeoutMs,
449
424
  onLog: (message) => options.runtime.log?.(`mattermost ${message}`)
450
425
  },
451
426
  ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
@@ -467,70 +442,6 @@ function createMattermostIngressMonitor(options) {
467
442
  };
468
443
  }
469
444
  //#endregion
470
- //#region extensions/mattermost/src/mattermost/monitor-context.ts
471
- function shouldUpdateMattermostDraftToolProgress(account) {
472
- return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config, account.streamingMode !== "progress", account.streamingMode);
473
- }
474
- function buildMattermostModelPickerSelectMessageSid(params) {
475
- const provider = normalizeLowercaseStringOrEmpty(params.provider);
476
- const model = normalizeLowercaseStringOrEmpty(params.model);
477
- return `interaction:${params.postId}:select:${provider}/${model}`;
478
- }
479
- function buildMattermostButtonInteractionMessageSid(params) {
480
- return `interaction:${params.postId}:${params.actionId}`;
481
- }
482
- function resolveMattermostReplyRootId(params) {
483
- const threadRootId = normalizeOptionalString(params.threadRootId);
484
- if (params.kind === "direct" && !threadRootId) return;
485
- if (threadRootId) return threadRootId;
486
- return normalizeOptionalString(params.replyToId);
487
- }
488
- function resolveMattermostInteractionReplyRootId(params) {
489
- const interactionMessageSid = normalizeOptionalString(params.interactionMessageSid);
490
- const replyToId = normalizeOptionalString(params.replyToId);
491
- const providerReplyToId = replyToId === interactionMessageSid ? normalizeOptionalString(params.sourcePostId) : replyToId;
492
- return resolveMattermostReplyRootId({
493
- kind: params.kind,
494
- threadRootId: params.threadRootId,
495
- replyToId: providerReplyToId
496
- });
497
- }
498
- function canFinalizeMattermostPreviewInPlace(params) {
499
- return resolveMattermostReplyRootId({
500
- kind: params.kind,
501
- threadRootId: params.threadRootId,
502
- replyToId: params.replyToId
503
- }) === params.previewRootId?.trim();
504
- }
505
- function formatMattermostFinalDeliveryOutcomeLog(params) {
506
- if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
507
- if (params.outcome === "empty") {
508
- const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
509
- const mediaUrlCount = countOutboundMedia(params.payload);
510
- 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}`;
511
- }
512
- }
513
- function resolveMattermostThreadSessionContext(params) {
514
- const effectiveReplyToId = params.kind === "direct" && params.replyToMode === "off" ? void 0 : normalizeOptionalString(params.threadRootId) ?? (params.replyToMode !== "off" ? normalizeOptionalString(params.postId) : void 0);
515
- const threadKeys = resolveThreadSessionKeys({
516
- baseSessionKey: params.baseSessionKey,
517
- threadId: effectiveReplyToId,
518
- normalizeThreadId: (threadId) => threadId,
519
- parentSessionKey: effectiveReplyToId && params.kind !== "direct" ? params.baseSessionKey : void 0
520
- });
521
- return {
522
- effectiveReplyToId,
523
- sessionKey: threadKeys.sessionKey,
524
- parentSessionKey: threadKeys.parentSessionKey
525
- };
526
- }
527
- function resolveMattermostPendingHistoryKey(params) {
528
- return params.kind === "direct" && !params.threadRootId ? null : params.sessionKey;
529
- }
530
- function resolveMattermostReactionChannelId(payload) {
531
- return normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
532
- }
533
- //#endregion
534
445
  //#region extensions/mattermost/src/mattermost/monitor-event-plan.ts
535
446
  async function buildMattermostEventPlan(monitor, params) {
536
447
  const channelInfo = params.channelInfo ?? await monitor.resources.resolveChannelInfo(params.channelId);
@@ -562,23 +473,18 @@ async function buildMattermostEventPlan(monitor, params) {
562
473
  threadRootId: params.threadRootId
563
474
  });
564
475
  const to = kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
565
- const from = kind === "direct" ? `mattermost:${params.senderId}` : kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`;
566
476
  return {
567
477
  channelId: params.channelId,
568
478
  senderId: params.senderId,
569
- channelInfo,
570
479
  kind,
571
- teamId,
572
- channelName,
573
480
  channelDisplay,
574
481
  roomLabel,
575
482
  route,
576
483
  thread,
577
484
  to,
578
- from,
579
485
  finalizeContext: (context) => finalizeInboundContext({
580
486
  ...context,
581
- From: from,
487
+ From: kind === "direct" ? `mattermost:${params.senderId}` : kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
582
488
  To: to,
583
489
  SessionKey: thread.sessionKey,
584
490
  DmScope: route.dmScope,
@@ -617,7 +523,7 @@ async function buildMattermostEventPlan(monitor, params) {
617
523
  });
618
524
  }
619
525
  } },
620
- replyOptions: { disableBlockStreaming: typeof monitor.account.blockStreaming === "boolean" ? !monitor.account.blockStreaming : void 0 }
526
+ replyOptions: { disableBlockStreaming: monitor.account.blockStreaming === void 0 ? void 0 : !monitor.account.blockStreaming }
621
527
  })
622
528
  };
623
529
  }
@@ -677,65 +583,10 @@ async function dispatchMattermostInteractionReply(monitor, eventPlan, params) {
677
583
  }
678
584
  //#endregion
679
585
  //#region extensions/mattermost/src/mattermost/monitor-interactions.ts
680
- /**
681
- * Answer an ask_user question from the button its own prompt offered.
682
- *
683
- * The Gateway owns the answer, so this consumes the click instead of letting it
684
- * fall through to the synthetic `[Button click: ...]` message the generic path
685
- * sends; that message would reach the agent as prose while the question stayed
686
- * open.
687
- */
688
- function createMattermostQuestionInteractionHandler(monitor) {
689
- const { account, cfg, core, pairing, resources, runtime } = monitor;
690
- return async (interaction) => {
691
- const selection = parseMattermostQuestionContext(interaction.context);
692
- if (!selection) return null;
693
- const channelInfo = await resources.resolveChannelInfo(interaction.payload.channel_id);
694
- const decide = async () => await authorizeMattermostCommandInvocation({
695
- account,
696
- cfg,
697
- senderId: interaction.payload.user_id,
698
- senderName: interaction.userName,
699
- channelId: interaction.payload.channel_id,
700
- channelInfo,
701
- readStoreAllowFrom: pairing.readAllowFromStore,
702
- allowTextCommands: core.channel.commands.shouldHandleTextCommands({
703
- cfg,
704
- surface: "mattermost"
705
- }),
706
- hasControlCommand: false
707
- });
708
- const auth = await decide();
709
- if (!auth.ok) return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
710
- try {
711
- const result = await questionGatewayRuntime.resolveOption({
712
- cfg,
713
- questionId: selection.questionId,
714
- optionIndex: selection.optionIndex,
715
- senderId: interaction.payload.user_id,
716
- clientDisplayName: `Mattermost question (${account.accountId})`,
717
- authorize: async () => (await decide()).ok
718
- });
719
- if (result.status === "denied") return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
720
- if (result.status !== "answered") return { ephemeral_text: "This question was already answered." };
721
- } catch (err) {
722
- runtime.error?.(`mattermost question interaction failed: ${String(err)}`);
723
- return { ephemeral_text: "Could not submit this answer." };
724
- }
725
- return {
726
- update: {
727
- message: interaction.post.message ?? "",
728
- props: { attachments: [{ text: `✓ **${interaction.actionName}** selected by @${interaction.userName}` }] }
729
- },
730
- ephemeral_text: "Answer submitted."
731
- };
732
- };
733
- }
734
586
  function registerMattermostInteractions(params) {
735
587
  const { monitor } = params;
736
588
  const { account, cfg, client, core, pairing, resources, runtime } = monitor;
737
589
  const { resolveChannelInfo } = resources;
738
- const handleQuestionInteraction = createMattermostQuestionInteractionHandler(monitor);
739
590
  return registerPluginHttpRoute({
740
591
  path: params.interactionPath,
741
592
  fallbackPath: "/mattermost/interactions/default",
@@ -746,7 +597,57 @@ function registerMattermostInteractions(params) {
746
597
  allowedSourceIps: params.allowedSourceIps,
747
598
  trustedProxies: cfg.gateway?.trustedProxies,
748
599
  allowRealIpFallback: cfg.gateway?.allowRealIpFallback === true,
749
- handleInteraction: async (interaction) => await handleQuestionInteraction(interaction) ?? await params.handleModelPickerInteraction(interaction),
600
+ /**
601
+ * Answer an ask_user question from the button its own prompt offered.
602
+ *
603
+ * The Gateway owns the answer, so this consumes the click instead of letting it
604
+ * fall through to the synthetic `[Button click: ...]` message the generic path
605
+ * sends; that message would reach the agent as prose while the question stayed
606
+ * open.
607
+ */
608
+ handleInteraction: async (interaction) => {
609
+ const selection = parseMattermostQuestionContext(interaction.context);
610
+ if (!selection) return await params.handleModelPickerInteraction(interaction);
611
+ const channelInfo = await resources.resolveChannelInfo(interaction.payload.channel_id);
612
+ const decide = async () => await authorizeMattermostCommandInvocation({
613
+ account,
614
+ cfg,
615
+ senderId: interaction.payload.user_id,
616
+ senderName: interaction.userName,
617
+ channelId: interaction.payload.channel_id,
618
+ channelInfo,
619
+ readStoreAllowFrom: pairing.readAllowFromStore,
620
+ allowTextCommands: core.channel.commands.shouldHandleTextCommands({
621
+ cfg,
622
+ surface: "mattermost"
623
+ }),
624
+ hasControlCommand: false
625
+ });
626
+ const auth = await decide();
627
+ if (!auth.ok) return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
628
+ try {
629
+ const result = await questionGatewayRuntime.resolveOption({
630
+ cfg,
631
+ questionId: selection.questionId,
632
+ optionIndex: selection.optionIndex,
633
+ senderId: interaction.payload.user_id,
634
+ clientDisplayName: `Mattermost question (${account.accountId})`,
635
+ authorize: async () => (await decide()).ok
636
+ });
637
+ if (result.status === "denied") return { ephemeral_text: `OpenClaw ignored this action for ${auth.roomLabel}.` };
638
+ if (result.status !== "answered") return { ephemeral_text: "This question was already answered." };
639
+ } catch (err) {
640
+ runtime.error?.(`mattermost question interaction failed: ${String(err)}`);
641
+ return { ephemeral_text: "Could not submit this answer." };
642
+ }
643
+ return {
644
+ update: {
645
+ message: interaction.post.message ?? "",
646
+ props: { attachments: [{ text: `✓ **${interaction.actionName}** selected by @${interaction.userName}` }] }
647
+ },
648
+ ephemeral_text: "Answer submitted."
649
+ };
650
+ },
750
651
  authorizeButtonClick: async ({ payload }) => {
751
652
  const channelInfo = await resolveChannelInfo(payload.channel_id);
752
653
  const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
@@ -890,11 +791,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
890
791
  });
891
792
  const data = await buildPreparedModelsProviderData(cfg, eventPlan.route.agentId, { sessionEntry });
892
793
  const interactionId = params.payload.trigger_id ?? `${params.payload.post_id}:${params.payload.user_id}:${pickerCommandText}:${"page" in pickerState ? pickerState.page : 1}`;
893
- const messageSid = pickerState.action === "select" ? buildMattermostModelPickerSelectMessageSid({
894
- postId: params.payload.post_id,
895
- provider: pickerState.provider,
896
- model: pickerState.model
897
- }) : interactionId;
794
+ const messageSid = pickerState.action === "select" ? `interaction:${params.payload.post_id}:select:${normalizeLowercaseStringOrEmpty(pickerState.provider)}/${normalizeLowercaseStringOrEmpty(pickerState.model)}` : interactionId;
898
795
  const commandId = pickerState.action === "select" ? scopeCommandTranscriptId(messageSid, {
899
796
  channelId: "mattermost",
900
797
  accountId: account.accountId,
@@ -940,7 +837,7 @@ function createMattermostModelPickerInteractionHandler(monitor) {
940
837
  return await updatePickerPost(view.text, view.buttons);
941
838
  }
942
839
  const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
943
- if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
840
+ if (!data.providers.includes(pickerState.provider) || !data.byProvider.get(pickerState.provider)?.has(pickerState.model)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
944
841
  runDetachedWebhookWork(async () => {
945
842
  const commandText = `/model ${targetModelRef}`;
946
843
  const sourcePostId = params.post.id || params.payload.post_id;
@@ -1003,30 +900,6 @@ function resolveBotThreadMentionPolicy(params) {
1003
900
  };
1004
901
  }
1005
902
  //#endregion
1006
- //#region extensions/mattermost/src/mattermost/monitor-activation.ts
1007
- function resolveMattermostInboundMentionDecision(params) {
1008
- const implicitMentions = resolveChannelImplicitMentions({
1009
- cfg: params.cfg,
1010
- channel: "mattermost",
1011
- accountId: params.accountId
1012
- });
1013
- return resolveInboundMentionDecision({
1014
- facts: {
1015
- canDetectMention: params.canDetectMention,
1016
- wasMentioned: params.wasMentioned,
1017
- implicitMentionKinds: params.implicitMentionKinds
1018
- },
1019
- policy: {
1020
- isGroup: params.kind !== "direct",
1021
- requireMention: params.requireMention,
1022
- implicitMentions,
1023
- allowTextCommands: params.allowTextCommands,
1024
- hasControlCommand: params.hasControlCommand,
1025
- commandAuthorized: params.commandAuthorized
1026
- }
1027
- });
1028
- }
1029
- //#endregion
1030
903
  //#region extensions/mattermost/src/mattermost/monitor-onchar.ts
1031
904
  const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
1032
905
  function resolveOncharPrefixes(prefixes) {
@@ -1121,7 +994,7 @@ function createMattermostMonitorResources(params) {
1121
994
  responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
1122
995
  readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
1123
996
  });
1124
- const contentType = saved.contentType ?? void 0;
997
+ const contentType = saved.contentType;
1125
998
  out.push({
1126
999
  path: saved.path,
1127
1000
  contentType,
@@ -1366,23 +1239,8 @@ function createMattermostThreadBackfill(params) {
1366
1239
  //#endregion
1367
1240
  //#region extensions/mattermost/src/mattermost/draft-stream.ts
1368
1241
  const MATTERMOST_STREAM_MAX_CHARS = 4e3;
1369
- const DEFAULT_THROTTLE_MS = 1e3;
1370
- function normalizeMattermostDraftText(text, maxChars) {
1371
- const trimmed = text.trim();
1372
- if (!trimmed) return "";
1373
- if (trimmed.length <= maxChars) return trimmed;
1374
- return `${sliceUtf16Safe(trimmed, 0, Math.max(0, maxChars - 3)).trimEnd()}...`;
1375
- }
1376
- function consumeMattermostPublishedChunk(params) {
1377
- const chunk = params.chunk.trim();
1378
- if (!chunk) return params.offset;
1379
- let offset = params.offset;
1380
- while (offset < params.source.length && /\s/.test(params.source[offset] ?? "")) offset += 1;
1381
- return params.source.startsWith(chunk, offset) ? offset + chunk.length : void 0;
1382
- }
1242
+ const THROTTLE_MS = 1200;
1383
1243
  function createMattermostDraftStream(params) {
1384
- const maxChars = Math.min(params.maxChars ?? MATTERMOST_STREAM_MAX_CHARS, MATTERMOST_STREAM_MAX_CHARS);
1385
- const throttleMs = Math.max(250, params.throttleMs ?? DEFAULT_THROTTLE_MS);
1386
1244
  const streamState = {
1387
1245
  stopped: false,
1388
1246
  final: false
@@ -1408,7 +1266,12 @@ function createMattermostDraftStream(params) {
1408
1266
  const publishedAssistantParts = /* @__PURE__ */ new Map();
1409
1267
  const sendOrEditStreamMessage = async (text) => {
1410
1268
  const target = currentGeneration;
1411
- const normalized = normalizeMattermostDraftText(params.renderText?.(text) ?? text, maxChars);
1269
+ const trimmed = text.trim();
1270
+ const normalized = trimmed ? truncateWithMarker(trimmed, MATTERMOST_STREAM_MAX_CHARS, {
1271
+ marker: "...",
1272
+ reserve: 3,
1273
+ trimEnd: true
1274
+ }) : "";
1412
1275
  if (!normalized) return false;
1413
1276
  await target.ready;
1414
1277
  if (streamState.stopped && !streamState.final) return false;
@@ -1435,7 +1298,7 @@ function createMattermostDraftStream(params) {
1435
1298
  }
1436
1299
  };
1437
1300
  const { loop, update: updateLifecycle, stop: stopLifecycle, stopForClear, clearWithStop, seal: sealLifecycle } = createFinalizableDraftLifecycle({
1438
- throttleMs,
1301
+ throttleMs: THROTTLE_MS,
1439
1302
  coalesceInFlight: true,
1440
1303
  state: streamState,
1441
1304
  sendOrEditStreamMessage,
@@ -1462,11 +1325,10 @@ function createMattermostDraftStream(params) {
1462
1325
  messageId,
1463
1326
  content
1464
1327
  });
1465
- publishedAssistantOffset = consumeMattermostPublishedChunk({
1466
- source: assistantText,
1467
- offset,
1468
- chunk: content
1469
- }) ?? offset;
1328
+ const chunk = content.trim();
1329
+ let nextOffset = offset;
1330
+ if (chunk) while (nextOffset < assistantText.length && /\s/.test(assistantText[nextOffset] ?? "")) nextOffset += 1;
1331
+ publishedAssistantOffset = !chunk || assistantText.startsWith(chunk, nextOffset) ? nextOffset + chunk.length : offset;
1470
1332
  };
1471
1333
  const boundary = (async () => {
1472
1334
  try {
@@ -1475,9 +1337,8 @@ function createMattermostDraftStream(params) {
1475
1337
  await inFlightAtBoundary;
1476
1338
  assertNoAcceptedDeliveryFailure();
1477
1339
  if (streamState.stopped && !streamState.final) return;
1478
- const sourceText = pendingText.trim() ? pendingText : sealed.latestSourceText;
1479
- const finalizedText = (params.renderText?.(sourceText) ?? sourceText).trim();
1480
- const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, maxChars, "length");
1340
+ const finalizedText = (pendingText.trim() ? pendingText : sealed.latestSourceText).trim();
1341
+ const chunks = params.chunkText?.(finalizedText) ?? chunkMarkdownTextWithMode(finalizedText, MATTERMOST_STREAM_MAX_CHARS, "length");
1481
1342
  const firstChunk = chunks[0];
1482
1343
  if (!firstChunk) return;
1483
1344
  if (sealed.postId) {
@@ -1625,7 +1486,7 @@ function createMattermostDraftStream(params) {
1625
1486
  });
1626
1487
  return messages.find((post) => !post.type?.startsWith("system_") && (!params.rootId || post.root_id === params.rootId))?.id;
1627
1488
  };
1628
- params.log?.(`mattermost stream preview ready (maxChars=${maxChars}, throttleMs=${throttleMs})`);
1489
+ params.log?.(`mattermost stream preview ready (maxChars=${MATTERMOST_STREAM_MAX_CHARS}, throttleMs=${THROTTLE_MS})`);
1629
1490
  return {
1630
1491
  update,
1631
1492
  updateAssistantText,
@@ -1644,17 +1505,6 @@ function createMattermostDraftStream(params) {
1644
1505
  }
1645
1506
  //#endregion
1646
1507
  //#region extensions/mattermost/src/mattermost/monitor-draft-delivery.ts
1647
- function combineMattermostVisibleDeliveryResults(results, outcome) {
1648
- const visibleResults = results.filter((result) => result?.visibleReplySent === true);
1649
- if (visibleResults.length === 0) return;
1650
- return {
1651
- outcome,
1652
- ...createAcceptedChannelDeliveryResult({
1653
- deliveryResults: visibleResults,
1654
- content: joinMattermostVisibleContent(visibleResults.map((result) => result.content))
1655
- })
1656
- };
1657
- }
1658
1508
  async function deliverMattermostReplyWithDraftPreview(params) {
1659
1509
  if (isReasoningReplyPayload(params.payload)) return {
1660
1510
  outcome: "reasoning_skipped",
@@ -1678,7 +1528,7 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1678
1528
  });
1679
1529
  }
1680
1530
  try {
1681
- return combineMattermostVisibleDeliveryResults([confirmedPreviewDelivery, (await params.previewLifecycle.deliver({
1531
+ const visibleResults = [confirmedPreviewDelivery, (await params.previewLifecycle.deliver({
1682
1532
  kind: params.info.kind,
1683
1533
  payload: params.payload,
1684
1534
  isError: params.payload.isError,
@@ -1732,7 +1582,7 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1732
1582
  const deliveryPayload = payload.isError !== true && supplement && (previewFinalTextAlreadyDelivered || !payloadText && supplement.visibleTextAlreadyDelivered === true) ? buildTtsSupplementMediaPayload(payload) : payload.isError !== true && supplement && !payloadText ? {
1733
1583
  ...payload,
1734
1584
  text: resolvedDeliveryText?.trim() ? resolvedDeliveryText : supplement.spokenText
1735
- } : payload.isError !== true && typeof resolvedDeliveryText === "string" ? {
1585
+ } : payload.isError !== true && resolvedDeliveryText !== void 0 ? {
1736
1586
  ...payload,
1737
1587
  text: resolvedDeliveryText
1738
1588
  } : payload;
@@ -1741,11 +1591,19 @@ async function deliverMattermostReplyWithDraftPreview(params) {
1741
1591
  return delivered;
1742
1592
  },
1743
1593
  onNormalDelivered: params.recordThreadParticipation
1744
- })).deliveryResult], outcome) ?? {
1594
+ })).deliveryResult].filter((result) => result?.visibleReplySent === true);
1595
+ if (visibleResults.length === 0) return {
1745
1596
  outcome: "empty",
1746
1597
  visibleReplySent: false,
1747
1598
  suppression: { reason: "no_visible_result" }
1748
1599
  };
1600
+ return {
1601
+ outcome,
1602
+ ...createAcceptedChannelDeliveryResult({
1603
+ deliveryResults: visibleResults,
1604
+ content: joinMattermostVisibleContent(visibleResults.map((result) => result.content))
1605
+ })
1606
+ };
1749
1607
  } catch (error) {
1750
1608
  if (!confirmedPreviewDelivery?.visibleReplySent) throw error;
1751
1609
  const failedPartial = isChannelPartialDeliveryError(error) ? error.deliveryResult : void 0;
@@ -1772,12 +1630,9 @@ const threadParticipation = createPersistentDedupeCache({
1772
1630
  function makeKey(accountId, channelId, threadRootId) {
1773
1631
  return `${accountId}:${channelId}:${threadRootId}`;
1774
1632
  }
1775
- async function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
1633
+ async function recordMattermostThreadParticipation(accountId, channelId, threadRootId) {
1776
1634
  if (!accountId || !channelId || !threadRootId) return;
1777
- await threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
1778
- ...opts?.agentId ? { agentId: opts.agentId } : {},
1779
- repliedAt: Date.now()
1780
- });
1635
+ await threadParticipation.register(makeKey(accountId, channelId, threadRootId), { repliedAt: Date.now() });
1781
1636
  }
1782
1637
  async function hasMattermostThreadParticipationWithPersistence(params) {
1783
1638
  if (!params.accountId || !params.channelId || !params.threadRootId) return false;
@@ -1787,7 +1642,7 @@ async function hasMattermostThreadParticipationWithPersistence(params) {
1787
1642
  //#region extensions/mattermost/src/mattermost/monitor-turn.ts
1788
1643
  async function dispatchMattermostInboundTurn(monitor, params) {
1789
1644
  const { account, cfg, client, core, runtime } = monitor;
1790
- const { channelHistories, ctxPayload, eventPlan, historyKey, historyLimit, pinnedMainDmOwner, post, rawText, turnAdoptionLifecycle } = params;
1645
+ const { botLoopProtection, channelHistories, ctxPayload, eventPlan, historyKey, historyLimit, pinnedMainDmOwner, post, rawText, turnAdoptionLifecycle } = params;
1791
1646
  const { channelId, kind, route, senderId, thread, to } = eventPlan;
1792
1647
  const { effectiveReplyToId } = thread;
1793
1648
  const { replyOptions, replyPipeline: baseReplyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
@@ -1806,7 +1661,6 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1806
1661
  client,
1807
1662
  channelId,
1808
1663
  rootId: effectiveReplyToId,
1809
- throttleMs: 1200,
1810
1664
  chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(core.channel.text.convertMarkdownTables(value, tableMode), textLimit, chunkMode),
1811
1665
  log: monitor.logVerboseMessage,
1812
1666
  warn: monitor.logVerboseMessage
@@ -1860,7 +1714,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1860
1714
  onCleanupFailure: (err) => monitor.logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`)
1861
1715
  });
1862
1716
  const resolvePreviewFinalText = (text) => {
1863
- const finalText = typeof text === "string" ? text : "";
1717
+ const finalText = text ?? "";
1864
1718
  const resolution = draftStream?.resolveFinalText(finalText) ?? {
1865
1719
  kind: "full",
1866
1720
  text: finalText,
@@ -1939,7 +1793,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1939
1793
  const markThreadParticipation = async () => {
1940
1794
  if (!threadParticipationRecorded && kind !== "direct" && effectiveReplyToId) {
1941
1795
  threadParticipationRecorded = true;
1942
- await recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
1796
+ await recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId);
1943
1797
  }
1944
1798
  };
1945
1799
  const result = await deliverMattermostReplyWithDraftPreview({
@@ -1954,7 +1808,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
1954
1808
  recordThreadParticipation: markThreadParticipation,
1955
1809
  findPostAfterPreview: draftStream?.findPostAfter,
1956
1810
  deliverPayload: async (payloadToDeliver) => {
1957
- const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && typeof payloadToDeliver.text === "string" ? draftStream?.resolveFinalText(payloadToDeliver.text) : void 0;
1811
+ const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && payloadToDeliver.text !== void 0 ? draftStream?.resolveFinalText(payloadToDeliver.text) : void 0;
1958
1812
  const resolvedPayload = finalTextResolution ? {
1959
1813
  ...payloadToDeliver,
1960
1814
  text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
@@ -2005,6 +1859,9 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2005
1859
  channel: "mattermost",
2006
1860
  accountId: route.accountId,
2007
1861
  raw: post,
1862
+ log: (event) => {
1863
+ if (event.reason === "bot-loop-protection") runtime.log?.(`mattermost: drop bot post (bot-loop-protection channel=${channelId} sender=${senderId})`);
1864
+ },
2008
1865
  adapter: {
2009
1866
  ingest: () => ({
2010
1867
  id: post.id ?? `${to}:${Date.now()}`,
@@ -2024,6 +1881,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2024
1881
  sessionKey: route.sessionKey
2025
1882
  },
2026
1883
  ctxPayload,
1884
+ botLoopProtection,
2027
1885
  record: {
2028
1886
  updateLastRoute: kind === "direct" ? {
2029
1887
  sessionKey: inboundLastRouteSessionKey,
@@ -2168,8 +2026,16 @@ function createMattermostPostHandler(monitor) {
2168
2026
  });
2169
2027
  if (!eventPlan) return;
2170
2028
  const { channelDisplay, kind, roomLabel, route, thread } = eventPlan;
2029
+ const isBotPost = post.props?.from_bot === "true";
2030
+ const channelBotConfig = kind === "direct" ? void 0 : account.config.groups?.[channelId];
2031
+ const wildcardBotConfig = kind === "direct" ? void 0 : account.config.groups?.["*"];
2032
+ const allowBots = channelBotConfig?.allowBots ?? wildcardBotConfig?.allowBots ?? account.config.allowBots ?? true;
2033
+ if (isBotPost && allowBots === false) {
2034
+ monitor.logVerboseMessage(`mattermost: drop bot post (allowBots=false sender=${senderId})`);
2035
+ return;
2036
+ }
2171
2037
  const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
2172
- const rawPostText = typeof post.message === "string" ? post.message : "";
2038
+ const rawPostText = post.message ?? "";
2173
2039
  const rawText = normalizeOptionalString(rawPostText) ?? "";
2174
2040
  const commandBody = normalizeMention(rawText, botUsername).trim();
2175
2041
  const { effectiveReplyToId, sessionKey } = thread;
@@ -2178,11 +2044,7 @@ function createMattermostPostHandler(monitor) {
2178
2044
  agentId: route.agentId,
2179
2045
  sessionKey
2180
2046
  });
2181
- const historyKey = resolveMattermostPendingHistoryKey({
2182
- kind,
2183
- sessionKey,
2184
- threadRootId: effectiveReplyToId
2185
- });
2047
+ const historyKey = kind === "direct" && !effectiveReplyToId ? null : sessionKey;
2186
2048
  const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2187
2049
  const nativeMedia = fileIds.map(() => ({}));
2188
2050
  const pendingBody = formatMattermostPendingMediaText({
@@ -2197,7 +2059,7 @@ function createMattermostPostHandler(monitor) {
2197
2059
  entry: historyKey && trimmed ? {
2198
2060
  sender: senderName,
2199
2061
  body: trimmed,
2200
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2062
+ timestamp: post.create_at ?? void 0,
2201
2063
  messageId: post.id
2202
2064
  } : null
2203
2065
  });
@@ -2324,17 +2186,25 @@ function createMattermostPostHandler(monitor) {
2324
2186
  implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged)
2325
2187
  });
2326
2188
  const botThreadMentionRequired = isBotOwnedThread && requireMentionInBotThreads === true;
2327
- const mentionDecision = resolveMattermostInboundMentionDecision({
2189
+ const implicitMentions = resolveChannelImplicitMentions({
2328
2190
  cfg,
2329
- accountId: account.accountId,
2330
- kind,
2331
- requireMention: botThreadPolicy.requireMention,
2332
- canDetectMention: canDetectMention || oncharEnabled || botThreadMentionRequired,
2333
- wasMentioned: wasMentioned || oncharTriggered,
2334
- implicitMentionKinds: botThreadPolicy.implicitMentionKinds,
2335
- allowTextCommands,
2336
- hasControlCommand: isControlCommand,
2337
- commandAuthorized
2191
+ channel: "mattermost",
2192
+ accountId: account.accountId
2193
+ });
2194
+ const mentionDecision = resolveInboundMentionDecision({
2195
+ facts: {
2196
+ canDetectMention: canDetectMention || oncharEnabled || botThreadMentionRequired,
2197
+ wasMentioned: wasMentioned || oncharTriggered,
2198
+ implicitMentionKinds: botThreadPolicy.implicitMentionKinds
2199
+ },
2200
+ policy: {
2201
+ isGroup: kind !== "direct",
2202
+ requireMention: botThreadPolicy.requireMention,
2203
+ implicitMentions,
2204
+ allowTextCommands,
2205
+ hasControlCommand: isControlCommand,
2206
+ commandAuthorized
2207
+ }
2338
2208
  });
2339
2209
  const { shouldBypassMention } = mentionDecision;
2340
2210
  if (mentionDecision.shouldSkip && oncharEnabled && !oncharTriggered && !wasMentioned && !shouldBypassMention) {
@@ -2354,6 +2224,11 @@ function createMattermostPostHandler(monitor) {
2354
2224
  recordPendingHistory();
2355
2225
  return;
2356
2226
  }
2227
+ if (isBotPost && allowBots === "mentions" && kind !== "direct" && !wasMentioned && !oncharTriggered) {
2228
+ monitor.logVerboseMessage(`mattermost: drop bot post (allowBots=mentions, missing mention channel=${channelId} sender=${senderId})`);
2229
+ recordPendingHistory();
2230
+ return;
2231
+ }
2357
2232
  const mediaList = await resolveMattermostMedia(fileIds);
2358
2233
  const bodyText = normalizeMention(formatMattermostInboundMediaText({
2359
2234
  body: oncharTriggered ? oncharResult.stripped : rawText,
@@ -2386,7 +2261,7 @@ function createMattermostPostHandler(monitor) {
2386
2261
  const body = formatInboundEnvelope({
2387
2262
  channel: "Mattermost",
2388
2263
  from: fromLabel,
2389
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2264
+ timestamp: post.create_at ?? void 0,
2390
2265
  body: textWithId,
2391
2266
  chatType: kind,
2392
2267
  sender: {
@@ -2439,7 +2314,7 @@ function createMattermostPostHandler(monitor) {
2439
2314
  MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2440
2315
  MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2441
2316
  MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2442
- Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2317
+ Timestamp: post.create_at ?? void 0,
2443
2318
  WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2444
2319
  CommandAuthorized: commandAuthorized,
2445
2320
  CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
@@ -2451,6 +2326,17 @@ function createMattermostPostHandler(monitor) {
2451
2326
  normalizeEntry: normalizeMattermostAllowEntry
2452
2327
  }) : null;
2453
2328
  monitor.logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} id=${post.id} len=${bodyText.length}`);
2329
+ const botLoopProtection = isBotPost ? {
2330
+ scopeId: account.accountId,
2331
+ conversationId: channelId,
2332
+ senderId,
2333
+ receiverId: botUserId,
2334
+ eventId: post.id,
2335
+ config: mergePairLoopGuardConfig(account.config.botLoopProtection, wildcardBotConfig?.botLoopProtection, channelBotConfig?.botLoopProtection),
2336
+ defaultsConfig: cfg.channels?.defaults?.botLoopProtection,
2337
+ defaultEnabled: true,
2338
+ nowMs: post.create_at ?? void 0
2339
+ } : void 0;
2454
2340
  await dispatchMattermostInboundTurn(monitor, {
2455
2341
  post,
2456
2342
  rawText,
@@ -2460,6 +2346,7 @@ function createMattermostPostHandler(monitor) {
2460
2346
  historyLimit,
2461
2347
  channelHistories,
2462
2348
  pinnedMainDmOwner,
2349
+ botLoopProtection,
2463
2350
  turnAdoptionLifecycle
2464
2351
  });
2465
2352
  };
@@ -2485,7 +2372,7 @@ function createMattermostReactionHandler(monitor) {
2485
2372
  if (!userId || !postId || !emojiName || userId === botUserId) return;
2486
2373
  const action = payload.event === "reaction_removed" ? "removed" : "added";
2487
2374
  const senderName = normalizeOptionalString((await resolveUserInfo(userId))?.username) ?? userId;
2488
- const channelId = resolveMattermostReactionChannelId(payload);
2375
+ const channelId = normalizeOptionalString(payload.broadcast?.channel_id) ?? normalizeOptionalString(payload.data?.channel_id);
2489
2376
  if (!channelId) {
2490
2377
  monitor.logVerboseMessage("mattermost: drop reaction (no channel_id in broadcast, cannot enforce policy)");
2491
2378
  return;
@@ -2530,49 +2417,6 @@ function createMattermostReactionHandler(monitor) {
2530
2417
  }
2531
2418
  //#endregion
2532
2419
  //#region extensions/mattermost/src/mattermost/monitor-slash.ts
2533
- async function buildSlashCommands(params) {
2534
- const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
2535
- if (!params.nativeSkills) return commandsToRegister;
2536
- try {
2537
- const skillCommands = await prepareSkillCommandsForAgents({ cfg: params.cfg });
2538
- for (const spec of skillCommands) {
2539
- const name = typeof spec.name === "string" ? spec.name.trim() : "";
2540
- if (!name) continue;
2541
- const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
2542
- commandsToRegister.push({
2543
- trigger,
2544
- description: spec.description || `Run skill ${name}`,
2545
- autoComplete: true,
2546
- autoCompleteHint: "[args]",
2547
- originalName: name
2548
- });
2549
- }
2550
- } catch (err) {
2551
- params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
2552
- }
2553
- return commandsToRegister;
2554
- }
2555
- function dedupeSlashCommands(commands) {
2556
- const seen = /* @__PURE__ */ new Set();
2557
- return commands.filter((cmd) => {
2558
- const key = cmd.trigger.trim();
2559
- if (!key || seen.has(key)) return false;
2560
- seen.add(key);
2561
- return true;
2562
- });
2563
- }
2564
- function buildTriggerMap(commands) {
2565
- const triggerMap = /* @__PURE__ */ new Map();
2566
- for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
2567
- return triggerMap;
2568
- }
2569
- function warnOnSuspiciousCallbackUrl(params) {
2570
- try {
2571
- const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
2572
- const callbackHost = new URL(params.callbackUrl).hostname;
2573
- 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).`);
2574
- } catch {}
2575
- }
2576
2420
  async function registerMattermostMonitorSlashCommands(params) {
2577
2421
  const commandsRaw = params.account.config.commands;
2578
2422
  const slashConfig = resolveSlashCommandConfig(commandsRaw);
@@ -2582,18 +2426,40 @@ async function registerMattermostMonitorSlashCommands(params) {
2582
2426
  const slashCallbackUrl = resolveCallbackUrl({
2583
2427
  config: slashConfig,
2584
2428
  gatewayPort: (0, gateway_config_runtime_exports.resolveGatewayPort)(params.cfg),
2585
- gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
2429
+ gatewayHost: params.cfg.gateway?.customBindHost
2586
2430
  });
2587
- warnOnSuspiciousCallbackUrl({
2588
- runtime: params.runtime,
2589
- baseUrl: params.baseUrl,
2590
- callbackUrl: slashCallbackUrl
2431
+ try {
2432
+ const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
2433
+ const callbackHost = new URL(slashCallbackUrl).hostname;
2434
+ 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).`);
2435
+ } catch {}
2436
+ const cfg = params.cfg;
2437
+ const runtime = params.runtime;
2438
+ const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
2439
+ if (slashConfig.nativeSkills === true) try {
2440
+ const skillCommands = await prepareSkillCommandsForAgents({ cfg });
2441
+ for (const spec of skillCommands) {
2442
+ const name = spec.name.trim();
2443
+ if (!name) continue;
2444
+ const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
2445
+ commandsToRegister.push({
2446
+ trigger,
2447
+ description: spec.description || `Run skill ${name}`,
2448
+ autoComplete: true,
2449
+ autoCompleteHint: "[args]",
2450
+ originalName: name
2451
+ });
2452
+ }
2453
+ } catch (err) {
2454
+ runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
2455
+ }
2456
+ const seen = /* @__PURE__ */ new Set();
2457
+ const dedupedCommands = commandsToRegister.filter((cmd) => {
2458
+ const key = cmd.trigger.trim();
2459
+ if (!key || seen.has(key)) return false;
2460
+ seen.add(key);
2461
+ return true;
2591
2462
  });
2592
- const dedupedCommands = dedupeSlashCommands(await buildSlashCommands({
2593
- cfg: params.cfg,
2594
- runtime: params.runtime,
2595
- nativeSkills: slashConfig.nativeSkills === true
2596
- }));
2597
2463
  const registered = [];
2598
2464
  let teamRegistrationFailures = 0;
2599
2465
  for (const team of teams) try {
@@ -2615,11 +2481,12 @@ async function registerMattermostMonitorSlashCommands(params) {
2615
2481
  return;
2616
2482
  }
2617
2483
  if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
2484
+ const triggerMap = /* @__PURE__ */ new Map();
2485
+ for (const cmd of dedupedCommands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
2618
2486
  activateSlashCommands({
2619
2487
  account: params.account,
2620
- commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
2621
2488
  registeredCommands: registered,
2622
- triggerMap: buildTriggerMap(dedupedCommands),
2489
+ triggerMap,
2623
2490
  api: {
2624
2491
  cfg: params.cfg,
2625
2492
  runtime: params.runtime
@@ -2634,10 +2501,7 @@ async function registerMattermostMonitorSlashCommands(params) {
2634
2501
  //#endregion
2635
2502
  //#region extensions/mattermost/src/mattermost/reconnect.ts
2636
2503
  async function runWithReconnect(connectFn, opts = {}) {
2637
- const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
2638
- const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
2639
- const random = opts.random ?? Math.random;
2640
- let retryDelay = initialDelayMs;
2504
+ let retryDelay = 2e3;
2641
2505
  while (!opts.abortSignal?.aborted) {
2642
2506
  let failed = false;
2643
2507
  try {
@@ -2648,8 +2512,9 @@ async function runWithReconnect(connectFn, opts = {}) {
2648
2512
  opts.onError?.(err);
2649
2513
  }
2650
2514
  if (opts.abortSignal?.aborted) return;
2651
- if (!failed) retryDelay = initialDelayMs;
2652
- const delayMs = withJitter(retryDelay, jitterRatio, random);
2515
+ if (!failed) retryDelay = 2e3;
2516
+ const spread = retryDelay * .2;
2517
+ const delayMs = Math.round(retryDelay - spread + Math.random() * spread * 2);
2653
2518
  if (!failed && opts.reconnectAfterClose === false) return;
2654
2519
  opts.onReconnect?.(delayMs);
2655
2520
  try {
@@ -2657,15 +2522,9 @@ async function runWithReconnect(connectFn, opts = {}) {
2657
2522
  } catch (delayError) {
2658
2523
  if (!opts.abortSignal?.aborted) throw delayError;
2659
2524
  }
2660
- if (failed) retryDelay = Math.min(retryDelay * 2, maxDelayMs);
2525
+ if (failed) retryDelay = Math.min(retryDelay * 2, 6e4);
2661
2526
  }
2662
2527
  }
2663
- function withJitter(baseMs, jitterRatio, random) {
2664
- if (jitterRatio <= 0) return baseMs;
2665
- const normalized = Math.max(0, Math.min(1, random()));
2666
- const spread = baseMs * jitterRatio;
2667
- return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
2668
- }
2669
2528
  //#endregion
2670
2529
  //#region extensions/mattermost/src/mattermost/monitor.ts
2671
2530
  function publishMattermostRecoveringStatus(statusSink, error) {
@@ -2699,21 +2558,12 @@ async function monitorMattermostProvider(opts = {}) {
2699
2558
  channel: "mattermost",
2700
2559
  accountId: account.accountId
2701
2560
  });
2702
- const botToken = normalizeOptionalString(opts.botToken) ?? normalizeOptionalString(account.botToken);
2703
- 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).`);
2704
- const baseUrl = normalizeMattermostBaseUrl(opts.baseUrl ?? account.baseUrl);
2705
- if (!baseUrl) throw new Error(`Mattermost baseUrl missing for account "${account.accountId}" (set channels.mattermost.accounts.${account.accountId}.baseUrl or MATTERMOST_URL for default).`);
2706
- const client = createMattermostClient({
2707
- baseUrl,
2708
- botToken,
2709
- allowPrivateNetwork: account.config.network?.dangerouslyAllowPrivateNetwork === true
2710
- });
2561
+ const { client, baseUrl, botToken } = createMattermostAccountClient(account, opts);
2711
2562
  let botUser;
2712
2563
  await runWithReconnect(async () => {
2713
2564
  botUser = await fetchMattermostMe(client);
2714
2565
  }, {
2715
2566
  abortSignal: opts.abortSignal,
2716
- jitterRatio: .2,
2717
2567
  reconnectAfterClose: false,
2718
2568
  onError: (err) => {
2719
2569
  runtime.error?.(`mattermost: API auth failed: ${String(err)}`);
@@ -2806,44 +2656,63 @@ async function monitorMattermostProvider(opts = {}) {
2806
2656
  const slashEnabled = getSlashCommandState(account.accountId) != null;
2807
2657
  const handlePost = createMattermostPostHandler(monitor);
2808
2658
  const handleReactionEvent = createMattermostReactionHandler(monitor);
2659
+ const pendingPosts = /* @__PURE__ */ new Set();
2660
+ const cancellationSettlements = [];
2661
+ const shutdown = new AbortController();
2662
+ const buildDebounceKey = (entry) => {
2663
+ const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2664
+ return channelId && entry.post.user_id ? `mattermost:${account.accountId}:${channelId}` : null;
2665
+ };
2809
2666
  const debouncer = core.channel.debounce.createInboundDebouncer({
2810
2667
  debounceMs: resolveDebounceMs(),
2811
2668
  resolveDebounceMs,
2812
- buildKey: (entry) => {
2813
- const channelId = entry.post.channel_id ?? entry.payload.data?.channel_id ?? entry.payload.broadcast?.channel_id;
2814
- if (!channelId || !entry.post.user_id) return null;
2815
- const threadId = normalizeOptionalString(entry.post.root_id);
2816
- return `mattermost:${account.accountId}:${channelId}:${threadId ? `thread:${threadId}` : "channel"}:${entry.post.user_id}`;
2669
+ buildKey: buildDebounceKey,
2670
+ canAppend: (entry, pending) => {
2671
+ const last = pending.at(-1);
2672
+ return last?.post.user_id === entry.post.user_id && normalizeOptionalString(last.post.root_id) === normalizeOptionalString(entry.post.root_id);
2817
2673
  },
2674
+ serializeImmediate: true,
2818
2675
  shouldDebounce: (entry) => {
2819
2676
  if (normalizeOptionalString(entry.post.type) !== void 0 || entry.post.file_ids?.length) return false;
2820
2677
  const text = normalizeOptionalString(entry.post.message) ?? "";
2821
2678
  return Boolean(text) && !core.channel.commands.isControlCommandMessage(normalizeMention(text, botUsername), cfg);
2822
2679
  },
2823
2680
  onFlush: (entries, createFlush) => {
2681
+ for (const entry of entries) pendingPosts.delete(entry);
2824
2682
  const last = entries.at(-1);
2825
- const { lifecycle, settle } = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle));
2683
+ const { lifecycle, settle, cancel } = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle));
2826
2684
  return createFlush({
2827
2685
  lifecycle,
2828
2686
  dispatch: async (admissionLifecycle) => {
2687
+ if (shutdown.signal.aborted || admissionLifecycle.abortSignal.aborted) {
2688
+ await cancel();
2689
+ return;
2690
+ }
2829
2691
  if (!last) return;
2830
- try {
2831
- const mergedPost = entries.length === 1 ? last.post : {
2692
+ if (entries.length === 1) await handlePost(last.post, last.payload, admissionLifecycle);
2693
+ else {
2694
+ const mergedPost = {
2832
2695
  ...last.post,
2833
2696
  message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
2834
2697
  file_ids: []
2835
2698
  };
2836
2699
  await handlePost(mergedPost, last.payload, admissionLifecycle, entries.length > 1 ? entries.map((entry) => entry.post.id) : void 0);
2837
- await settle();
2838
- } catch (error) {
2839
- await admissionLifecycle.onAbandoned();
2840
- throw error;
2841
2700
  }
2701
+ if (shutdown.signal.aborted || admissionLifecycle.abortSignal.aborted) await cancel();
2702
+ else await settle();
2842
2703
  }
2843
2704
  });
2844
2705
  },
2845
2706
  onError: (err) => {
2846
2707
  runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
2708
+ },
2709
+ onCancel: (entries) => {
2710
+ for (const entry of entries) pendingPosts.delete(entry);
2711
+ const settlement = fanInChannelIngressLifecycles(entries.map((entry) => entry.turnAdoptionLifecycle)).cancel();
2712
+ cancellationSettlements.push(settlement);
2713
+ settlement.catch((error) => {
2714
+ runtime.error?.(`mattermost ingress cancellation failed: ${String(error)}`);
2715
+ });
2847
2716
  }
2848
2717
  });
2849
2718
  const ingress = createMattermostIngressMonitor({
@@ -2851,11 +2720,22 @@ async function monitorMattermostProvider(opts = {}) {
2851
2720
  runtime,
2852
2721
  abortSignal: opts.abortSignal,
2853
2722
  dispatch: async (post, payload, turnAdoptionLifecycle) => {
2854
- await debouncer.enqueue({
2723
+ if (shutdown.signal.aborted || turnAdoptionLifecycle.abortSignal.aborted) {
2724
+ await fanInChannelIngressLifecycles([turnAdoptionLifecycle]).cancel();
2725
+ return { kind: "deferred" };
2726
+ }
2727
+ const entry = {
2855
2728
  post,
2856
2729
  payload,
2857
2730
  turnAdoptionLifecycle
2858
- });
2731
+ };
2732
+ pendingPosts.add(entry);
2733
+ try {
2734
+ await debouncer.enqueue(entry);
2735
+ } catch (error) {
2736
+ pendingPosts.delete(entry);
2737
+ throw error;
2738
+ }
2859
2739
  return { kind: "deferred" };
2860
2740
  }
2861
2741
  });
@@ -2866,7 +2746,6 @@ async function monitorMattermostProvider(opts = {}) {
2866
2746
  abortSignal: opts.abortSignal,
2867
2747
  statusSink: opts.statusSink,
2868
2748
  runtime,
2869
- webSocketFactory: opts.webSocketFactory,
2870
2749
  nextSeq: () => sequence++,
2871
2750
  getBotUpdateAt: async () => (await fetchMattermostMe(client)).update_at ?? 0,
2872
2751
  onPosted: ingress.receive,
@@ -2889,10 +2768,11 @@ async function monitorMattermostProvider(opts = {}) {
2889
2768
  if (opts.abortSignal?.aborted) runAbortCleanup();
2890
2769
  else opts.abortSignal?.addEventListener("abort", runAbortCleanup, { once: true });
2891
2770
  }
2771
+ let connectionFailure;
2772
+ let shutdownFailures = [];
2892
2773
  try {
2893
2774
  await runWithReconnect(connectOnce, {
2894
2775
  abortSignal: opts.abortSignal,
2895
- jitterRatio: .2,
2896
2776
  onError: (err) => {
2897
2777
  runtime.error?.(`mattermost connection failed: ${String(err)}`);
2898
2778
  publishMattermostRecoveringStatus(opts.statusSink, err);
@@ -2901,11 +2781,23 @@ async function monitorMattermostProvider(opts = {}) {
2901
2781
  runtime.log?.(`mattermost reconnecting in ${Math.round(delayMs / 1e3)}s`);
2902
2782
  }
2903
2783
  });
2784
+ } catch (error) {
2785
+ connectionFailure = { error };
2904
2786
  } finally {
2905
- await ingress.stop();
2906
- unregisterInteractions();
2787
+ shutdown.abort();
2788
+ const pendingKeys = new Set([...pendingPosts].map(buildDebounceKey));
2789
+ for (const key of pendingKeys) if (key) debouncer.cancelKey(key);
2790
+ try {
2791
+ const stopped = await Promise.allSettled([ingress.stop(), debouncer.drain()]);
2792
+ const cancelled = await Promise.allSettled(cancellationSettlements);
2793
+ shutdownFailures = [...stopped, ...cancelled].flatMap((result) => result.status === "rejected" ? [result.reason] : []);
2794
+ } finally {
2795
+ unregisterInteractions();
2796
+ }
2907
2797
  }
2908
2798
  await Promise.resolve(slashShutdownCleanup);
2799
+ if (shutdownFailures.length > 0) throw new AggregateError(shutdownFailures, "Mattermost monitor shutdown failed.", { cause: connectionFailure?.error });
2800
+ if (connectionFailure) throw connectionFailure.error;
2909
2801
  }
2910
2802
  //#endregion
2911
2803
  export { monitorMattermostProvider };