@openclaw/mattermost 2026.7.2-beta.5 → 2026.7.33

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