@openclaw/mattermost 2026.7.2-beta.4 → 2026.7.2-beta.7

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