@openclaw/mattermost 2026.7.2-beta.7 → 2026.7.34

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