@openclaw/mattermost 2026.7.2-beta.3 → 2026.7.2-beta.5

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