@openclaw/mattermost 2026.9.6 → 2026.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,183 +1,44 @@
1
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl, u as gateway_config_runtime_exports } from "./interactions-DMSZYnEx.mjs";
1
2
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.mjs";
2
- import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-rBQWCbK8.mjs";
3
- import { _ as readMattermostError, 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-BSSVve1x.mjs";
4
- import { C as resolveAllowlistProviderRuntimeGroupPolicy$1, E as resolveDefaultGroupPolicy, O as warnMissingProviderGroupPolicyFallbackOnce, S as registerPluginHttpRoute, _ as listSkillCommandsForAgents, a as resolveMattermostMonitorInboundAccess, b as logTypingFailure, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, l as buildPreparedModelsProviderData, m as isDangerousNameMatchingEnabled, n as formatMattermostDirectMessageDropLog, o as resolveMattermostTrustedChatKind, s as shouldRetainMattermostSenderHistory, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, w as resolveChannelMediaMaxBytes, y as logInboundDrop } from "./monitor-auth-CCpN0z_f.mjs";
3
+ import { a as createMattermostPost, d as fetchMattermostUser, h as normalizeMattermostBaseUrl, 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-CVeeTqCO.mjs";
4
+ import { C as resolveAllowlistProviderRuntimeGroupPolicy, E as resolveDefaultGroupPolicy, O as warnMissingProviderGroupPolicyFallbackOnce, S as registerPluginHttpRoute, _ as listSkillCommandsForAgents, a as resolveMattermostMonitorInboundAccess, b as logTypingFailure, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, l as buildPreparedModelsProviderData, m as isDangerousNameMatchingEnabled, n as formatMattermostDirectMessageDropLog, o as resolveMattermostTrustedChatKind, s as shouldRetainMattermostSenderHistory, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, w as resolveChannelMediaMaxBytes, y as logInboundDrop } from "./monitor-auth-aZ0b1gqx.mjs";
5
5
  import { n as normalizeMattermostAllowEntry } from "./ingress-identity-DNl4yQSc.mjs";
6
- import { c as listMattermostAccountIds, d as resolveMattermostReplyToMode, n as normalizeMattermostMessagingTarget, o as inspectMattermostAccount, r as parseMattermostQuestionContext, u as resolveMattermostAccount } from "./normalize-DM54w7ud.mjs";
7
- import { _ as registerSlashCommands, a as sendMessageMattermost, c as joinMattermostVisibleContent, d as renderMattermostModelsPickerView, f as renderMattermostProviderPickerView, g as isSlashCommandsEnabled, h as cleanupSlashCommands, l as buildMattermostAllowedModelRefs, m as DEFAULT_COMMAND_SPECS, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as resolveMattermostModelPickerCurrentModel, r as getSlashCommandState, s as deliverMattermostReplyPayload, t as activateSlashCommands, u as parseMattermostModelPickerContext, v as resolveCallbackUrl, y as resolveSlashCommandConfig } from "./slash-state-DfnmzXMr.mjs";
6
+ import { d as resolveMattermostReplyToMode, r as parseMattermostQuestionContext, u as resolveMattermostAccount } from "./normalize-BCjtmxtp.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-Dni1XNc1.mjs";
8
+ import { t as sendMessageMattermost } from "./send-ClgX-usq.mjs";
8
9
  import { randomUUID } from "node:crypto";
9
- import { resolveGatewayPort } from "openclaw/plugin-sdk/gateway-config-runtime";
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
12
  import { buildChannelInboundMediaPayload, createAcceptedChannelDeliveryResult, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContext, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
13
13
  import { formatErrorMessage, toErrorObject } from "openclaw/plugin-sdk/error-runtime";
14
14
  import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
15
- import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolvePromptHistoryLimit, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
16
- import { readProviderJsonResponse } from "openclaw/plugin-sdk/provider-http";
17
- import { fetchWithSsrFGuard, isPrivateNetworkOptInEnabled, ssrfPolicyFromPrivateNetworkOptIn } from "openclaw/plugin-sdk/ssrf-runtime";
15
+ import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolvePromptHistoryLimit } from "openclaw/plugin-sdk/number-runtime";
16
+ import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
18
17
  import { z } from "zod";
19
18
  import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createLivePreviewLifecycle, createMessageReceiptFromOutboundResults, createPreviewMessageReceipt, listMessageReceiptPlatformIds, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
20
- import { resolveAllowlistProviderRuntimeGroupPolicy } from "openclaw/plugin-sdk/runtime-group-policy";
21
19
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
22
20
  import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
23
21
  import { fanInChannelIngressLifecycles, resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
24
22
  import { resolveChannelGroups, resolveChannelGroupsConfigPath } from "openclaw/plugin-sdk/channel-policy";
25
23
  import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
26
- import { normalizeAccountId } from "openclaw/plugin-sdk/account-id";
27
24
  import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
28
- import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
29
- import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
30
- import { escapeRegExp, runChannelProbe, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
25
+ import { escapeRegExp, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
31
26
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
32
- import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
33
27
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
28
+ import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
29
+ import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
34
30
  import { channelReadyPatch, isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
35
31
  import { createRuntimeConfigReader } from "openclaw/plugin-sdk/runtime-config-snapshot";
36
- import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
32
+ import * as proxyCaptureSdk from "openclaw/plugin-sdk/proxy-capture";
33
+ import { createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
37
34
  import { WebSocket } from "openclaw/plugin-sdk/websocket-runtime";
38
35
  import { questionGatewayRuntime } from "openclaw/plugin-sdk/question-gateway-runtime";
36
+ import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
39
37
  import { getGlobalHookRunner } from "openclaw/plugin-sdk/plugin-runtime";
40
38
  import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
41
39
  import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
42
40
  import { createPluginStateErrorReporter } from "openclaw/plugin-sdk/plugin-state-runtime";
43
- //#region extensions/mattermost/src/mattermost/directory.ts
44
- function buildClient(params) {
45
- const account = inspectMattermostAccount({
46
- cfg: params.cfg,
47
- accountId: params.accountId
48
- });
49
- if (!account.enabled || !account.botToken || !account.baseUrl) return null;
50
- return createMattermostClient({
51
- baseUrl: account.baseUrl,
52
- botToken: account.botToken,
53
- allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
54
- });
55
- }
56
- /** Build the requested account client, or aggregate accounts for an explicitly unscoped lookup. */
57
- function buildClients(params) {
58
- const requestedAccountId = params.accountId?.trim();
59
- const accountIds = requestedAccountId ? [requestedAccountId] : listMattermostAccountIds(params.cfg);
60
- const seen = /* @__PURE__ */ new Set();
61
- const clients = [];
62
- for (const id of accountIds) {
63
- const client = buildClient({
64
- cfg: params.cfg,
65
- accountId: id
66
- });
67
- if (client && !seen.has(client.token)) {
68
- seen.add(client.token);
69
- clients.push(client);
70
- }
71
- }
72
- return clients;
73
- }
74
- /**
75
- * List channels (public + private) visible to any configured bot account.
76
- *
77
- * NOTE: Uses per_page=200 which covers most instances. Mattermost does not
78
- * return a "has more" indicator, so very large instances (200+ channels per bot)
79
- * may see incomplete results. Pagination can be added if needed.
80
- */
81
- async function listMattermostDirectoryGroups(params) {
82
- const clients = buildClients(params);
83
- if (!clients.length) return [];
84
- const q = normalizeLowercaseStringOrEmpty(params.query);
85
- const seenIds = /* @__PURE__ */ new Set();
86
- const entries = [];
87
- for (const client of clients) try {
88
- const me = await fetchMattermostMe(client);
89
- const channels = await client.request(`/users/${me.id}/channels?per_page=200`);
90
- for (const ch of channels) {
91
- if (ch.type !== "O" && ch.type !== "P") continue;
92
- if (seenIds.has(ch.id)) continue;
93
- if (q) {
94
- const name = normalizeLowercaseStringOrEmpty(ch.name);
95
- const display = normalizeLowercaseStringOrEmpty(ch.display_name);
96
- if (!name.includes(q) && !display.includes(q)) continue;
97
- }
98
- seenIds.add(ch.id);
99
- entries.push({
100
- kind: resolveMattermostTrustedChatKind({ channelType: ch.type }) === "group" ? "group" : "channel",
101
- id: `channel:${ch.id}`,
102
- name: ch.name ?? void 0,
103
- handle: ch.display_name ?? void 0
104
- });
105
- }
106
- } catch (err) {
107
- console.debug?.("[mattermost-directory] listGroups: skipping account:", err?.message);
108
- continue;
109
- }
110
- return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
111
- }
112
- /**
113
- * List team members as peer directory entries.
114
- *
115
- * Uses only the first available client since all bots in a team see the same
116
- * user list (unlike channels where membership varies). Uses the first team
117
- * returned — multi-team setups will only see members from that team.
118
- *
119
- * Uses paginated member listing with per_page=200, the Mattermost API maximum.
120
- */
121
- async function listMattermostDirectoryPeers(params) {
122
- const clients = buildClients(params);
123
- if (!clients.length) return [];
124
- const client = clients[0];
125
- if (!client) return [];
126
- try {
127
- const me = await fetchMattermostMe(client);
128
- const teams = await client.request("/users/me/teams");
129
- if (!teams.length) return [];
130
- const team = teams[0];
131
- if (!team) return [];
132
- const teamId = team.id;
133
- const q = normalizeLowercaseStringOrEmpty(params.query);
134
- let users;
135
- if (q) users = await client.request("/users/search", {
136
- method: "POST",
137
- body: JSON.stringify({
138
- term: q,
139
- team_id: teamId
140
- })
141
- });
142
- else {
143
- const pageSize = 200;
144
- const userIds = [];
145
- for (let page = 0;; page += 1) {
146
- const pageMembers = await client.request(`/teams/${teamId}/members?page=${page}&per_page=${pageSize}`);
147
- for (const member of pageMembers) if (member.user_id !== me.id) userIds.push(member.user_id);
148
- if (pageMembers.length < pageSize) break;
149
- }
150
- if (!userIds.length) return [];
151
- users = [];
152
- for (let index = 0; index < userIds.length; index += pageSize) {
153
- const userIdBatch = userIds.slice(index, index + pageSize);
154
- users.push(...await client.request("/users/ids", {
155
- method: "POST",
156
- body: JSON.stringify(userIdBatch)
157
- }));
158
- }
159
- }
160
- const entries = users.filter((u) => u.id !== me.id).map((u) => ({
161
- kind: "user",
162
- id: `user:${u.id}`,
163
- name: u.username ?? void 0,
164
- handle: [u.first_name, u.last_name].filter(Boolean).join(" ").trim() || u.nickname || void 0
165
- }));
166
- return params.limit && params.limit > 0 ? entries.slice(0, params.limit) : entries;
167
- } catch (err) {
168
- console.debug?.("[mattermost-directory] listPeers failed:", err?.message);
169
- return [];
170
- }
171
- }
172
- //#endregion
173
41
  //#region extensions/mattermost/src/mattermost/monitor-helpers.ts
174
- const formatInboundFromLabel$1 = formatInboundFromLabel;
175
- function resolveThreadSessionKeys$1(params) {
176
- return resolveThreadSessionKeys({
177
- ...params,
178
- normalizeThreadId: (threadId) => threadId
179
- });
180
- }
181
42
  function buildMattermostBotMentionPattern(username) {
182
43
  return `(?<![a-z0-9_])@${escapeRegExp(username)}(?![a-z0-9_]|[.:-]+[a-z0-9_])`;
183
44
  }
@@ -218,6 +79,7 @@ function shouldDropEmptyMattermostBody(params) {
218
79
  }
219
80
  //#endregion
220
81
  //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
82
+ const captureSdk = proxyCaptureSdk;
221
83
  const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16777216;
222
84
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
223
85
  const MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS = 3e4;
@@ -300,22 +162,14 @@ function createMattermostConnectOnce(opts) {
300
162
  let authenticationSeq;
301
163
  let authTimer;
302
164
  const clearTimers = () => {
303
- if (healthCheckTimer !== void 0) {
304
- clearTimeout(healthCheckTimer);
305
- healthCheckTimer = void 0;
306
- }
307
- if (authTimer !== void 0) {
308
- clearTimeout(authTimer);
309
- authTimer = void 0;
310
- }
311
- if (protocolPingTimer !== void 0) {
312
- clearTimeout(protocolPingTimer);
313
- protocolPingTimer = void 0;
314
- }
315
- if (protocolPongTimer !== void 0) {
316
- clearTimeout(protocolPongTimer);
317
- protocolPongTimer = void 0;
318
- }
165
+ clearTimeout(healthCheckTimer);
166
+ healthCheckTimer = void 0;
167
+ clearTimeout(authTimer);
168
+ authTimer = void 0;
169
+ clearTimeout(protocolPingTimer);
170
+ protocolPingTimer = void 0;
171
+ clearTimeout(protocolPongTimer);
172
+ protocolPongTimer = void 0;
319
173
  };
320
174
  const stopHealthChecks = () => {
321
175
  healthCheckEnabled = false;
@@ -324,7 +178,7 @@ function createMattermostConnectOnce(opts) {
324
178
  };
325
179
  const sendProtocolPing = () => {
326
180
  if (!protocolKeepaliveEnabled || settled) return;
327
- if (protocolPongTimer !== void 0) clearTimeout(protocolPongTimer);
181
+ clearTimeout(protocolPongTimer);
328
182
  protocolPongTimer = setTimeout(() => {
329
183
  protocolPongTimer = void 0;
330
184
  if (!protocolKeepaliveEnabled || settled) return;
@@ -393,13 +247,13 @@ function createMattermostConnectOnce(opts) {
393
247
  };
394
248
  ws.on("open", () => {
395
249
  opened = true;
396
- captureWsEvent({
250
+ captureSdk.captureWsEventAsync?.({
397
251
  url: opts.wsUrl,
398
252
  direction: "local",
399
253
  kind: "ws-open",
400
254
  flowId,
401
255
  meta: { subsystem: "mattermost-websocket" }
402
- });
256
+ }).catch(() => {});
403
257
  opts.statusSink?.({
404
258
  connected: true,
405
259
  lifecycle: "starting"
@@ -410,7 +264,7 @@ function createMattermostConnectOnce(opts) {
410
264
  action: "authentication_challenge",
411
265
  data: { token: opts.botToken }
412
266
  });
413
- captureWsEvent({
267
+ captureSdk.captureWsEventAsync?.({
414
268
  url: opts.wsUrl,
415
269
  direction: "outbound",
416
270
  kind: "ws-frame",
@@ -420,7 +274,7 @@ function createMattermostConnectOnce(opts) {
420
274
  subsystem: "mattermost-websocket",
421
275
  eventType: "authentication_challenge"
422
276
  }
423
- });
277
+ }).catch(() => {});
424
278
  ws.send(authPayload);
425
279
  authTimer = setTimeout(() => {
426
280
  authTimer = void 0;
@@ -433,30 +287,26 @@ function createMattermostConnectOnce(opts) {
433
287
  if (getBotUpdateAt) runHealthCheck();
434
288
  });
435
289
  ws.on("pong", () => {
436
- if (protocolPongTimer !== void 0) {
437
- clearTimeout(protocolPongTimer);
438
- protocolPongTimer = void 0;
439
- }
290
+ clearTimeout(protocolPongTimer);
291
+ protocolPongTimer = void 0;
440
292
  scheduleProtocolPing();
441
293
  });
442
294
  ws.on("message", async (data) => {
443
295
  const raw = rawDataToString(data);
444
- captureWsEvent({
296
+ captureSdk.captureWsEventAsync?.({
445
297
  url: opts.wsUrl,
446
298
  direction: "inbound",
447
299
  kind: "ws-frame",
448
300
  flowId,
449
301
  payload: Buffer.from(raw),
450
302
  meta: { subsystem: "mattermost-websocket" }
451
- });
303
+ }).catch(() => {});
452
304
  const payload = parseMattermostEventPayload(raw);
453
305
  if (!payload) return;
454
306
  if (payload.status === "OK" && payload.seq_reply === authenticationSeq) {
455
307
  authenticated = true;
456
- if (authTimer !== void 0) {
457
- clearTimeout(authTimer);
458
- authTimer = void 0;
459
- }
308
+ clearTimeout(authTimer);
309
+ authTimer = void 0;
460
310
  opts.statusSink?.(channelReadyPatch());
461
311
  return;
462
312
  }
@@ -478,7 +328,7 @@ function createMattermostConnectOnce(opts) {
478
328
  }
479
329
  });
480
330
  ws.on("close", (code, reason) => {
481
- captureWsEvent({
331
+ captureSdk.captureWsEventAsync?.({
482
332
  url: opts.wsUrl,
483
333
  direction: "local",
484
334
  kind: "ws-close",
@@ -486,9 +336,9 @@ function createMattermostConnectOnce(opts) {
486
336
  closeCode: code,
487
337
  payload: reason,
488
338
  meta: { subsystem: "mattermost-websocket" }
489
- });
339
+ }).catch(() => {});
490
340
  stopHealthChecks();
491
- const message = reasonToString(reason);
341
+ const message = reason.toString("utf8");
492
342
  opts.statusSink?.({
493
343
  connected: false,
494
344
  lifecycle: "recovering",
@@ -509,14 +359,14 @@ function createMattermostConnectOnce(opts) {
509
359
  rejectOnce(new WebSocketClosedBeforeOpenError(code, message || void 0));
510
360
  });
511
361
  ws.on("error", (err) => {
512
- captureWsEvent({
362
+ captureSdk.captureWsEventAsync?.({
513
363
  url: opts.wsUrl,
514
364
  direction: "local",
515
365
  kind: "error",
516
366
  flowId,
517
367
  errorText: String(err),
518
368
  meta: { subsystem: "mattermost-websocket" }
519
- });
369
+ }).catch(() => {});
520
370
  opts.runtime.error?.(`mattermost websocket error: ${String(err)}`);
521
371
  opts.statusSink?.({
522
372
  connected: false,
@@ -533,11 +383,6 @@ function createMattermostConnectOnce(opts) {
533
383
  }
534
384
  };
535
385
  }
536
- function reasonToString(reason) {
537
- if (!reason) return "";
538
- if (typeof reason === "string") return reason;
539
- return reason.length > 0 ? reason.toString("utf8") : "";
540
- }
541
386
  //#endregion
542
387
  //#region extensions/mattermost/src/mattermost/monitor-ingress.ts
543
388
  const MATTERMOST_INGRESS_PAYLOAD_VERSION = 1;
@@ -604,7 +449,7 @@ function resolveMattermostIngressNonRetryableFailure(error) {
604
449
  function createMattermostIngressMonitor(options) {
605
450
  const monitor = createChannelIngressMonitor({
606
451
  queue: options.queue ?? (() => getMattermostRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
607
- inspect: (rawEvent) => inspectMattermostIngressEvent(rawEvent),
452
+ inspect: inspectMattermostIngressEvent,
608
453
  payload: {
609
454
  version: MATTERMOST_INGRESS_PAYLOAD_VERSION,
610
455
  serialize: (rawEvent, { receivedAt }) => ({
@@ -657,20 +502,7 @@ function createMattermostIngressMonitor(options) {
657
502
  }
658
503
  //#endregion
659
504
  //#region extensions/mattermost/src/mattermost/no-visible-reply-diagnostic.ts
660
- /**
661
- * Detects the #80501 symptom: `deliverMattermostReplyPayload` accepted a
662
- * substantive (non-reasoning) payload, called the underlying
663
- * `deliverTextOrMediaReply`, and the outcome was `"empty"` — meaning the
664
- * payload had no text and no media to send, so no Mattermost API call
665
- * happened. The agent's run completes successfully, but no visible
666
- * channel/thread reply ever surfaces to the user.
667
- *
668
- * Returns a structured violation when the outcome is `"empty"` for a payload
669
- * that nominally carried user-facing content (text or media bytes that ended
670
- * up dropped by `resolveSendableOutboundReplyParts`/`sendMediaWithLeadingCaption`).
671
- * Returns `null` for `"reasoning_skipped"` (intentional suppression),
672
- * `"text"`, or `"media"` (successful visible sends).
673
- */
505
+ /** Detect dropped substantive payloads even when the agent run succeeded (#80501). */
674
506
  function evaluateMattermostNoVisibleReply(params) {
675
507
  if (params.outcome !== "empty") return null;
676
508
  const finalText = typeof params.payload.text === "string" ? params.payload.text.trim() : "";
@@ -691,9 +523,6 @@ function formatMattermostNoVisibleReplyLog(params) {
691
523
  function shouldUpdateMattermostDraftToolProgress(account) {
692
524
  return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config, account.streamingMode !== "progress", account.streamingMode);
693
525
  }
694
- function shouldSuppressMattermostDefaultToolProgressMessages(account) {
695
- return account.streamingMode !== "off";
696
- }
697
526
  function buildMattermostModelPickerSelectMessageSid(params) {
698
527
  const provider = normalizeLowercaseStringOrEmpty(params.provider);
699
528
  const model = normalizeLowercaseStringOrEmpty(params.model);
@@ -753,9 +582,10 @@ function resolveMattermostThreadSessionContext(params) {
753
582
  replyToMode: params.replyToMode,
754
583
  threadRootId: params.threadRootId
755
584
  });
756
- const threadKeys = resolveThreadSessionKeys$1({
585
+ const threadKeys = resolveThreadSessionKeys({
757
586
  baseSessionKey: params.baseSessionKey,
758
587
  threadId: effectiveReplyToId,
588
+ normalizeThreadId: (threadId) => threadId,
759
589
  parentSessionKey: effectiveReplyToId && params.kind !== "direct" ? params.baseSessionKey : void 0
760
590
  });
761
591
  return {
@@ -917,7 +747,7 @@ function createMattermostQuestionInteractionHandler(monitor) {
917
747
  }
918
748
  function registerMattermostInteractions(params) {
919
749
  const { monitor } = params;
920
- const { account, botUserId, cfg, client, core, pairing, resources, runtime } = monitor;
750
+ const { account, cfg, client, core, pairing, resources, runtime } = monitor;
921
751
  const { resolveChannelInfo } = resources;
922
752
  const handleQuestionInteraction = createMattermostQuestionInteractionHandler(monitor);
923
753
  return registerPluginHttpRoute({
@@ -926,7 +756,6 @@ function registerMattermostInteractions(params) {
926
756
  auth: "plugin",
927
757
  handler: createMattermostInteractionHandler({
928
758
  client,
929
- botUserId,
930
759
  accountId: account.accountId,
931
760
  allowedSourceIps: params.allowedSourceIps,
932
761
  trustedProxies: cfg.gateway?.trustedProxies,
@@ -1179,32 +1008,22 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1179
1008
  buttons
1180
1009
  });
1181
1010
  if (data.providers.length === 0) return await updatePickerPost("No models available.");
1182
- if (pickerState.action === "providers" || pickerState.action === "back") {
1011
+ if (pickerState.action !== "select") {
1183
1012
  const currentModel = resolveMattermostModelPickerCurrentModel({
1184
1013
  cfg,
1185
1014
  route: modelSessionRoute,
1186
1015
  data
1187
1016
  });
1188
- const view = renderMattermostProviderPickerView({
1017
+ const viewParams = {
1189
1018
  ownerUserId: pickerState.ownerUserId,
1190
1019
  data,
1191
1020
  currentModel
1192
- });
1193
- return await updatePickerPost(view.text, view.buttons);
1194
- }
1195
- if (pickerState.action === "list") {
1196
- const currentModel = resolveMattermostModelPickerCurrentModel({
1197
- cfg,
1198
- route: modelSessionRoute,
1199
- data
1200
- });
1201
- const view = renderMattermostModelsPickerView({
1202
- ownerUserId: pickerState.ownerUserId,
1203
- data,
1021
+ };
1022
+ const view = pickerState.action === "list" ? renderMattermostModelsPickerView({
1023
+ ...viewParams,
1204
1024
  provider: pickerState.provider,
1205
- page: pickerState.page,
1206
- currentModel
1207
- });
1025
+ page: pickerState.page
1026
+ }) : renderMattermostProviderPickerView(viewParams);
1208
1027
  return await updatePickerPost(view.text, view.buttons);
1209
1028
  }
1210
1029
  const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
@@ -1244,6 +1063,18 @@ function createMattermostModelPickerInteractionHandler(monitor) {
1244
1063
  };
1245
1064
  }
1246
1065
  //#endregion
1066
+ //#region src/channels/mention-gating.ts
1067
+ function resolveBotThreadMentionPolicy(params) {
1068
+ if (!params.isBotOwnedThread || params.requireMentionInBotThreads === void 0) return {
1069
+ requireMention: params.requireMention,
1070
+ implicitMentionKinds: params.implicitMentionKinds
1071
+ };
1072
+ return {
1073
+ requireMention: params.requireMentionInBotThreads,
1074
+ implicitMentionKinds: params.requireMentionInBotThreads ? params.implicitMentionKinds?.filter((kind) => kind === "native") : params.implicitMentionKinds
1075
+ };
1076
+ }
1077
+ //#endregion
1247
1078
  //#region extensions/mattermost/src/mattermost/monitor-activation.ts
1248
1079
  function resolveMattermostInboundMentionDecision(params) {
1249
1080
  const implicitMentions = resolveChannelImplicitMentions({
@@ -1318,30 +1149,39 @@ function formatMattermostInboundMediaText(params) {
1318
1149
  }
1319
1150
  const CHANNEL_CACHE_TTL_MS = 3e5;
1320
1151
  const USER_CACHE_TTL_MS = 6e5;
1152
+ const POST_CACHE_TTL_MS = 3e5;
1321
1153
  const MONITOR_RESOURCE_CACHE_MAX_ENTRIES = 1e3;
1322
1154
  const MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS = 12e4;
1323
1155
  const MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS = 3e4;
1324
1156
  function createMattermostMonitorResources(params) {
1325
1157
  const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
1326
- const channelCache = /* @__PURE__ */ new Map();
1327
- const userCache = /* @__PURE__ */ new Map();
1328
- const getCachedValue = (cache, key, nowMs) => {
1329
- const cached = cache.get(key);
1330
- if (!cached) return;
1331
- if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
1332
- cache.delete(key);
1333
- };
1334
- const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
1335
- const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
1336
- if (expiresAt !== void 0) {
1337
- cache.delete(key);
1338
- cache.set(key, {
1339
- value,
1340
- expiresAt
1341
- });
1342
- pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
1343
- }
1344
- };
1158
+ function createCachedLookup(label, ttlMs, fetchValue) {
1159
+ const cache = /* @__PURE__ */ new Map();
1160
+ return async (id) => {
1161
+ const rawNow = Date.now();
1162
+ const now = asDateTimestampMs(rawNow);
1163
+ const cached = cache.get(id);
1164
+ if (cached && now !== void 0 && cached.expiresAt > now) {
1165
+ if (cached.value !== void 0) return cached.value;
1166
+ } else cache.delete(id);
1167
+ try {
1168
+ const value = await fetchValue(id);
1169
+ const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNow });
1170
+ if (expiresAt !== void 0) {
1171
+ cache.delete(id);
1172
+ cache.set(id, {
1173
+ value,
1174
+ expiresAt
1175
+ });
1176
+ pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
1177
+ }
1178
+ return value;
1179
+ } catch (err) {
1180
+ logger.debug?.(`mattermost: ${label} lookup failed: ${String(err)}`);
1181
+ return null;
1182
+ }
1183
+ };
1184
+ }
1345
1185
  const resolveMattermostMedia = async (fileIds) => {
1346
1186
  const ids = normalizeStringEntries(fileIds ?? []);
1347
1187
  if (ids.length === 0) return [];
@@ -1397,40 +1237,20 @@ function createMattermostMonitorResources(params) {
1397
1237
  parentId
1398
1238
  });
1399
1239
  };
1400
- const resolveChannelInfo = async (channelId) => {
1401
- const rawNow = Date.now();
1402
- const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
1403
- if (cached !== void 0) return cached;
1404
- try {
1405
- const info = await fetchMattermostChannel(client, channelId);
1406
- setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
1407
- return info;
1408
- } catch (err) {
1409
- logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
1410
- return null;
1411
- }
1412
- };
1413
- const resolveUserInfo = async (userId) => {
1414
- const rawNow = Date.now();
1415
- const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
1416
- if (cached !== void 0) return cached;
1417
- try {
1418
- const info = await fetchMattermostUser(client, userId);
1419
- setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
1420
- return info;
1421
- } catch (err) {
1422
- logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
1423
- return null;
1424
- }
1425
- };
1426
- const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
1427
- callbackUrl,
1428
- accountId,
1429
- channelId,
1430
- buttons
1240
+ const resolveChannelInfo = createCachedLookup("channel", CHANNEL_CACHE_TTL_MS, (channelId) => fetchMattermostChannel(client, channelId));
1241
+ const resolveUserInfo = createCachedLookup("user", USER_CACHE_TTL_MS, (userId) => fetchMattermostUser(client, userId));
1242
+ const resolvePostInfo = createCachedLookup("post", POST_CACHE_TTL_MS, async (postId) => {
1243
+ const info = MattermostPostSchema.parse(await client.request(`/posts/${encodeURIComponent(postId)}`));
1244
+ if (info.id !== postId) throw new Error("Mattermost post lookup returned a different post id");
1245
+ return info;
1431
1246
  });
1432
1247
  const updateModelPickerPost = async (paramsLocal) => {
1433
- const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
1248
+ const props = buildButtonProps({
1249
+ callbackUrl,
1250
+ accountId,
1251
+ channelId: paramsLocal.channelId,
1252
+ buttons: paramsLocal.buttons ?? []
1253
+ }) ?? { attachments: [] };
1434
1254
  await updateMattermostPost(client, paramsLocal.postId, {
1435
1255
  message: paramsLocal.message,
1436
1256
  props
@@ -1442,6 +1262,7 @@ function createMattermostMonitorResources(params) {
1442
1262
  sendTypingIndicator,
1443
1263
  resolveChannelInfo,
1444
1264
  resolveUserInfo,
1265
+ resolvePostInfo,
1445
1266
  updateModelPickerPost
1446
1267
  };
1447
1268
  }
@@ -1730,21 +1551,16 @@ function createMattermostDraftStream(params) {
1730
1551
  return false;
1731
1552
  }
1732
1553
  };
1733
- const clearMessageId = () => {
1734
- currentGeneration.postId = void 0;
1735
- };
1736
- const isValidMessageId = (value) => typeof value === "string" && value.length > 0;
1737
- const deleteMessage = async (postId) => {
1738
- await deleteMattermostPost(params.client, postId);
1739
- };
1740
1554
  const { loop, update: updateLifecycle, stop: stopLifecycle, stopForClear, clearWithStop, seal: sealLifecycle } = createFinalizableDraftLifecycle({
1741
1555
  throttleMs,
1742
1556
  state: streamState,
1743
1557
  sendOrEditStreamMessage,
1744
1558
  readMessageId: () => currentGeneration.postId,
1745
- clearMessageId,
1746
- isValidMessageId,
1747
- deleteMessage,
1559
+ clearMessageId: () => {
1560
+ currentGeneration.postId = void 0;
1561
+ },
1562
+ isValidMessageId: (value) => typeof value === "string" && value.length > 0,
1563
+ deleteMessage: (postId) => deleteMattermostPost(params.client, postId),
1748
1564
  warn: params.warn,
1749
1565
  warnPrefix: "mattermost stream preview cleanup failed"
1750
1566
  });
@@ -1834,18 +1650,13 @@ function createMattermostDraftStream(params) {
1834
1650
  loop.resetThrottleWindow();
1835
1651
  return boundary;
1836
1652
  };
1837
- const flush = async () => {
1838
- assertNoAcceptedDeliveryFailure();
1839
- await loop.flush();
1840
- await currentGeneration.ready;
1841
- assertNoAcceptedDeliveryFailure();
1842
- };
1843
- const discardPending = async () => {
1653
+ const settleOperation = (operation) => async () => {
1844
1654
  assertNoAcceptedDeliveryFailure();
1845
- await stopForClear();
1655
+ await operation();
1846
1656
  await currentGeneration.ready;
1847
1657
  assertNoAcceptedDeliveryFailure();
1848
1658
  };
1659
+ const discardPending = settleOperation(stopForClear);
1849
1660
  const clear = async () => {
1850
1661
  assertNoAcceptedDeliveryFailure();
1851
1662
  await clearWithStop(discardPending);
@@ -1875,18 +1686,6 @@ function createMattermostDraftStream(params) {
1875
1686
  await retirement;
1876
1687
  assertNoAcceptedDeliveryFailure();
1877
1688
  };
1878
- const seal = async () => {
1879
- assertNoAcceptedDeliveryFailure();
1880
- await sealLifecycle();
1881
- await currentGeneration.ready;
1882
- assertNoAcceptedDeliveryFailure();
1883
- };
1884
- const stop = async () => {
1885
- assertNoAcceptedDeliveryFailure();
1886
- await stopLifecycle();
1887
- await currentGeneration.ready;
1888
- assertNoAcceptedDeliveryFailure();
1889
- };
1890
1689
  const update = (text) => {
1891
1690
  currentGeneration.latestSourceText = text;
1892
1691
  currentGeneration.latestAssistantText = void 0;
@@ -1945,13 +1744,13 @@ function createMattermostDraftStream(params) {
1945
1744
  return {
1946
1745
  update,
1947
1746
  updateAssistantText,
1948
- flush,
1747
+ flush: settleOperation(loop.flush),
1949
1748
  postId: () => currentGeneration.postId,
1950
1749
  clear,
1951
1750
  deleteCurrentMessage,
1952
1751
  discardPending,
1953
- seal,
1954
- stop,
1752
+ seal: settleOperation(sealLifecycle),
1753
+ stop: settleOperation(stopLifecycle),
1955
1754
  forceNewMessage,
1956
1755
  settleBoundaries,
1957
1756
  resolveFinalText
@@ -2131,7 +1930,6 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2131
1930
  const hookRunner = getGlobalHookRunner();
2132
1931
  const draftPreviewEnabled = !((hookRunner?.hasHooks("reply_payload_sending") ?? false) || (hookRunner?.hasHooks("message_sending") ?? false)) && account.streamingMode !== "off";
2133
1932
  const draftProgressEnabled = draftPreviewEnabled && (account.streamingMode === "progress" || shouldUpdateMattermostDraftToolProgress(account));
2134
- const suppressDefaultToolProgressMessages = draftPreviewEnabled && shouldSuppressMattermostDefaultToolProgressMessages(account);
2135
1933
  const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
2136
1934
  client,
2137
1935
  channelId,
@@ -2143,9 +1941,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2143
1941
  }) : createDisabledMattermostDraftStream();
2144
1942
  const previewBoundaryController = createMattermostDraftPreviewBoundaryController({
2145
1943
  enabled: draftPreviewEnabled && account.streamingMode === "block",
2146
- forceNewMessage: async () => {
2147
- await draftStream.forceNewMessage();
2148
- }
1944
+ forceNewMessage: draftStream.forceNewMessage
2149
1945
  });
2150
1946
  let lastPartialText = "";
2151
1947
  let firstAssistantPreviewPrefix;
@@ -2214,12 +2010,7 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2214
2010
  const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
2215
2011
  const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
2216
2012
  if (!chunks.length && formatted) chunks.push(formatted);
2217
- if (chunks.length !== 1) return {
2218
- deliveryText,
2219
- confirmedDelivery,
2220
- alreadyDelivered: resolution.kind === "already-delivered"
2221
- };
2222
- const trimmed = chunks[0]?.trim();
2013
+ const trimmed = chunks.length === 1 ? chunks[0]?.trim() : void 0;
2223
2014
  if (!trimmed) return {
2224
2015
  deliveryText,
2225
2016
  confirmedDelivery,
@@ -2388,16 +2179,13 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2388
2179
  preserveProgressCallbackStartOrder: draftPreviewEnabled ? true : void 0,
2389
2180
  onObservedReplyDelivery: draftPreviewEnabled ? () => previewLifecycle.observeDelivery({ visibleReplySent: true }) : void 0,
2390
2181
  disableBlockStreaming: draftPreviewEnabled ? true : replyOptions.disableBlockStreaming,
2391
- ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2182
+ ...draftPreviewEnabled ? { suppressDefaultToolProgressMessages: true } : {},
2392
2183
  onModelSelected,
2393
2184
  onPartialReply: (payloadResult) => account.streamingMode === "progress" ? false : updateDraftFromPartial(payloadResult.text),
2394
2185
  onAssistantMessageStart: () => {
2395
2186
  lastPartialText = "";
2396
2187
  progressDraft.beginAssistantMessage();
2397
- if (account.streamingMode === "block") {
2398
- blockPreviewAssistantMessagePending = true;
2399
- return false;
2400
- }
2188
+ if (account.streamingMode === "block") blockPreviewAssistantMessagePending = true;
2401
2189
  return false;
2402
2190
  },
2403
2191
  onReasoningEnd: () => {
@@ -2453,11 +2241,12 @@ async function dispatchMattermostInboundTurn(monitor, params) {
2453
2241
  //#region extensions/mattermost/src/mattermost/monitor-posts.ts
2454
2242
  function createMattermostPostHandler(monitor) {
2455
2243
  const { account, botUserId, botUsername, cfg, core, groupPolicy, pairing, resources } = monitor;
2244
+ const groups = resolveChannelGroups(cfg, "mattermost", account.accountId);
2456
2245
  const groupsConfigPath = resolveChannelGroupsConfigPath({
2457
2246
  cfg,
2458
2247
  channel: "mattermost",
2459
2248
  accountId: account.accountId,
2460
- groups: resolveChannelGroups(cfg, "mattermost", account.accountId)
2249
+ groups
2461
2250
  });
2462
2251
  const { resolveMattermostMedia, resolveUserInfo } = resources;
2463
2252
  const channelHistories = /* @__PURE__ */ new Map();
@@ -2640,14 +2429,30 @@ function createMattermostPostHandler(monitor) {
2640
2429
  groupId: channelId,
2641
2430
  requireMentionOverride: account.requireMention
2642
2431
  });
2432
+ const requireMentionInBotThreads = groups?.[channelId]?.requireMentionInBotThreads ?? groups?.["*"]?.requireMentionInBotThreads ?? account.config.requireMentionInBotThreads;
2433
+ const nativeThreadRootId = normalizeOptionalString(post.root_id);
2434
+ let isBotOwnedThread = false;
2435
+ if (kind !== "direct" && nativeThreadRootId && requireMentionInBotThreads !== void 0) try {
2436
+ const root = MattermostPostSchema.safeParse(await monitor.client.request(`/posts/${encodeURIComponent(nativeThreadRootId)}`));
2437
+ isBotOwnedThread = root.success && root.data.id === nativeThreadRootId && root.data.channel_id === channelId && root.data.user_id === botUserId && !root.data.delete_at && !normalizeOptionalString(root.data.root_id);
2438
+ } catch (err) {
2439
+ monitor.logVerboseMessage(`mattermost: failed resolving thread owner channel=${channelId} root=${nativeThreadRootId}: ${String(err)}`);
2440
+ }
2441
+ const botThreadPolicy = resolveBotThreadMentionPolicy({
2442
+ isBotOwnedThread,
2443
+ requireMentionInBotThreads,
2444
+ requireMention: shouldRequireMention || oncharEnabled,
2445
+ implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged)
2446
+ });
2447
+ const botThreadMentionRequired = isBotOwnedThread && requireMentionInBotThreads === true;
2643
2448
  const mentionDecision = resolveMattermostInboundMentionDecision({
2644
2449
  cfg,
2645
2450
  accountId: account.accountId,
2646
2451
  kind,
2647
- requireMention: shouldRequireMention || oncharEnabled,
2648
- canDetectMention: canDetectMention || oncharEnabled,
2452
+ requireMention: botThreadPolicy.requireMention,
2453
+ canDetectMention: canDetectMention || oncharEnabled || botThreadMentionRequired,
2649
2454
  wasMentioned: wasMentioned || oncharTriggered,
2650
- implicitMentionKinds: implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged),
2455
+ implicitMentionKinds: botThreadPolicy.implicitMentionKinds,
2651
2456
  allowTextCommands,
2652
2457
  hasControlCommand: isControlCommand,
2653
2458
  commandAuthorized
@@ -2665,7 +2470,7 @@ function createMattermostPostHandler(monitor) {
2665
2470
  reason: "no mention",
2666
2471
  target: channelId,
2667
2472
  onceKey: JSON.stringify([account.accountId, channelId]),
2668
- hint: `Mention patterns can be derived from the agent identity name. Set ${groupsConfigPath}[${JSON.stringify(channelId)}].requireMention=false to process messages without a mention. Preserve existing groups entries; when adding the first groups map, include "*": {} to keep other chats admitted.`
2473
+ hint: `Mention patterns can be derived from the agent identity name. Set ${groupsConfigPath}[${JSON.stringify(channelId)}].${botThreadMentionRequired ? "requireMentionInBotThreads" : "requireMention"}=false to process messages without a mention. Preserve existing groups entries; when adding the first groups map, include "*": {} to keep other chats admitted.`
2669
2474
  });
2670
2475
  recordPendingHistory();
2671
2476
  return;
@@ -2690,7 +2495,7 @@ function createMattermostPostHandler(monitor) {
2690
2495
  accountId: account.accountId,
2691
2496
  direction: "inbound"
2692
2497
  });
2693
- const fromLabel = formatInboundFromLabel$1({
2498
+ const fromLabel = formatInboundFromLabel({
2694
2499
  isGroup: kind !== "direct",
2695
2500
  groupLabel: channelDisplay || roomLabel,
2696
2501
  groupId: channelId,
@@ -2811,13 +2616,18 @@ function createMattermostReactionHandler(monitor) {
2811
2616
  monitor.logVerboseMessage("mattermost: drop reaction (no channel_id in broadcast, cannot enforce policy)");
2812
2617
  return;
2813
2618
  }
2619
+ const reactedPost = await monitor.resources.resolvePostInfo(postId);
2814
2620
  const eventPlan = await buildMattermostEventPlan(monitor, {
2815
2621
  channelId,
2816
2622
  senderId: userId,
2623
+ ...reactedPost ? {
2624
+ postId: reactedPost.id,
2625
+ threadRootId: normalizeOptionalString(reactedPost.root_id)
2626
+ } : {},
2817
2627
  dropLabel: "reaction"
2818
2628
  });
2819
2629
  if (!eventPlan) return;
2820
- const { kind, route } = eventPlan;
2630
+ const { kind, thread } = eventPlan;
2821
2631
  const reactionAccess = await resolveMattermostMonitorInboundAccess({
2822
2632
  account,
2823
2633
  cfg,
@@ -2838,7 +2648,7 @@ function createMattermostReactionHandler(monitor) {
2838
2648
  }
2839
2649
  const eventText = `Mattermost reaction ${action}: :${emojiName}: by @${senderName} on post ${postId} in channel ${channelId}`;
2840
2650
  core.system.enqueueSystemEvent(eventText, {
2841
- sessionKey: route.sessionKey,
2651
+ sessionKey: thread.sessionKey,
2842
2652
  contextKey: `mattermost:reaction:${postId}:${emojiName}:${userId}:${action}`
2843
2653
  });
2844
2654
  monitor.logVerboseMessage(`mattermost reaction: ${action} :${emojiName}: by ${senderName} on ${postId}`);
@@ -2889,28 +2699,6 @@ function warnOnSuspiciousCallbackUrl(params) {
2889
2699
  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).`);
2890
2700
  } catch {}
2891
2701
  }
2892
- async function registerSlashCommandsAcrossTeams(params) {
2893
- const registered = [];
2894
- let teamRegistrationFailures = 0;
2895
- for (const team of params.teams) try {
2896
- const created = await registerSlashCommands({
2897
- client: params.client,
2898
- teamId: team.id,
2899
- creatorUserId: params.botUserId,
2900
- callbackUrl: params.callbackUrl,
2901
- commands: params.commands,
2902
- log: (msg) => params.runtime.log?.(msg)
2903
- });
2904
- registered.push(...created);
2905
- } catch (err) {
2906
- teamRegistrationFailures += 1;
2907
- params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
2908
- }
2909
- return {
2910
- registered,
2911
- teamRegistrationFailures
2912
- };
2913
- }
2914
2702
  async function registerMattermostMonitorSlashCommands(params) {
2915
2703
  const commandsRaw = params.account.config.commands;
2916
2704
  const slashConfig = resolveSlashCommandConfig(commandsRaw);
@@ -2919,7 +2707,7 @@ async function registerMattermostMonitorSlashCommands(params) {
2919
2707
  const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
2920
2708
  const slashCallbackUrl = resolveCallbackUrl({
2921
2709
  config: slashConfig,
2922
- gatewayPort: resolveGatewayPort(params.cfg),
2710
+ gatewayPort: (0, gateway_config_runtime_exports.resolveGatewayPort)(params.cfg),
2923
2711
  gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
2924
2712
  });
2925
2713
  warnOnSuspiciousCallbackUrl({
@@ -2932,14 +2720,22 @@ async function registerMattermostMonitorSlashCommands(params) {
2932
2720
  runtime: params.runtime,
2933
2721
  nativeSkills: slashConfig.nativeSkills === true
2934
2722
  }));
2935
- const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
2936
- client: params.client,
2937
- teams,
2938
- botUserId: params.botUserId,
2939
- callbackUrl: slashCallbackUrl,
2940
- commands: dedupedCommands,
2941
- runtime: params.runtime
2942
- });
2723
+ const registered = [];
2724
+ let teamRegistrationFailures = 0;
2725
+ for (const team of teams) try {
2726
+ const created = await registerSlashCommands({
2727
+ client: params.client,
2728
+ teamId: team.id,
2729
+ creatorUserId: params.botUserId,
2730
+ callbackUrl: slashCallbackUrl,
2731
+ commands: dedupedCommands,
2732
+ log: (msg) => params.runtime.log?.(msg)
2733
+ });
2734
+ registered.push(...created);
2735
+ } catch (err) {
2736
+ teamRegistrationFailures += 1;
2737
+ params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
2738
+ }
2943
2739
  if (registered.length === 0) {
2944
2740
  params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
2945
2741
  return;
@@ -2975,14 +2771,13 @@ async function runWithReconnect(connectFn, opts = {}) {
2975
2771
  const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
2976
2772
  const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
2977
2773
  const random = opts.random ?? Math.random;
2978
- const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
2774
+ let retryDelay = initialDelayMs;
2979
2775
  let attempt = 0;
2980
2776
  while (!opts.abortSignal?.aborted) {
2981
2777
  let outcome = "resolved";
2982
2778
  let error;
2983
2779
  try {
2984
2780
  await connectFn();
2985
- backoff.reset();
2986
2781
  } catch (err) {
2987
2782
  if (opts.abortSignal?.aborted) return;
2988
2783
  outcome = "rejected";
@@ -2990,7 +2785,8 @@ async function runWithReconnect(connectFn, opts = {}) {
2990
2785
  opts.onError?.(err);
2991
2786
  }
2992
2787
  if (opts.abortSignal?.aborted) return;
2993
- const delayMs = withJitter(backoff.current(), jitterRatio, random);
2788
+ if (outcome === "resolved") retryDelay = initialDelayMs;
2789
+ const delayMs = withJitter(retryDelay, jitterRatio, random);
2994
2790
  if (!(opts.shouldReconnect?.({
2995
2791
  attempt,
2996
2792
  delayMs,
@@ -2999,22 +2795,10 @@ async function runWithReconnect(connectFn, opts = {}) {
2999
2795
  }) ?? true)) return;
3000
2796
  opts.onReconnect?.(delayMs);
3001
2797
  await sleepAbortable(delayMs, opts.abortSignal);
3002
- if (outcome === "rejected") backoff.increase();
2798
+ if (outcome === "rejected") retryDelay = Math.min(retryDelay * 2, maxDelayMs);
3003
2799
  attempt++;
3004
2800
  }
3005
2801
  }
3006
- function createReconnectBackoff(initialDelayMs, maxDelayMs) {
3007
- let retryDelay = initialDelayMs;
3008
- return {
3009
- current: () => retryDelay,
3010
- reset: () => {
3011
- retryDelay = initialDelayMs;
3012
- },
3013
- increase: () => {
3014
- retryDelay = Math.min(retryDelay * 2, maxDelayMs);
3015
- }
3016
- };
3017
- }
3018
2802
  function withJitter(baseMs, jitterRatio, random) {
3019
2803
  if (jitterRatio <= 0) return baseMs;
3020
2804
  const normalized = Math.max(0, Math.min(1, random()));
@@ -3122,7 +2906,7 @@ async function monitorMattermostProvider(opts = {}) {
3122
2906
  resolveChannelLimitMb: () => account.config.mediaMaxMb,
3123
2907
  accountId: account.accountId
3124
2908
  }) ?? 8388608;
3125
- const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy$1({
2909
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
3126
2910
  providerConfigPresent: cfg.channels?.mattermost !== void 0,
3127
2911
  groupPolicy: account.config.groupPolicy,
3128
2912
  defaultGroupPolicy: resolveDefaultGroupPolicy(cfg)
@@ -3286,244 +3070,4 @@ async function monitorMattermostProvider(opts = {}) {
3286
3070
  if (slashShutdownCleanupPromise) await Promise.resolve(slashShutdownCleanupPromise);
3287
3071
  }
3288
3072
  //#endregion
3289
- //#region extensions/mattermost/src/mattermost/probe.ts
3290
- async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivateNetwork = false, deps) {
3291
- const normalized = normalizeMattermostBaseUrl(baseUrl);
3292
- if (!normalized) return {
3293
- ok: false,
3294
- error: "baseUrl missing"
3295
- };
3296
- const url = `${normalized}/api/v4/users/me`;
3297
- const headers = { Authorization: `Bearer ${botToken}` };
3298
- return await runChannelProbe(void 0, async ({ elapsedMs }) => {
3299
- const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : void 0;
3300
- const { response: res, release } = await fetchWithSsrFGuard({
3301
- url,
3302
- init: { headers },
3303
- auditContext: "mattermost-probe",
3304
- policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork),
3305
- ...resolvedTimeoutMs !== void 0 ? { timeoutMs: resolvedTimeoutMs } : {},
3306
- ...deps?.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
3307
- ...deps?.lookupFn ? { lookupFn: deps.lookupFn } : {}
3308
- });
3309
- const requestElapsedMs = elapsedMs();
3310
- try {
3311
- if (!res.ok) {
3312
- const detail = await readMattermostError(res, headers);
3313
- return {
3314
- ok: false,
3315
- status: res.status,
3316
- error: detail || res.statusText,
3317
- elapsedMs: requestElapsedMs
3318
- };
3319
- }
3320
- const bot = await readProviderJsonResponse(res, "Mattermost probe /users/me");
3321
- return {
3322
- ok: true,
3323
- status: res.status,
3324
- elapsedMs: requestElapsedMs,
3325
- bot
3326
- };
3327
- } finally {
3328
- await release();
3329
- }
3330
- }, (error) => ({
3331
- ok: false,
3332
- status: null,
3333
- error: formatErrorMessage(error)
3334
- }));
3335
- }
3336
- //#endregion
3337
- //#region extensions/mattermost/src/mattermost/reactions.ts
3338
- const BOT_USER_CACHE_TTL_MS = 6e5;
3339
- const botUserIdCache = /* @__PURE__ */ new Map();
3340
- async function resolveBotUserId(client, cacheKey) {
3341
- const rawNow = Date.now();
3342
- const now = asDateTimestampMs(rawNow);
3343
- const cached = botUserIdCache.get(cacheKey);
3344
- if (cached) {
3345
- if (now !== void 0 && cached.expiresAt > now) return cached.userId;
3346
- botUserIdCache.delete(cacheKey);
3347
- }
3348
- const userId = (await fetchMattermostMe(client))?.id?.trim();
3349
- if (!userId) return null;
3350
- const expiresAt = resolveExpiresAtMsFromDurationMs(BOT_USER_CACHE_TTL_MS, { nowMs: rawNow });
3351
- if (expiresAt !== void 0) botUserIdCache.set(cacheKey, {
3352
- userId,
3353
- expiresAt
3354
- });
3355
- return userId;
3356
- }
3357
- async function addMattermostReaction(params) {
3358
- return runMattermostReaction(params, {
3359
- action: "add",
3360
- mutation: createReaction
3361
- });
3362
- }
3363
- async function removeMattermostReaction(params) {
3364
- return runMattermostReaction(params, {
3365
- action: "remove",
3366
- mutation: deleteReaction
3367
- });
3368
- }
3369
- function parseAuthorizedReactionTarget(rawTarget) {
3370
- const normalized = rawTarget ? normalizeMattermostMessagingTarget(rawTarget) : void 0;
3371
- if (!normalized) return null;
3372
- if (normalized.startsWith("channel:")) {
3373
- const id = normalized.slice(8).trim();
3374
- return id ? {
3375
- kind: "channel",
3376
- id
3377
- } : null;
3378
- }
3379
- if (normalized.startsWith("user:")) {
3380
- const id = normalized.slice(5).trim();
3381
- return id ? {
3382
- kind: "user",
3383
- id
3384
- } : null;
3385
- }
3386
- return null;
3387
- }
3388
- async function authorizeMattermostReactionResource(params) {
3389
- const target = parseAuthorizedReactionTarget(params.authorizedTarget);
3390
- if (!target) throw new Error("Mattermost delegated reactions require a canonical authorized conversation target.");
3391
- const postChannelId = (await params.client.request(`/posts/${encodeURIComponent(params.postId)}`)).channel_id?.trim();
3392
- if (!postChannelId) throw new Error("Mattermost reaction post is missing its conversation binding.");
3393
- if (target.kind === "channel") {
3394
- if (postChannelId !== target.id) throw new Error("Mattermost reaction post belongs to a different conversation.");
3395
- return;
3396
- }
3397
- const botUserId = await resolveBotUserId(params.client, params.cacheKey);
3398
- if (!botUserId) throw new Error("Mattermost reactions failed: could not resolve bot user id.");
3399
- const channel = await fetchMattermostChannel(params.client, postChannelId);
3400
- const participants = channel.name?.split("__").map((entry) => entry.trim()).filter(Boolean).toSorted() ?? [];
3401
- const authorizedParticipants = [botUserId, target.id].toSorted();
3402
- if (channel.type !== "D" || participants.length !== 2 || participants[0] !== authorizedParticipants[0] || participants[1] !== authorizedParticipants[1]) throw new Error("Mattermost reaction post belongs to a different direct conversation.");
3403
- return botUserId;
3404
- }
3405
- async function runMattermostReaction(params, options) {
3406
- const resolved = resolveMattermostAccount({
3407
- cfg: params.cfg,
3408
- accountId: params.accountId
3409
- });
3410
- const baseUrl = resolved.baseUrl?.trim();
3411
- const botToken = resolved.botToken?.trim();
3412
- if (!baseUrl || !botToken) return {
3413
- ok: false,
3414
- error: "Mattermost botToken/baseUrl missing."
3415
- };
3416
- const client = createMattermostClient({
3417
- baseUrl,
3418
- botToken,
3419
- fetchImpl: params.fetchImpl,
3420
- allowPrivateNetwork: isPrivateNetworkOptInEnabled(resolved.config)
3421
- });
3422
- const cacheKey = `${baseUrl}:${botToken}`;
3423
- try {
3424
- const userId = (params.conversationReadOrigin === "direct-operator" ? void 0 : await authorizeMattermostReactionResource({
3425
- client,
3426
- cacheKey,
3427
- postId: params.postId,
3428
- authorizedTarget: params.authorizedTarget
3429
- })) ?? await resolveBotUserId(client, cacheKey);
3430
- if (!userId) return {
3431
- ok: false,
3432
- error: "Mattermost reactions failed: could not resolve bot user id."
3433
- };
3434
- await options.mutation(client, {
3435
- userId,
3436
- postId: params.postId,
3437
- emojiName: params.emojiName
3438
- });
3439
- } catch (err) {
3440
- return {
3441
- ok: false,
3442
- error: `Mattermost ${options.action} reaction failed: ${String(err)}`
3443
- };
3444
- }
3445
- return { ok: true };
3446
- }
3447
- async function createReaction(client, params) {
3448
- await client.request("/reactions", {
3449
- method: "POST",
3450
- body: JSON.stringify({
3451
- user_id: params.userId,
3452
- post_id: params.postId,
3453
- emoji_name: params.emojiName
3454
- })
3455
- });
3456
- }
3457
- async function deleteReaction(client, params) {
3458
- const emoji = encodeURIComponent(params.emojiName);
3459
- await client.request(`/users/${params.userId}/posts/${params.postId}/reactions/${emoji}`, { method: "DELETE" });
3460
- }
3461
- //#endregion
3462
- //#region extensions/mattermost/src/mattermost/read.ts
3463
- function parseMattermostChannelTarget(rawTarget) {
3464
- const normalized = normalizeMattermostMessagingTarget(rawTarget);
3465
- if (normalized?.startsWith("channel:")) return normalized.slice(8).trim() || void 0;
3466
- const trimmed = rawTarget.trim();
3467
- return trimmed && !trimmed.includes(":") ? trimmed : void 0;
3468
- }
3469
- function isCurrentMattermostReadTarget(params) {
3470
- const toolContext = params.context.toolContext;
3471
- const requesterAccountId = params.context.requesterAccountId?.trim();
3472
- if (normalizeLowercaseStringOrEmpty(toolContext?.currentChannelProvider) !== "mattermost" || !requesterAccountId || normalizeAccountId(requesterAccountId) !== normalizeAccountId(params.accountId)) return false;
3473
- const nativeChannelId = toolContext?.currentChannelId;
3474
- if (typeof nativeChannelId === "string" && nativeChannelId.trim()) return parseMattermostChannelTarget(nativeChannelId) === params.channelId;
3475
- const messagingTarget = toolContext?.currentMessagingTarget;
3476
- return typeof messagingTarget === "string" && Boolean(messagingTarget.trim()) && parseMattermostChannelTarget(messagingTarget) === params.channelId;
3477
- }
3478
- function isConfiguredMattermostReadTarget(params) {
3479
- const { groupPolicy } = resolveAllowlistProviderRuntimeGroupPolicy({
3480
- providerConfigPresent: params.cfg.channels?.mattermost !== void 0,
3481
- groupPolicy: params.account.config.groupPolicy,
3482
- defaultGroupPolicy: params.cfg.channels?.defaults?.groupPolicy
3483
- });
3484
- if (groupPolicy === "disabled") return false;
3485
- if (groupPolicy === "open") return true;
3486
- const groups = params.account.config.groups;
3487
- return groups?.[params.channelId] !== void 0 || groups?.["*"] !== void 0;
3488
- }
3489
- async function readMattermostMessages(params) {
3490
- const account = resolveMattermostAccount({
3491
- cfg: params.cfg,
3492
- accountId: params.accountId
3493
- });
3494
- if (!account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
3495
- const baseUrl = account.baseUrl?.trim();
3496
- const botToken = account.botToken?.trim();
3497
- if (!baseUrl || !botToken) throw new Error("Mattermost botToken/baseUrl missing.");
3498
- const client = createMattermostClient({
3499
- baseUrl,
3500
- botToken,
3501
- fetchImpl: params.fetchImpl,
3502
- allowPrivateNetwork: isPrivateNetworkOptInEnabled(account.config)
3503
- });
3504
- const directOperator = params.context.conversationReadOrigin === "direct-operator";
3505
- const currentConversation = isCurrentMattermostReadTarget({
3506
- accountId: account.accountId,
3507
- channelId: params.channelId,
3508
- context: params.context
3509
- });
3510
- if (!directOperator && !currentConversation) {
3511
- const requesterAccountId = params.context.requesterAccountId?.trim();
3512
- const sameProvider = normalizeLowercaseStringOrEmpty(params.context.toolContext?.currentChannelProvider) === "mattermost";
3513
- const sameAccount = requesterAccountId && normalizeAccountId(requesterAccountId) === normalizeAccountId(account.accountId);
3514
- if (!sameProvider || !sameAccount) throw new Error("Mattermost delegated reads require the current Mattermost account.");
3515
- const channel = await fetchMattermostChannel(client, params.channelId);
3516
- if (channel.type !== "O" && channel.type !== "P" || !isConfiguredMattermostReadTarget({
3517
- cfg: params.cfg,
3518
- account,
3519
- channelId: params.channelId
3520
- })) throw new Error("Mattermost read target channel is not allowed.");
3521
- }
3522
- return await fetchMattermostChannelPosts(client, params.channelId, {
3523
- limit: params.limit,
3524
- before: params.before,
3525
- after: params.after
3526
- });
3527
- }
3528
- //#endregion
3529
- export { addMattermostReaction, listMattermostDirectoryGroups, listMattermostDirectoryPeers, monitorMattermostProvider, probeMattermost, readMattermostMessages, removeMattermostReaction, resolveMattermostOpaqueTarget, sendMessageMattermost };
3073
+ export { monitorMattermostProvider };