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

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 { a as deleteMattermostPost, c as fetchMattermostMe, d as fetchMattermostUserTeams, f as normalizeMattermostBaseUrl, g as updateMattermostPost, h as sendMattermostTyping, i as createMattermostPost, l as fetchMattermostUser, n as createMattermostClient, o as fetchMattermostChannel, p as readMattermostError, t as MattermostPostSchema } from "./client-BzLj4dyf.js";
3
- import { C as resolveChannelMediaMaxBytes, E as warnMissingProviderGroupPolicyFallbackOnce, S as resolveAllowlistProviderRuntimeGroupPolicy, T as resolveDefaultGroupPolicy, _ as logInboundDrop, c as buildAgentMediaPayload, d as createChannelMessageReplyPipeline, f as createChannelPairingController, h as listSkillCommandsForAgents, i as normalizeMattermostAllowEntry, l as buildModelsProviderData, n as formatMattermostDirectMessageDropLog, o as resolveMattermostMonitorInboundAccess, s as DEFAULT_GROUP_HISTORY_LIMIT, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logTypingFailure, x as registerPluginHttpRoute, y as parseTcpPort } from "./monitor-auth-dEHa1_On.js";
4
- import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-DO7J-ND1.js";
5
- import { i as resolveMattermostReplyToMode, r as resolveMattermostAccount, t as listMattermostAccountIds } from "./accounts-C4Azn6rA.js";
6
- import { i as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-BXmjNn6B.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-C9bpBN40.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 registerPluginHttpRoute, D as resolveDefaultGroupPolicy, O as warnMissingProviderGroupPolicyFallbackOnce, T as resolveChannelMediaMaxBytes, _ as listSkillCommandsForAgents, a as normalizeMattermostAllowEntry, b as logTypingFailure, c as resolveMattermostTrustedChatKind, d as buildModelsProviderData, f as createChannelHistoryWindow, i as mapMattermostChannelTypeToChatType, l as DEFAULT_GROUP_HISTORY_LIMIT, m as createChannelPairingController, n as formatMattermostDirectMessageDropLog, p as createChannelMessageReplyPipeline, s as resolveMattermostMonitorInboundAccess, t as authorizeMattermostCommandInvocation, u as buildAgentMediaPayload, w as resolveAllowlistProviderRuntimeGroupPolicy, x as parseTcpPort, y as logInboundDrop } from "./monitor-auth-ynw9EnGC.js";
4
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-BIb5iJjA.js";
5
+ import { i as resolveMattermostReplyToMode, r as resolveMattermostAccount, t as listMattermostAccountIds } from "./accounts-B-GrNVwP.js";
6
+ import { i as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-BfV83pya.js";
7
+ import { _ as registerSlashCommands, a as sendMessageMattermost, c as deliverMattermostReplyPayload, d as renderMattermostModelsPickerView, f as renderMattermostProviderPickerView, g as isSlashCommandsEnabled, h as cleanupSlashCommands, l as buildMattermostAllowedModelRefs, m as DEFAULT_COMMAND_SPECS, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as resolveMattermostModelPickerCurrentModel, r as getSlashCommandState, s as createMattermostReplyDeliveryBarrier, t as activateSlashCommands, u as parseMattermostModelPickerContext, v as resolveCallbackUrl, y as resolveSlashCommandConfig } from "./slash-state-N-zfDDSz.js";
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,20 +13,22 @@ 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 { formatInboundFromLabel, formatInboundMediaUnavailableText } from "openclaw/plugin-sdk/channel-inbound";
17
- import { buildChannelProgressDraftLineForEntry, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
16
+ import { formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, implicitMentionKindWhen, resolveInboundMentionDecision } from "openclaw/plugin-sdk/channel-inbound";
17
+ import { DEFAULT_INGRESS_ADOPTION_STALL_MS, DEFAULT_INGRESS_RETRY_DEAD_LETTER_MIN_AGE_MS, DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS, bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressDrain, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
18
18
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
19
+ import { resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
19
20
  import { buildTtsSupplementMediaPayload, countOutboundMedia, getReplyPayloadTtsSupplement, isReasoningReplyPayload } from "openclaw/plugin-sdk/reply-payload";
20
21
  import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
22
+ import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
23
+ import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
21
24
  import { sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
22
25
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
23
26
  import { isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
24
27
  import { chunkMarkdownTextWithMode } from "openclaw/plugin-sdk/reply-chunking";
25
- import { createChannelReplayGuard } from "openclaw/plugin-sdk/persistent-dedupe";
28
+ import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
26
29
  import { captureWsEvent, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
27
30
  import WebSocket from "ws";
28
31
  import { createPersistentDedupeCache } from "openclaw/plugin-sdk/dedupe-runtime";
29
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
30
32
  //#region extensions/mattermost/src/mattermost/directory.ts
31
33
  function buildClient(params) {
32
34
  const account = resolveMattermostAccount({
@@ -368,6 +370,30 @@ function createMattermostDraftStream(params) {
368
370
  };
369
371
  }
370
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
371
397
  //#region extensions/mattermost/src/mattermost/monitor-helpers.ts
372
398
  const formatInboundFromLabel$1 = formatInboundFromLabel;
373
399
  function resolveThreadSessionKeys$1(params) {
@@ -558,398 +584,63 @@ async function deliverMattermostReplyWithDraftPreview(params) {
558
584
  });
559
585
  }
560
586
  //#endregion
561
- //#region extensions/mattermost/src/mattermost/monitor-gating.ts
562
- function mapMattermostChannelTypeToChatType(channelType) {
563
- const normalized = channelType?.trim().toUpperCase();
564
- if (!normalized) return "direct";
565
- if (normalized === "D") return "direct";
566
- if (normalized === "G" || normalized === "P") return "group";
567
- return "channel";
568
- }
569
- function resolveMattermostTrustedChatKind(params) {
570
- const channelType = params.channelType?.trim();
571
- if (channelType) return mapMattermostChannelTypeToChatType(channelType);
572
- return params.fallback ?? "direct";
573
- }
574
- function evaluateMattermostMentionGate(params) {
575
- const shouldRequireMention = params.kind !== "direct" && params.resolveRequireMention({
576
- cfg: params.cfg,
577
- channel: "mattermost",
578
- accountId: params.accountId,
579
- groupId: params.channelId,
580
- requireMentionOverride: params.requireMentionOverride
581
- });
582
- const shouldBypassMention = params.isControlCommand && shouldRequireMention && !params.wasMentioned && params.commandAuthorized;
583
- const effectiveWasMentioned = params.wasMentioned || shouldBypassMention || params.oncharTriggered || params.threadAlreadyEngaged === true;
584
- if (params.oncharEnabled && !params.oncharTriggered && !params.wasMentioned && !params.isControlCommand && params.threadAlreadyEngaged !== true) return {
585
- shouldRequireMention,
586
- shouldBypassMention,
587
- effectiveWasMentioned,
588
- dropReason: "onchar-not-triggered"
589
- };
590
- if (params.kind !== "direct" && shouldRequireMention && params.canDetectMention && !effectiveWasMentioned) return {
591
- shouldRequireMention,
592
- shouldBypassMention,
593
- effectiveWasMentioned,
594
- dropReason: "missing-mention"
595
- };
596
- return {
597
- shouldRequireMention,
598
- shouldBypassMention,
599
- effectiveWasMentioned,
600
- dropReason: null
601
- };
587
+ //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
588
+ const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
589
+ const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
590
+ const MattermostEventPayloadSchema = z.object({
591
+ event: z.string().optional(),
592
+ data: z.object({
593
+ post: z.unknown().optional(),
594
+ reaction: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
595
+ channel_id: z.string().optional(),
596
+ channel_name: z.string().optional(),
597
+ channel_display_name: z.string().optional(),
598
+ channel_type: z.string().optional(),
599
+ sender_name: z.string().optional(),
600
+ team_id: z.string().optional()
601
+ }).optional(),
602
+ broadcast: z.object({
603
+ channel_id: z.string().optional(),
604
+ team_id: z.string().optional(),
605
+ user_id: z.string().optional()
606
+ }).optional()
607
+ });
608
+ function parseMattermostEventPayload(raw) {
609
+ return safeParseJsonWithSchema(MattermostEventPayloadSchema, raw);
602
610
  }
603
- //#endregion
604
- //#region extensions/mattermost/src/mattermost/monitor-onchar.ts
605
- const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
606
- function resolveOncharPrefixes(prefixes) {
607
- const cleaned = prefixes ? normalizeStringEntries(prefixes) : DEFAULT_ONCHAR_PREFIXES;
608
- return cleaned.length > 0 ? cleaned : DEFAULT_ONCHAR_PREFIXES;
611
+ function parseMattermostPost(value) {
612
+ if (typeof value === "string") return safeParseJsonWithSchema(MattermostPostSchema, value);
613
+ return safeParseWithSchema(MattermostPostSchema, value);
609
614
  }
610
- function stripOncharPrefix(text, prefixes) {
611
- const trimmed = text.trimStart();
612
- for (const prefix of prefixes) {
613
- if (!prefix) continue;
614
- if (trimmed.startsWith(prefix)) return {
615
- triggered: true,
616
- stripped: trimmed.slice(prefix.length).trimStart()
617
- };
615
+ var WebSocketClosedBeforeOpenError = class extends Error {
616
+ constructor(code, reason) {
617
+ super(`websocket closed before open (code ${code})`);
618
+ this.code = code;
619
+ this.reason = reason;
620
+ this.name = "WebSocketClosedBeforeOpenError";
618
621
  }
619
- return {
620
- triggered: false,
621
- stripped: text
622
- };
623
- }
624
- //#endregion
625
- //#region extensions/mattermost/src/mattermost/monitor-replay.ts
626
- const RECENT_MATTERMOST_MESSAGE_TTL_MS = 5 * 6e4;
627
- const RECENT_MATTERMOST_MESSAGE_MAX = 2e3;
628
- function buildMattermostInboundReplayKeys(params) {
629
- return params.messageIds.map((id) => id.trim() ? `${params.accountId}:${id.trim()}` : "");
630
- }
631
- function createMattermostInboundReplayGuard() {
632
- return createChannelReplayGuard({
633
- dedupe: {
634
- ttlMs: RECENT_MATTERMOST_MESSAGE_TTL_MS,
635
- memoryMaxSize: RECENT_MATTERMOST_MESSAGE_MAX
636
- },
637
- buildReplayKey: buildMattermostInboundReplayKeys
638
- });
639
- }
640
- const recentInboundMessages = createMattermostInboundReplayGuard();
641
- async function processMattermostReplayGuardedPost(params) {
642
- const replayGuard = params.replayGuard ?? recentInboundMessages;
643
- const event = {
644
- accountId: params.accountId,
645
- messageIds: params.messageIds
646
- };
647
- return (await replayGuard.processGuarded(event, params.handlePost, { onError: "commit" })).kind === "processed" ? "processed" : "duplicate";
648
- }
649
- //#endregion
650
- //#region extensions/mattermost/src/mattermost/monitor-resources.ts
651
- function formatMattermostInboundMediaText(params) {
652
- const unavailableCount = Math.max(0, params.expectedCount - params.mediaCount);
653
- if (unavailableCount === 0) return params.body;
654
- return formatInboundMediaUnavailableText({
655
- body: params.body,
656
- mediaPlaceholder: params.mediaCount === 0 ? params.mediaPlaceholder : void 0,
657
- notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]`
622
+ };
623
+ const defaultMattermostWebSocketFactory = (url, options) => {
624
+ const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
625
+ return new WebSocket(url, {
626
+ ...options,
627
+ ...agent ? { agent } : {}
658
628
  });
659
- }
660
- const CHANNEL_CACHE_TTL_MS = 5 * 6e4;
661
- const USER_CACHE_TTL_MS = 10 * 6e4;
662
- const MONITOR_RESOURCE_CACHE_MAX_ENTRIES = 1e3;
663
- const MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS = 12e4;
664
- const MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS = 3e4;
665
- function createMattermostMonitorResources(params) {
666
- const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
667
- const channelCache = /* @__PURE__ */ new Map();
668
- const userCache = /* @__PURE__ */ new Map();
669
- const getCachedValue = (cache, key, nowMs) => {
670
- const cached = cache.get(key);
671
- if (!cached) return;
672
- if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
673
- cache.delete(key);
674
- };
675
- const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
676
- const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
677
- if (expiresAt !== void 0) {
678
- cache.delete(key);
679
- cache.set(key, {
680
- value,
681
- expiresAt
682
- });
683
- pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
684
- }
685
- };
686
- const resolveMattermostMedia = async (fileIds) => {
687
- const ids = normalizeStringEntries(fileIds ?? []);
688
- if (ids.length === 0) return [];
689
- const out = [];
690
- for (const fileId of ids) try {
691
- const saved = await saveRemoteMedia({
692
- url: `${client.apiBaseUrl}/files/${fileId}`,
693
- requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
694
- filePathHint: fileId,
695
- maxBytes: mediaMaxBytes,
696
- ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] },
697
- responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
698
- readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
699
- });
700
- const contentType = saved.contentType ?? void 0;
701
- out.push({
702
- path: saved.path,
703
- contentType,
704
- kind: mediaKindFromMime(contentType) ?? "unknown"
705
- });
706
- } catch (err) {
707
- logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
708
- }
709
- return out;
710
- };
711
- const sendTypingIndicator = async (channelId, parentId) => {
712
- await sendMattermostTyping(client, {
713
- channelId,
714
- parentId
629
+ };
630
+ function createMattermostConnectOnce(opts) {
631
+ const webSocketFactory = opts.webSocketFactory ?? defaultMattermostWebSocketFactory;
632
+ const healthCheckIntervalMs = opts.healthCheckIntervalMs ?? 3e4;
633
+ const pingIntervalMs = opts.pingIntervalMs ?? 3e4;
634
+ const pongTimeoutMs = opts.pongTimeoutMs ?? 1e4;
635
+ return async () => {
636
+ const flowId = randomUUID();
637
+ const ws = webSocketFactory(opts.wsUrl, {
638
+ maxPayload: MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES,
639
+ handshakeTimeout: MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS
715
640
  });
716
- };
717
- const resolveChannelInfo = async (channelId) => {
718
- const rawNow = Date.now();
719
- const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
720
- if (cached !== void 0) return cached;
721
- try {
722
- const info = await fetchMattermostChannel(client, channelId);
723
- setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
724
- return info;
725
- } catch (err) {
726
- logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
727
- setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
728
- return null;
729
- }
730
- };
731
- const resolveUserInfo = async (userId) => {
732
- const rawNow = Date.now();
733
- const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
734
- if (cached !== void 0) return cached;
735
- try {
736
- const info = await fetchMattermostUser(client, userId);
737
- setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
738
- return info;
739
- } catch (err) {
740
- logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
741
- setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
742
- return null;
743
- }
744
- };
745
- const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
746
- callbackUrl,
747
- accountId,
748
- channelId,
749
- buttons
750
- });
751
- const updateModelPickerPost = async (paramsLocal) => {
752
- const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
753
- await updateMattermostPost(client, paramsLocal.postId, {
754
- message: paramsLocal.message,
755
- props
756
- });
757
- return {};
758
- };
759
- return {
760
- resolveMattermostMedia,
761
- sendTypingIndicator,
762
- resolveChannelInfo,
763
- resolveUserInfo,
764
- updateModelPickerPost
765
- };
766
- }
767
- //#endregion
768
- //#region extensions/mattermost/src/mattermost/monitor-slash.ts
769
- function buildSlashCommands(params) {
770
- const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
771
- if (!params.nativeSkills) return commandsToRegister;
772
- try {
773
- const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
774
- for (const spec of skillCommands) {
775
- const name = typeof spec.name === "string" ? spec.name.trim() : "";
776
- if (!name) continue;
777
- const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
778
- commandsToRegister.push({
779
- trigger,
780
- description: spec.description || `Run skill ${name}`,
781
- autoComplete: true,
782
- autoCompleteHint: "[args]",
783
- originalName: name
784
- });
785
- }
786
- } catch (err) {
787
- params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
788
- }
789
- return commandsToRegister;
790
- }
791
- function dedupeSlashCommands(commands) {
792
- const seen = /* @__PURE__ */ new Set();
793
- return commands.filter((cmd) => {
794
- const key = cmd.trigger.trim();
795
- if (!key || seen.has(key)) return false;
796
- seen.add(key);
797
- return true;
798
- });
799
- }
800
- function buildTriggerMap(commands) {
801
- const triggerMap = /* @__PURE__ */ new Map();
802
- for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
803
- return triggerMap;
804
- }
805
- function warnOnSuspiciousCallbackUrl(params) {
806
- try {
807
- const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
808
- const callbackHost = new URL(params.callbackUrl).hostname;
809
- 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).`);
810
- } catch {}
811
- }
812
- async function registerSlashCommandsAcrossTeams(params) {
813
- const registered = [];
814
- let teamRegistrationFailures = 0;
815
- for (const team of params.teams) try {
816
- const created = await registerSlashCommands({
817
- client: params.client,
818
- teamId: team.id,
819
- creatorUserId: params.botUserId,
820
- callbackUrl: params.callbackUrl,
821
- commands: params.commands,
822
- log: (msg) => params.runtime.log?.(msg)
823
- });
824
- registered.push(...created);
825
- } catch (err) {
826
- teamRegistrationFailures += 1;
827
- params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
828
- }
829
- return {
830
- registered,
831
- teamRegistrationFailures
832
- };
833
- }
834
- async function registerMattermostMonitorSlashCommands(params) {
835
- const commandsRaw = params.account.config.commands;
836
- const slashConfig = resolveSlashCommandConfig(commandsRaw);
837
- if (!isSlashCommandsEnabled(slashConfig)) return;
838
- try {
839
- const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
840
- const slashCallbackUrl = resolveCallbackUrl({
841
- config: slashConfig,
842
- gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
843
- gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
844
- });
845
- warnOnSuspiciousCallbackUrl({
846
- runtime: params.runtime,
847
- baseUrl: params.baseUrl,
848
- callbackUrl: slashCallbackUrl
849
- });
850
- const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
851
- cfg: params.cfg,
852
- runtime: params.runtime,
853
- nativeSkills: slashConfig.nativeSkills === true
854
- }));
855
- const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
856
- client: params.client,
857
- teams,
858
- botUserId: params.botUserId,
859
- callbackUrl: slashCallbackUrl,
860
- commands: dedupedCommands,
861
- runtime: params.runtime
862
- });
863
- if (registered.length === 0) {
864
- params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
865
- return;
866
- }
867
- if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
868
- activateSlashCommands({
869
- account: params.account,
870
- commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
871
- registeredCommands: registered,
872
- triggerMap: buildTriggerMap(dedupedCommands),
873
- api: {
874
- cfg: params.cfg,
875
- runtime: params.runtime
876
- },
877
- log: (msg) => params.runtime.log?.(msg)
878
- });
879
- params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
880
- } catch (err) {
881
- params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
882
- }
883
- }
884
- //#endregion
885
- //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
886
- const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
887
- const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
888
- const MattermostEventPayloadSchema = z.object({
889
- event: z.string().optional(),
890
- data: z.object({
891
- post: z.union([z.string(), MattermostPostSchema]).optional(),
892
- reaction: z.union([z.string(), z.record(z.string(), z.unknown())]).optional(),
893
- channel_id: z.string().optional(),
894
- channel_name: z.string().optional(),
895
- channel_display_name: z.string().optional(),
896
- channel_type: z.string().optional(),
897
- sender_name: z.string().optional(),
898
- team_id: z.string().optional()
899
- }).optional(),
900
- broadcast: z.object({
901
- channel_id: z.string().optional(),
902
- team_id: z.string().optional(),
903
- user_id: z.string().optional()
904
- }).optional()
905
- });
906
- function parseMattermostEventPayload(raw) {
907
- return safeParseJsonWithSchema(MattermostEventPayloadSchema, raw);
908
- }
909
- function parseMattermostPost(value) {
910
- if (typeof value === "string") return safeParseJsonWithSchema(MattermostPostSchema, value);
911
- return safeParseWithSchema(MattermostPostSchema, value);
912
- }
913
- var WebSocketClosedBeforeOpenError = class extends Error {
914
- constructor(code, reason) {
915
- super(`websocket closed before open (code ${code})`);
916
- this.code = code;
917
- this.reason = reason;
918
- this.name = "WebSocketClosedBeforeOpenError";
919
- }
920
- };
921
- const defaultMattermostWebSocketFactory = (url, options) => {
922
- const agent = createDebugProxyWebSocketAgent(resolveDebugProxySettings());
923
- return new WebSocket(url, {
924
- ...options,
925
- ...agent ? { agent } : {}
926
- });
927
- };
928
- function parsePostedPayload(payload) {
929
- if (payload.event !== "posted") return null;
930
- const postData = payload.data?.post;
931
- if (!postData) return null;
932
- const post = parseMattermostPost(postData);
933
- if (!post) return null;
934
- return {
935
- payload,
936
- post
937
- };
938
- }
939
- function createMattermostConnectOnce(opts) {
940
- const webSocketFactory = opts.webSocketFactory ?? defaultMattermostWebSocketFactory;
941
- const healthCheckIntervalMs = opts.healthCheckIntervalMs ?? 3e4;
942
- const pingIntervalMs = opts.pingIntervalMs ?? 3e4;
943
- const pongTimeoutMs = opts.pongTimeoutMs ?? 1e4;
944
- return async () => {
945
- const flowId = randomUUID();
946
- const ws = webSocketFactory(opts.wsUrl, {
947
- maxPayload: MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES,
948
- handshakeTimeout: MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS
949
- });
950
- const onAbort = () => ws.terminate();
951
- opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
952
- const getBotUpdateAt = opts.getBotUpdateAt;
641
+ const onAbort = () => ws.terminate();
642
+ opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
643
+ const getBotUpdateAt = opts.getBotUpdateAt;
953
644
  try {
954
645
  return await new Promise((resolve, reject) => {
955
646
  let opened = false;
@@ -1099,7 +790,8 @@ function createMattermostConnectOnce(opts) {
1099
790
  payload: Buffer.from(rawDataToString(data)),
1100
791
  meta: { subsystem: "mattermost-websocket" }
1101
792
  });
1102
- const payload = parseMattermostEventPayload(rawDataToString(data));
793
+ const raw = rawDataToString(data);
794
+ const payload = parseMattermostEventPayload(raw);
1103
795
  if (!payload) return;
1104
796
  if (payload.event === "reaction_added" || payload.event === "reaction_removed") {
1105
797
  if (!opts.onReaction) return;
@@ -1111,12 +803,11 @@ function createMattermostConnectOnce(opts) {
1111
803
  return;
1112
804
  }
1113
805
  if (payload.event !== "posted") return;
1114
- const parsed = parsePostedPayload(payload);
1115
- if (!parsed) return;
1116
806
  try {
1117
- await opts.onPosted(parsed.post, parsed.payload);
807
+ await opts.onPosted(raw);
1118
808
  } catch (err) {
1119
- opts.runtime.error?.(`mattermost handler failed: ${String(err)}`);
809
+ opts.runtime.error?.(`mattermost durable admission failed; terminating websocket: ${String(err)}`);
810
+ ws.terminate();
1120
811
  }
1121
812
  });
1122
813
  ws.on("close", (code, reason) => {
@@ -1172,102 +863,592 @@ function reasonToString(reason) {
1172
863
  return reason.length > 0 ? reason.toString("utf8") : "";
1173
864
  }
1174
865
  //#endregion
1175
- //#region extensions/mattermost/src/mattermost/reconnect.ts
1176
- /**
1177
- * Reconnection loop with exponential backoff.
1178
- *
1179
- * Calls `connectFn` in a while loop. On normal resolve (connection closed),
1180
- * the backoff resets. On thrown error (connection failed), the current delay is
1181
- * used, then doubled for the next retry.
1182
- * The loop exits when `abortSignal` fires.
1183
- */
1184
- async function runWithReconnect(connectFn, opts = {}) {
1185
- const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
1186
- const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
1187
- const random = opts.random ?? Math.random;
1188
- const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
1189
- let attempt = 0;
1190
- while (!opts.abortSignal?.aborted) {
1191
- let outcome = "resolved";
1192
- let error;
1193
- try {
1194
- await connectFn();
1195
- backoff.reset();
1196
- } catch (err) {
1197
- if (opts.abortSignal?.aborted) return;
1198
- outcome = "rejected";
1199
- error = err;
1200
- opts.onError?.(err);
866
+ //#region extensions/mattermost/src/mattermost/monitor-ingress.ts
867
+ const MATTERMOST_INGRESS_PAYLOAD_VERSION = 1;
868
+ 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();
1201
909
  }
1202
- if (opts.abortSignal?.aborted) return;
1203
- const delayMs = withJitter(backoff.current(), jitterRatio, random);
1204
- if (!(opts.shouldReconnect?.({
1205
- attempt,
1206
- delayMs,
1207
- outcome,
1208
- error
1209
- }) ?? true)) return;
1210
- opts.onReconnect?.(delayMs);
1211
- await sleepAbortable(delayMs, opts.abortSignal);
1212
- if (outcome === "rejected") backoff.increase();
1213
- attempt++;
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";
1214
917
  }
918
+ };
919
+ function isRecord(value) {
920
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1215
921
  }
1216
- function createReconnectBackoff(initialDelayMs, maxDelayMs) {
1217
- let retryDelay = initialDelayMs;
922
+ function parseRawObject(raw, subject) {
923
+ let parsed;
924
+ try {
925
+ parsed = JSON.parse(raw);
926
+ } catch (error) {
927
+ throw new MattermostIngressPermanentError("invalid-event", `${subject} contains invalid JSON.`, { cause: error });
928
+ }
929
+ if (!isRecord(parsed)) throw new MattermostIngressPermanentError("invalid-event", `${subject} must be a JSON object.`);
930
+ return parsed;
931
+ }
932
+ function parseRawPost(value) {
933
+ if (typeof value === "string") return parseRawObject(value, "Mattermost posted event post");
934
+ if (isRecord(value)) return value;
935
+ throw new MattermostIngressPermanentError("invalid-event", "Mattermost posted event is missing its post object.");
936
+ }
937
+ function requiredString(value, field) {
938
+ if (typeof value === "string" && value.trim()) return value.trim();
939
+ throw new MattermostIngressPermanentError("invalid-event", `Mattermost posted event is missing ${field}.`);
940
+ }
941
+ function inspectMattermostIngressEvent(rawEvent) {
942
+ const envelope = parseRawObject(rawEvent, "Mattermost WebSocket event");
943
+ if (envelope.event !== "posted") return null;
944
+ const data = isRecord(envelope.data) ? envelope.data : null;
945
+ const post = parseRawPost(data?.post);
946
+ const eventId = requiredString(post.id, "post.id");
947
+ const broadcast = isRecord(envelope.broadcast) ? envelope.broadcast : null;
1218
948
  return {
1219
- current: () => retryDelay,
1220
- reset: () => {
1221
- retryDelay = initialDelayMs;
1222
- },
1223
- increase: () => {
1224
- retryDelay = Math.min(retryDelay * 2, maxDelayMs);
1225
- }
949
+ eventId,
950
+ laneKey: `channel:${typeof post.channel_id === "string" && post.channel_id.trim() ? post.channel_id.trim() : typeof data?.channel_id === "string" && data.channel_id.trim() ? data.channel_id.trim() : requiredString(broadcast?.channel_id, "channel_id")}`
1226
951
  };
1227
952
  }
1228
- function withJitter(baseMs, jitterRatio, random) {
1229
- if (jitterRatio <= 0) return baseMs;
1230
- const normalized = Math.max(0, Math.min(1, random()));
1231
- const spread = baseMs * jitterRatio;
1232
- return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
953
+ function parseClaimedEvent(rawEvent, eventId) {
954
+ const payload = parseMattermostEventPayload(rawEvent);
955
+ if (!payload || payload.event !== "posted") throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} is not a posted event.`);
956
+ const post = parseMattermostPost(payload.data?.post);
957
+ const claimedChannelId = post?.channel_id?.trim() || payload.data?.channel_id?.trim() || payload.broadcast?.channel_id?.trim();
958
+ if (!post || post.id !== eventId || !claimedChannelId) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${eventId} has invalid post identity.`);
959
+ return {
960
+ post,
961
+ payload
962
+ };
1233
963
  }
1234
- function sleepAbortable(ms, signal) {
1235
- return new Promise((resolve) => {
1236
- if (signal?.aborted) {
1237
- resolve();
1238
- return;
964
+ function resolveMattermostIngressNonRetryableFailure(error) {
965
+ if (error instanceof MattermostIngressPermanentError) return {
966
+ reason: error.reason,
967
+ message: error.message
968
+ };
969
+ const message = formatErrorMessage(error);
970
+ return /Mattermost API (?:401|403)\b/.test(message) ? {
971
+ reason: "mattermost-auth",
972
+ message
973
+ } : null;
974
+ }
975
+ function createMattermostIngressMonitor(options) {
976
+ let queue = options.queue;
977
+ let drain;
978
+ let running = true;
979
+ let requested = false;
980
+ let pumping;
981
+ let lastPrunedAt = 0;
982
+ const getQueue = () => {
983
+ queue ??= getMattermostRuntime().state.openChannelIngressQueue({ accountId: options.accountId });
984
+ return queue;
985
+ };
986
+ const getDrain = () => {
987
+ drain ??= createChannelIngressDrain({
988
+ queue: getQueue(),
989
+ adoptionStallTimeoutMs: options.adoptionStallTimeoutMs ?? DEFAULT_INGRESS_ADOPTION_STALL_MS,
990
+ retryPolicy: {
991
+ maxAttempts: DEFAULT_INGRESS_RETRY_MAX_ATTEMPTS,
992
+ deadLetterMinAgeMs: DEFAULT_INGRESS_RETRY_DEAD_LETTER_MIN_AGE_MS
993
+ },
994
+ resolveNonRetryableFailure: resolveMattermostIngressNonRetryableFailure,
995
+ ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
996
+ onLog: (message) => options.runtime.log?.(`mattermost ${message}`),
997
+ dispatchClaimedEvent: async (record, lifecycle) => {
998
+ if (record.payload.version !== MATTERMOST_INGRESS_PAYLOAD_VERSION) throw new MattermostIngressPermanentError("invalid-event", `Mattermost ingress row ${record.id} has an unsupported version.`);
999
+ const { post, payload } = parseClaimedEvent(record.payload.rawEvent, record.id);
1000
+ return await options.dispatch(post, payload, lifecycle);
1001
+ }
1002
+ });
1003
+ return drain;
1004
+ };
1005
+ const pruneIfDue = async () => {
1006
+ const now = Date.now();
1007
+ if (now - lastPrunedAt < MATTERMOST_INGRESS_PRUNE_INTERVAL_MS) return;
1008
+ await getQueue().prune({
1009
+ completedTtlMs: MATTERMOST_INGRESS_COMPLETED_TTL_MS,
1010
+ completedMaxEntries: MATTERMOST_INGRESS_COMPLETED_MAX_ENTRIES,
1011
+ failedTtlMs: MATTERMOST_INGRESS_FAILED_TTL_MS,
1012
+ failedMaxEntries: MATTERMOST_INGRESS_FAILED_MAX_ENTRIES,
1013
+ now
1014
+ });
1015
+ lastPrunedAt = now;
1016
+ };
1017
+ const runPump = async () => {
1018
+ try {
1019
+ for (;;) {
1020
+ requested = false;
1021
+ await pruneIfDue();
1022
+ if (!running) break;
1023
+ const activeDrain = getDrain();
1024
+ const { started } = await activeDrain.drainOnce();
1025
+ await activeDrain.waitForIdle();
1026
+ if (!running || !requested && started === 0) break;
1027
+ }
1028
+ } catch (error) {
1029
+ options.runtime.error?.(`mattermost ingress drain failed: ${formatErrorMessage(error)}`);
1030
+ } finally {
1031
+ pumping = void 0;
1032
+ if (running && requested) requestDrain();
1239
1033
  }
1240
- const onAbort = () => {
1241
- clearTimeout(timer);
1242
- resolve();
1243
- };
1244
- const timer = setTimeout(() => {
1245
- signal?.removeEventListener("abort", onAbort);
1246
- resolve();
1247
- }, ms);
1248
- signal?.addEventListener("abort", onAbort, { once: true });
1249
- });
1250
- }
1251
- //#endregion
1252
- //#region extensions/mattermost/src/mattermost/thread-participation.ts
1253
- const threadParticipation = createPersistentDedupeCache({
1254
- globalKey: Symbol.for("openclaw.mattermostThreadParticipation"),
1255
- ttlMs: 10080 * 60 * 1e3,
1256
- maxSize: 5e3,
1257
- persistent: {
1258
- namespace: "mattermost.thread-participation",
1259
- maxEntries: 1e3,
1260
- openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
1261
- logError: (error) => {
1034
+ };
1035
+ const requestDrain = () => {
1036
+ requested = true;
1037
+ if (!running || pumping) return;
1038
+ pumping = runPump();
1039
+ };
1040
+ const timer = setInterval(requestDrain, options.pollIntervalMs ?? MATTERMOST_INGRESS_POLL_INTERVAL_MS);
1041
+ timer.unref?.();
1042
+ requestDrain();
1043
+ let admissionTail = Promise.resolve();
1044
+ const admitOnce = async (rawEvent) => {
1045
+ const facts = inspectMattermostIngressEvent(rawEvent);
1046
+ if (!facts) return;
1047
+ const receivedAt = Date.now();
1048
+ let lastError;
1049
+ for (const delayMs of [
1050
+ 0,
1051
+ 100,
1052
+ 300
1053
+ ]) {
1054
+ if (delayMs > 0) await new Promise((resolve) => {
1055
+ setTimeout(resolve, delayMs);
1056
+ });
1262
1057
  try {
1263
- getOptionalMattermostRuntime()?.logging.getChildLogger({
1264
- plugin: "mattermost",
1265
- feature: "thread-participation-state"
1266
- }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
1267
- } catch {}
1058
+ await getQueue().enqueue(facts.eventId, {
1059
+ version: MATTERMOST_INGRESS_PAYLOAD_VERSION,
1060
+ receivedAt,
1061
+ rawEvent
1062
+ }, {
1063
+ receivedAt,
1064
+ laneKey: facts.laneKey
1065
+ });
1066
+ requestDrain();
1067
+ return;
1068
+ } catch (error) {
1069
+ lastError = error;
1070
+ }
1268
1071
  }
1269
- }
1270
- });
1072
+ throw lastError;
1073
+ };
1074
+ return {
1075
+ receive: (rawEvent) => {
1076
+ const admission = admissionTail.then(() => admitOnce(rawEvent));
1077
+ admissionTail = admission.catch(() => void 0);
1078
+ return admission;
1079
+ },
1080
+ stop: async () => {
1081
+ running = false;
1082
+ clearInterval(timer);
1083
+ await admissionTail;
1084
+ drain?.dispose();
1085
+ await pumping;
1086
+ drain?.dispose();
1087
+ await drain?.waitForIdle();
1088
+ },
1089
+ waitForIdle: async () => {
1090
+ for (;;) {
1091
+ const activePump = pumping;
1092
+ if (!activePump) break;
1093
+ await activePump;
1094
+ }
1095
+ await drain?.waitForIdle();
1096
+ }
1097
+ };
1098
+ }
1099
+ //#endregion
1100
+ //#region extensions/mattermost/src/mattermost/monitor-onchar.ts
1101
+ const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
1102
+ function resolveOncharPrefixes(prefixes) {
1103
+ const cleaned = prefixes ? normalizeStringEntries(prefixes) : DEFAULT_ONCHAR_PREFIXES;
1104
+ return cleaned.length > 0 ? cleaned : DEFAULT_ONCHAR_PREFIXES;
1105
+ }
1106
+ function stripOncharPrefix(text, prefixes) {
1107
+ const trimmed = text.trimStart();
1108
+ for (const prefix of prefixes) {
1109
+ if (!prefix) continue;
1110
+ if (trimmed.startsWith(prefix)) return {
1111
+ triggered: true,
1112
+ stripped: trimmed.slice(prefix.length).trimStart()
1113
+ };
1114
+ }
1115
+ return {
1116
+ triggered: false,
1117
+ stripped: text
1118
+ };
1119
+ }
1120
+ //#endregion
1121
+ //#region extensions/mattermost/src/mattermost/monitor-resources.ts
1122
+ function formatMattermostInboundMediaText(params) {
1123
+ const unavailableCount = Math.max(0, params.expectedCount - params.mediaCount);
1124
+ if (unavailableCount === 0) return params.body;
1125
+ return formatInboundMediaUnavailableText({
1126
+ body: params.body,
1127
+ mediaPlaceholder: params.mediaCount === 0 ? params.mediaPlaceholder : void 0,
1128
+ notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]`
1129
+ });
1130
+ }
1131
+ const CHANNEL_CACHE_TTL_MS = 5 * 6e4;
1132
+ const USER_CACHE_TTL_MS = 10 * 6e4;
1133
+ const MONITOR_RESOURCE_CACHE_MAX_ENTRIES = 1e3;
1134
+ const MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS = 12e4;
1135
+ const MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS = 3e4;
1136
+ function createMattermostMonitorResources(params) {
1137
+ const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
1138
+ const channelCache = /* @__PURE__ */ new Map();
1139
+ const userCache = /* @__PURE__ */ new Map();
1140
+ const getCachedValue = (cache, key, nowMs) => {
1141
+ const cached = cache.get(key);
1142
+ if (!cached) return;
1143
+ if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
1144
+ cache.delete(key);
1145
+ };
1146
+ const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
1147
+ const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
1148
+ if (expiresAt !== void 0) {
1149
+ cache.delete(key);
1150
+ cache.set(key, {
1151
+ value,
1152
+ expiresAt
1153
+ });
1154
+ pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
1155
+ }
1156
+ };
1157
+ const resolveMattermostMedia = async (fileIds) => {
1158
+ const ids = normalizeStringEntries(fileIds ?? []);
1159
+ if (ids.length === 0) return [];
1160
+ const out = [];
1161
+ for (const fileId of ids) try {
1162
+ const saved = await saveRemoteMedia({
1163
+ url: buildMattermostApiUrl(client.baseUrl, `/files/${fileId}`),
1164
+ requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
1165
+ filePathHint: fileId,
1166
+ maxBytes: mediaMaxBytes,
1167
+ ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] },
1168
+ responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
1169
+ readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
1170
+ });
1171
+ const contentType = saved.contentType ?? void 0;
1172
+ out.push({
1173
+ path: saved.path,
1174
+ contentType,
1175
+ kind: mediaKindFromMime(contentType) ?? "unknown"
1176
+ });
1177
+ } catch (err) {
1178
+ logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
1179
+ }
1180
+ return out;
1181
+ };
1182
+ const sendTypingIndicator = async (channelId, parentId) => {
1183
+ await sendMattermostTyping(client, {
1184
+ channelId,
1185
+ parentId
1186
+ });
1187
+ };
1188
+ const resolveChannelInfo = async (channelId) => {
1189
+ const rawNow = Date.now();
1190
+ const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
1191
+ if (cached !== void 0) return cached;
1192
+ try {
1193
+ const info = await fetchMattermostChannel(client, channelId);
1194
+ setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
1195
+ return info;
1196
+ } catch (err) {
1197
+ logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
1198
+ setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
1199
+ return null;
1200
+ }
1201
+ };
1202
+ const resolveUserInfo = async (userId) => {
1203
+ const rawNow = Date.now();
1204
+ const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
1205
+ if (cached !== void 0) return cached;
1206
+ try {
1207
+ const info = await fetchMattermostUser(client, userId);
1208
+ setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
1209
+ return info;
1210
+ } catch (err) {
1211
+ logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
1212
+ setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
1213
+ return null;
1214
+ }
1215
+ };
1216
+ const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
1217
+ callbackUrl,
1218
+ accountId,
1219
+ channelId,
1220
+ buttons
1221
+ });
1222
+ const updateModelPickerPost = async (paramsLocal) => {
1223
+ const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
1224
+ await updateMattermostPost(client, paramsLocal.postId, {
1225
+ message: paramsLocal.message,
1226
+ props
1227
+ });
1228
+ return {};
1229
+ };
1230
+ return {
1231
+ resolveMattermostMedia,
1232
+ sendTypingIndicator,
1233
+ resolveChannelInfo,
1234
+ resolveUserInfo,
1235
+ updateModelPickerPost
1236
+ };
1237
+ }
1238
+ //#endregion
1239
+ //#region extensions/mattermost/src/mattermost/monitor-slash.ts
1240
+ function buildSlashCommands(params) {
1241
+ const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
1242
+ if (!params.nativeSkills) return commandsToRegister;
1243
+ try {
1244
+ const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
1245
+ for (const spec of skillCommands) {
1246
+ const name = typeof spec.name === "string" ? spec.name.trim() : "";
1247
+ if (!name) continue;
1248
+ const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
1249
+ commandsToRegister.push({
1250
+ trigger,
1251
+ description: spec.description || `Run skill ${name}`,
1252
+ autoComplete: true,
1253
+ autoCompleteHint: "[args]",
1254
+ originalName: name
1255
+ });
1256
+ }
1257
+ } catch (err) {
1258
+ params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
1259
+ }
1260
+ return commandsToRegister;
1261
+ }
1262
+ function dedupeSlashCommands(commands) {
1263
+ const seen = /* @__PURE__ */ new Set();
1264
+ return commands.filter((cmd) => {
1265
+ const key = cmd.trigger.trim();
1266
+ if (!key || seen.has(key)) return false;
1267
+ seen.add(key);
1268
+ return true;
1269
+ });
1270
+ }
1271
+ function buildTriggerMap(commands) {
1272
+ const triggerMap = /* @__PURE__ */ new Map();
1273
+ for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
1274
+ return triggerMap;
1275
+ }
1276
+ function warnOnSuspiciousCallbackUrl(params) {
1277
+ try {
1278
+ const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
1279
+ const callbackHost = new URL(params.callbackUrl).hostname;
1280
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${params.callbackUrl} (loopback) while baseUrl is ${params.baseUrl}. This MAY be unreachable depending on your deployment. If native slash commands don't work, set channels.mattermost.commands.callbackUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
1281
+ } catch {}
1282
+ }
1283
+ async function registerSlashCommandsAcrossTeams(params) {
1284
+ const registered = [];
1285
+ let teamRegistrationFailures = 0;
1286
+ for (const team of params.teams) try {
1287
+ const created = await registerSlashCommands({
1288
+ client: params.client,
1289
+ teamId: team.id,
1290
+ creatorUserId: params.botUserId,
1291
+ callbackUrl: params.callbackUrl,
1292
+ commands: params.commands,
1293
+ log: (msg) => params.runtime.log?.(msg)
1294
+ });
1295
+ registered.push(...created);
1296
+ } catch (err) {
1297
+ teamRegistrationFailures += 1;
1298
+ params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
1299
+ }
1300
+ return {
1301
+ registered,
1302
+ teamRegistrationFailures
1303
+ };
1304
+ }
1305
+ async function registerMattermostMonitorSlashCommands(params) {
1306
+ const commandsRaw = params.account.config.commands;
1307
+ const slashConfig = resolveSlashCommandConfig(commandsRaw);
1308
+ if (!isSlashCommandsEnabled(slashConfig)) return;
1309
+ try {
1310
+ const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
1311
+ const slashCallbackUrl = resolveCallbackUrl({
1312
+ config: slashConfig,
1313
+ gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
1314
+ gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
1315
+ });
1316
+ warnOnSuspiciousCallbackUrl({
1317
+ runtime: params.runtime,
1318
+ baseUrl: params.baseUrl,
1319
+ callbackUrl: slashCallbackUrl
1320
+ });
1321
+ const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
1322
+ cfg: params.cfg,
1323
+ runtime: params.runtime,
1324
+ nativeSkills: slashConfig.nativeSkills === true
1325
+ }));
1326
+ const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
1327
+ client: params.client,
1328
+ teams,
1329
+ botUserId: params.botUserId,
1330
+ callbackUrl: slashCallbackUrl,
1331
+ commands: dedupedCommands,
1332
+ runtime: params.runtime
1333
+ });
1334
+ if (registered.length === 0) {
1335
+ params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
1336
+ return;
1337
+ }
1338
+ if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
1339
+ activateSlashCommands({
1340
+ account: params.account,
1341
+ commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
1342
+ registeredCommands: registered,
1343
+ triggerMap: buildTriggerMap(dedupedCommands),
1344
+ api: {
1345
+ cfg: params.cfg,
1346
+ runtime: params.runtime
1347
+ },
1348
+ log: (msg) => params.runtime.log?.(msg)
1349
+ });
1350
+ params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
1351
+ } catch (err) {
1352
+ params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
1353
+ }
1354
+ }
1355
+ //#endregion
1356
+ //#region extensions/mattermost/src/mattermost/reconnect.ts
1357
+ /**
1358
+ * Reconnection loop with exponential backoff.
1359
+ *
1360
+ * Calls `connectFn` in a while loop. On normal resolve (connection closed),
1361
+ * the backoff resets. On thrown error (connection failed), the current delay is
1362
+ * used, then doubled for the next retry.
1363
+ * The loop exits when `abortSignal` fires.
1364
+ */
1365
+ async function runWithReconnect(connectFn, opts = {}) {
1366
+ const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
1367
+ const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
1368
+ const random = opts.random ?? Math.random;
1369
+ const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
1370
+ let attempt = 0;
1371
+ while (!opts.abortSignal?.aborted) {
1372
+ let outcome = "resolved";
1373
+ let error;
1374
+ try {
1375
+ await connectFn();
1376
+ backoff.reset();
1377
+ } catch (err) {
1378
+ if (opts.abortSignal?.aborted) return;
1379
+ outcome = "rejected";
1380
+ error = err;
1381
+ opts.onError?.(err);
1382
+ }
1383
+ if (opts.abortSignal?.aborted) return;
1384
+ const delayMs = withJitter(backoff.current(), jitterRatio, random);
1385
+ if (!(opts.shouldReconnect?.({
1386
+ attempt,
1387
+ delayMs,
1388
+ outcome,
1389
+ error
1390
+ }) ?? true)) return;
1391
+ opts.onReconnect?.(delayMs);
1392
+ await sleepAbortable(delayMs, opts.abortSignal);
1393
+ if (outcome === "rejected") backoff.increase();
1394
+ attempt++;
1395
+ }
1396
+ }
1397
+ function createReconnectBackoff(initialDelayMs, maxDelayMs) {
1398
+ let retryDelay = initialDelayMs;
1399
+ return {
1400
+ current: () => retryDelay,
1401
+ reset: () => {
1402
+ retryDelay = initialDelayMs;
1403
+ },
1404
+ increase: () => {
1405
+ retryDelay = Math.min(retryDelay * 2, maxDelayMs);
1406
+ }
1407
+ };
1408
+ }
1409
+ function withJitter(baseMs, jitterRatio, random) {
1410
+ if (jitterRatio <= 0) return baseMs;
1411
+ const normalized = Math.max(0, Math.min(1, random()));
1412
+ const spread = baseMs * jitterRatio;
1413
+ return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
1414
+ }
1415
+ function sleepAbortable(ms, signal) {
1416
+ return new Promise((resolve) => {
1417
+ if (signal?.aborted) {
1418
+ resolve();
1419
+ return;
1420
+ }
1421
+ const onAbort = () => {
1422
+ clearTimeout(timer);
1423
+ resolve();
1424
+ };
1425
+ const timer = setTimeout(() => {
1426
+ signal?.removeEventListener("abort", onAbort);
1427
+ resolve();
1428
+ }, ms);
1429
+ signal?.addEventListener("abort", onAbort, { once: true });
1430
+ });
1431
+ }
1432
+ //#endregion
1433
+ //#region extensions/mattermost/src/mattermost/thread-participation.ts
1434
+ const threadParticipation = createPersistentDedupeCache({
1435
+ globalKey: Symbol.for("openclaw.mattermostThreadParticipation"),
1436
+ ttlMs: 10080 * 60 * 1e3,
1437
+ maxSize: 5e3,
1438
+ persistent: {
1439
+ namespace: "mattermost.thread-participation",
1440
+ maxEntries: 1e3,
1441
+ openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
1442
+ logError: (error) => {
1443
+ try {
1444
+ getOptionalMattermostRuntime()?.logging.getChildLogger({
1445
+ plugin: "mattermost",
1446
+ feature: "thread-participation-state"
1447
+ }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
1448
+ } catch {}
1449
+ }
1450
+ }
1451
+ });
1271
1452
  function makeKey(accountId, channelId, threadRootId) {
1272
1453
  return `${accountId}:${channelId}:${threadRootId}`;
1273
1454
  }
@@ -1507,7 +1688,7 @@ async function monitorMattermostProvider(opts = {}) {
1507
1688
  });
1508
1689
  const to = kind === "direct" ? `user:${optsLocal.userId}` : `channel:${optsLocal.channelId}`;
1509
1690
  const bodyText = `[Button click: user @${optsLocal.userName} selected "${optsLocal.actionName}"]`;
1510
- const ctxPayload = core.channel.reply.finalizeInboundContext({
1691
+ const ctxPayload = finalizeInboundContext({
1511
1692
  Body: bodyText,
1512
1693
  BodyForAgent: bodyText,
1513
1694
  RawBody: bodyText,
@@ -1515,6 +1696,7 @@ async function monitorMattermostProvider(opts = {}) {
1515
1696
  From: kind === "direct" ? `mattermost:${optsLocal.userId}` : kind === "group" ? `mattermost:group:${optsLocal.channelId}` : `mattermost:channel:${optsLocal.channelId}`,
1516
1697
  To: to,
1517
1698
  SessionKey: threadContext.sessionKey,
1699
+ DmScope: route.dmScope,
1518
1700
  ParentSessionKey: threadContext.parentSessionKey,
1519
1701
  AccountId: route.accountId,
1520
1702
  ChatType: chatType,
@@ -1561,51 +1743,43 @@ async function monitorMattermostProvider(opts = {}) {
1561
1743
  isDirect: kind === "direct",
1562
1744
  dmRetryOptions: account.config.dmChannelRetry
1563
1745
  });
1564
- const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
1565
- ...replyPipeline,
1566
- resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1567
- onDeliverySettled: deliveryBarrier.markDeliverySettled,
1568
- humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
1569
- deliver: async (payload) => {
1570
- await deliverMattermostReplyPayload({
1571
- core,
1572
- cfg,
1573
- payload,
1574
- to,
1575
- accountId: account.accountId,
1576
- agentId: route.agentId,
1577
- replyToId: resolveMattermostReplyRootId({
1578
- kind,
1579
- threadRootId: threadContext.effectiveReplyToId,
1580
- replyToId: payload.replyToId
1581
- }),
1582
- textLimit,
1583
- tableMode,
1584
- sendMessage: sendMessageMattermost,
1585
- onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1586
- });
1587
- runtime.log?.(`delivered button-click reply to ${to}`);
1588
- },
1589
- onError: (err, info) => {
1590
- runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
1591
- },
1592
- onReplyStart: typingCallbacks?.onReplyStart
1593
- });
1594
- await core.channel.reply.withReplyDispatcher({
1595
- dispatcher,
1596
- onSettled: () => {
1597
- markDispatchIdle();
1746
+ await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1747
+ ctx: ctxPayload,
1748
+ cfg,
1749
+ dispatcherOptions: {
1750
+ ...replyPipeline,
1751
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1752
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1753
+ humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
1754
+ deliver: async (payload) => {
1755
+ await deliverMattermostReplyPayload({
1756
+ core,
1757
+ cfg,
1758
+ payload,
1759
+ to,
1760
+ accountId: account.accountId,
1761
+ agentId: route.agentId,
1762
+ replyToId: resolveMattermostReplyRootId({
1763
+ kind,
1764
+ threadRootId: threadContext.effectiveReplyToId,
1765
+ replyToId: payload.replyToId
1766
+ }),
1767
+ textLimit,
1768
+ tableMode,
1769
+ sendMessage: sendMessageMattermost,
1770
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1771
+ });
1772
+ runtime.log?.(`delivered button-click reply to ${to}`);
1773
+ },
1774
+ onError: (err, info) => {
1775
+ runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
1776
+ },
1777
+ typingCallbacks
1598
1778
  },
1599
- run: () => core.channel.reply.dispatchReplyFromConfig({
1600
- ctx: ctxPayload,
1601
- cfg,
1602
- dispatcher,
1603
- replyOptions: {
1604
- ...replyOptions,
1605
- disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1606
- onModelSelected
1607
- }
1608
- })
1779
+ replyOptions: {
1780
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1781
+ onModelSelected
1782
+ }
1609
1783
  });
1610
1784
  },
1611
1785
  log: (msg) => runtime.log?.(msg)
@@ -1652,7 +1826,7 @@ async function monitorMattermostProvider(opts = {}) {
1652
1826
  const runModelPickerCommand = async (params) => {
1653
1827
  const to = params.kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
1654
1828
  const fromLabel = params.kind === "direct" ? `Mattermost DM from ${params.senderName}` : `Mattermost message in ${params.roomLabel} from ${params.senderName}`;
1655
- const ctxPayload = core.channel.reply.finalizeInboundContext({
1829
+ const ctxPayload = finalizeInboundContext({
1656
1830
  Body: params.commandText,
1657
1831
  BodyForAgent: params.commandText,
1658
1832
  RawBody: params.commandText,
@@ -1660,6 +1834,7 @@ async function monitorMattermostProvider(opts = {}) {
1660
1834
  From: params.kind === "direct" ? `mattermost:${params.senderId}` : params.kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
1661
1835
  To: to,
1662
1836
  SessionKey: params.sessionKey,
1837
+ DmScope: params.route.dmScope,
1663
1838
  ParentSessionKey: params.parentSessionKey,
1664
1839
  AccountId: params.route.accountId,
1665
1840
  ChatType: params.chatType,
@@ -1710,57 +1885,49 @@ async function monitorMattermostProvider(opts = {}) {
1710
1885
  isDirect: params.kind === "direct",
1711
1886
  dmRetryOptions: account.config.dmChannelRetry
1712
1887
  });
1713
- const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
1714
- ...replyPipeline,
1715
- resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1716
- onDeliverySettled: deliveryBarrier.markDeliverySettled,
1717
- deliver: async (payload) => {
1718
- const trimmedPayload = {
1719
- ...payload,
1720
- text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
1721
- };
1722
- if (!shouldDeliverReplies) {
1723
- if (trimmedPayload.text) capturedTexts.push(trimmedPayload.text);
1724
- return;
1725
- }
1726
- await deliverMattermostReplyPayload({
1727
- core,
1728
- cfg,
1729
- payload: trimmedPayload,
1730
- to,
1731
- accountId: account.accountId,
1732
- agentId: params.route.agentId,
1733
- replyToId: resolveMattermostReplyRootId({
1734
- kind: params.kind,
1735
- threadRootId: params.effectiveReplyToId,
1736
- replyToId: trimmedPayload.replyToId
1737
- }),
1738
- textLimit,
1739
- tableMode: "off",
1740
- sendMessage: sendMessageMattermost,
1741
- onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1742
- });
1743
- },
1744
- onError: (err, info) => {
1745
- runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
1746
- },
1747
- onReplyStart: typingCallbacks?.onReplyStart
1748
- });
1749
- await core.channel.reply.withReplyDispatcher({
1750
- dispatcher,
1751
- onSettled: () => {
1752
- markDispatchIdle();
1888
+ await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1889
+ ctx: ctxPayload,
1890
+ cfg,
1891
+ dispatcherOptions: {
1892
+ ...replyPipeline,
1893
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1894
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1895
+ deliver: async (payload) => {
1896
+ const trimmedPayload = {
1897
+ ...payload,
1898
+ text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
1899
+ };
1900
+ if (!shouldDeliverReplies) {
1901
+ if (trimmedPayload.text) capturedTexts.push(trimmedPayload.text);
1902
+ return;
1903
+ }
1904
+ await deliverMattermostReplyPayload({
1905
+ core,
1906
+ cfg,
1907
+ payload: trimmedPayload,
1908
+ to,
1909
+ accountId: account.accountId,
1910
+ agentId: params.route.agentId,
1911
+ replyToId: resolveMattermostReplyRootId({
1912
+ kind: params.kind,
1913
+ threadRootId: params.effectiveReplyToId,
1914
+ replyToId: trimmedPayload.replyToId
1915
+ }),
1916
+ textLimit,
1917
+ tableMode: "off",
1918
+ sendMessage: sendMessageMattermost,
1919
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1920
+ });
1921
+ },
1922
+ onError: (err, info) => {
1923
+ runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
1924
+ },
1925
+ typingCallbacks
1753
1926
  },
1754
- run: () => core.channel.reply.dispatchReplyFromConfig({
1755
- ctx: ctxPayload,
1756
- cfg,
1757
- dispatcher,
1758
- replyOptions: {
1759
- ...replyOptions,
1760
- disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1761
- onModelSelected
1762
- }
1763
- })
1927
+ replyOptions: {
1928
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1929
+ onModelSelected
1930
+ }
1764
1931
  });
1765
1932
  return capturedTexts.join("\n\n").trim();
1766
1933
  };
@@ -1925,644 +2092,626 @@ async function monitorMattermostProvider(opts = {}) {
1925
2092
  })();
1926
2093
  return {};
1927
2094
  }
1928
- const handlePost = async (post, payload, messageIds) => {
2095
+ const handlePost = async (post, payload, turnAdoptionLifecycle, messageIds) => {
1929
2096
  const channelId = post.channel_id ?? payload.data?.channel_id ?? payload.broadcast?.channel_id;
1930
2097
  if (!channelId) {
1931
2098
  logVerboseMessage("mattermost: drop post (missing channel id)");
1932
2099
  return;
1933
2100
  }
1934
- const allMessageIds = messageIds?.length ? messageIds : post.id ? [post.id] : [];
1935
- if (allMessageIds.length === 0) {
1936
- logVerboseMessage("mattermost: drop post (missing message id)");
2101
+ if (!post.id) {
2102
+ logVerboseMessage("mattermost: drop post (missing message id)");
2103
+ return;
2104
+ }
2105
+ const allMessageIds = messageIds?.length ? messageIds : [post.id];
2106
+ const senderId = post.user_id ?? payload.broadcast?.user_id;
2107
+ if (!senderId) {
2108
+ logVerboseMessage("mattermost: drop post (missing sender id)");
2109
+ return;
2110
+ }
2111
+ if (senderId === botUserId) {
2112
+ logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
2113
+ return;
2114
+ }
2115
+ if (isSystemPost(post)) {
2116
+ logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
2117
+ return;
2118
+ }
2119
+ const channelInfo = await resolveChannelInfo(channelId);
2120
+ const channelType = normalizeOptionalString(channelInfo?.type) ?? normalizeOptionalString(payload.data?.channel_type);
2121
+ if (!channelType) {
2122
+ logVerboseMessage(`mattermost: drop post (cannot resolve channel type for ${channelId})`);
2123
+ return;
2124
+ }
2125
+ const kind = resolveMattermostTrustedChatKind({ channelType });
2126
+ const chatType = channelChatType(kind);
2127
+ const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
2128
+ const rawPostText = typeof post.message === "string" ? post.message : "";
2129
+ const rawText = normalizeOptionalString(rawPostText) ?? "";
2130
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
2131
+ cfg,
2132
+ surface: "mattermost"
2133
+ });
2134
+ const isControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(rawText, cfg);
2135
+ const accessDecision = await resolveMattermostMonitorInboundAccess({
2136
+ account,
2137
+ cfg,
2138
+ senderId,
2139
+ senderName,
2140
+ channelId,
2141
+ kind,
2142
+ groupPolicy,
2143
+ readStoreAllowFrom: pairing.readAllowFromStore,
2144
+ allowTextCommands,
2145
+ hasControlCommand: isControlCommand,
2146
+ eventKind: "message",
2147
+ mayPair: true
2148
+ });
2149
+ const commandAuthorized = accessDecision.commandAccess.authorized;
2150
+ if (accessDecision.ingress.decision !== "allow") {
2151
+ if (kind === "direct") {
2152
+ if (accessDecision.ingress.reasonCode === "dm_policy_disabled") {
2153
+ logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
2154
+ return;
2155
+ }
2156
+ if (accessDecision.ingress.decision === "pairing") {
2157
+ const { code, created } = await pairing.upsertPairingRequest({
2158
+ id: senderId,
2159
+ meta: { name: senderName }
2160
+ });
2161
+ logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
2162
+ if (created) try {
2163
+ await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
2164
+ channel: "mattermost",
2165
+ idLine: `Your Mattermost user id: ${senderId}`,
2166
+ code
2167
+ }), {
2168
+ cfg,
2169
+ accountId: account.accountId
2170
+ });
2171
+ opts.statusSink?.({ lastOutboundAt: Date.now() });
2172
+ } catch (err) {
2173
+ logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
2174
+ }
2175
+ return;
2176
+ }
2177
+ logVerboseMessage(formatMattermostDirectMessageDropLog({
2178
+ senderId,
2179
+ dmPolicy,
2180
+ reasonCode: accessDecision.senderAccess.reasonCode
2181
+ }));
2182
+ return;
2183
+ }
2184
+ if (accessDecision.ingress.reasonCode === "group_policy_disabled") {
2185
+ logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
2186
+ return;
2187
+ }
2188
+ if (accessDecision.ingress.reasonCode === "group_policy_empty_allowlist") {
2189
+ logVerboseMessage("mattermost: drop group message (no group allowlist)");
2190
+ return;
2191
+ }
2192
+ if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
2193
+ logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
2194
+ return;
2195
+ }
2196
+ logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
2197
+ return;
2198
+ }
2199
+ if (kind !== "direct" && accessDecision.commandAccess.shouldBlockControlCommand) {
2200
+ logInboundDrop({
2201
+ log: logVerboseMessage,
2202
+ channel: "mattermost",
2203
+ reason: "control command (unauthorized)",
2204
+ target: senderId
2205
+ });
2206
+ return;
2207
+ }
2208
+ const teamId = payload.data?.team_id ?? channelInfo?.team_id ?? void 0;
2209
+ const channelName = payload.data?.channel_name ?? channelInfo?.name ?? "";
2210
+ const channelDisplay = payload.data?.channel_display_name ?? channelInfo?.display_name ?? channelName;
2211
+ const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${channelId}`;
2212
+ const route = core.channel.routing.resolveAgentRoute({
2213
+ cfg,
2214
+ channel: "mattermost",
2215
+ accountId: account.accountId,
2216
+ teamId,
2217
+ peer: {
2218
+ kind,
2219
+ id: kind === "direct" ? senderId : channelId
2220
+ }
2221
+ });
2222
+ const baseSessionKey = route.sessionKey;
2223
+ const threadRootId = normalizeOptionalString(post.root_id);
2224
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
2225
+ const { effectiveReplyToId, sessionKey, parentSessionKey } = resolveMattermostThreadSessionContext({
2226
+ baseSessionKey,
2227
+ kind,
2228
+ postId: post.id,
2229
+ replyToMode,
2230
+ threadRootId
2231
+ });
2232
+ const historyKey = resolveMattermostPendingHistoryKey({
2233
+ kind,
2234
+ sessionKey
2235
+ });
2236
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
2237
+ const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
2238
+ const pendingBody = rawText || (post.file_ids?.length ? `[Mattermost ${post.file_ids.length === 1 ? "file" : "files"}]` : "");
2239
+ const pendingSender = senderName;
2240
+ const recordPendingHistory = () => {
2241
+ const trimmed = pendingBody.trim();
2242
+ createChannelHistoryWindow({ historyMap: channelHistories }).record({
2243
+ limit: historyLimit,
2244
+ historyKey: historyKey ?? "",
2245
+ entry: historyKey && trimmed ? {
2246
+ sender: pendingSender,
2247
+ body: trimmed,
2248
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2249
+ messageId: post.id ?? void 0
2250
+ } : null
2251
+ });
2252
+ };
2253
+ const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
2254
+ const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
2255
+ const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
2256
+ triggered: false,
2257
+ stripped: rawText
2258
+ };
2259
+ const oncharTriggered = oncharResult.triggered;
2260
+ const canDetectMention = Boolean(botUsername) || mentionRegexes.length > 0;
2261
+ const threadAlreadyEngaged = kind !== "direct" && effectiveReplyToId ? await hasMattermostThreadParticipationWithPersistence({
2262
+ accountId: account.accountId,
2263
+ channelId,
2264
+ threadRootId: effectiveReplyToId
2265
+ }) : false;
2266
+ const shouldRequireMention = kind !== "direct" && core.channel.groups.resolveRequireMention({
2267
+ cfg,
2268
+ channel: "mattermost",
2269
+ accountId: account.accountId,
2270
+ groupId: channelId,
2271
+ requireMentionOverride: account.requireMention
2272
+ });
2273
+ const implicitMentionKinds = implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged);
2274
+ const mentionDecision = resolveMattermostInboundMentionDecision({
2275
+ cfg,
2276
+ accountId: account.accountId,
2277
+ kind,
2278
+ requireMention: shouldRequireMention || oncharEnabled,
2279
+ canDetectMention: canDetectMention || oncharEnabled,
2280
+ wasMentioned: wasMentioned || oncharTriggered,
2281
+ implicitMentionKinds,
2282
+ allowTextCommands,
2283
+ hasControlCommand: isControlCommand,
2284
+ commandAuthorized
2285
+ });
2286
+ const { shouldBypassMention } = mentionDecision;
2287
+ if (mentionDecision.shouldSkip && oncharEnabled && !oncharTriggered && !wasMentioned && !shouldBypassMention) {
2288
+ logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
2289
+ recordPendingHistory();
2290
+ return;
2291
+ }
2292
+ if (mentionDecision.shouldSkip) {
2293
+ logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
2294
+ recordPendingHistory();
2295
+ return;
2296
+ }
2297
+ const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2298
+ const mediaList = await resolveMattermostMedia(fileIds);
2299
+ const mediaPlaceholder = buildMattermostAttachmentPlaceholder(mediaList);
2300
+ const bodyText = normalizeMention(formatMattermostInboundMediaText({
2301
+ body: [oncharTriggered ? oncharResult.stripped : rawText, mediaPlaceholder].filter(Boolean).join("\n").trim(),
2302
+ mediaPlaceholder,
2303
+ expectedCount: fileIds.length,
2304
+ mediaCount: mediaList.length
2305
+ }), botUsername);
2306
+ if (shouldDropEmptyMattermostBody({
2307
+ bodyText,
2308
+ rawText: rawPostText,
2309
+ botUsername
2310
+ })) {
2311
+ logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
1937
2312
  return;
1938
2313
  }
1939
- if (await processMattermostReplayGuardedPost({
2314
+ const bodyForAgent = bodyText || rawText.trim();
2315
+ core.channel.activity.record({
2316
+ channel: "mattermost",
1940
2317
  accountId: account.accountId,
1941
- messageIds: allMessageIds,
1942
- handlePost: async () => {
1943
- const senderId = post.user_id ?? payload.broadcast?.user_id;
1944
- if (!senderId) {
1945
- logVerboseMessage("mattermost: drop post (missing sender id)");
1946
- return;
1947
- }
1948
- if (senderId === botUserId) {
1949
- logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
1950
- return;
1951
- }
1952
- if (isSystemPost(post)) {
1953
- logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
1954
- return;
1955
- }
1956
- const channelInfo = await resolveChannelInfo(channelId);
1957
- const channelType = normalizeOptionalString(channelInfo?.type) ?? normalizeOptionalString(payload.data?.channel_type);
1958
- if (!channelType) {
1959
- logVerboseMessage(`mattermost: drop post (cannot resolve channel type for ${channelId})`);
1960
- return;
1961
- }
1962
- const kind = resolveMattermostTrustedChatKind({ channelType });
1963
- const chatType = channelChatType(kind);
1964
- const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
1965
- const rawPostText = typeof post.message === "string" ? post.message : "";
1966
- const rawText = normalizeOptionalString(rawPostText) ?? "";
1967
- const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
1968
- cfg,
1969
- surface: "mattermost"
1970
- });
1971
- const isControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(rawText, cfg);
1972
- const accessDecision = await resolveMattermostMonitorInboundAccess({
1973
- account,
1974
- cfg,
1975
- senderId,
1976
- senderName,
1977
- channelId,
1978
- kind,
1979
- groupPolicy,
1980
- readStoreAllowFrom: pairing.readAllowFromStore,
1981
- allowTextCommands,
1982
- hasControlCommand: isControlCommand,
1983
- eventKind: "message",
1984
- mayPair: true
1985
- });
1986
- const commandAuthorized = accessDecision.commandAccess.authorized;
1987
- if (accessDecision.ingress.decision !== "allow") {
1988
- if (kind === "direct") {
1989
- if (accessDecision.ingress.reasonCode === "dm_policy_disabled") {
1990
- logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
1991
- return;
1992
- }
1993
- if (accessDecision.ingress.decision === "pairing") {
1994
- const { code, created } = await pairing.upsertPairingRequest({
1995
- id: senderId,
1996
- meta: { name: senderName }
1997
- });
1998
- logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
1999
- if (created) try {
2000
- await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
2001
- channel: "mattermost",
2002
- idLine: `Your Mattermost user id: ${senderId}`,
2003
- code
2004
- }), {
2005
- cfg,
2006
- accountId: account.accountId
2007
- });
2008
- opts.statusSink?.({ lastOutboundAt: Date.now() });
2009
- } catch (err) {
2010
- logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
2011
- }
2012
- return;
2013
- }
2014
- logVerboseMessage(formatMattermostDirectMessageDropLog({
2015
- senderId,
2016
- dmPolicy,
2017
- reasonCode: accessDecision.senderAccess.reasonCode
2018
- }));
2019
- return;
2020
- }
2021
- if (accessDecision.ingress.reasonCode === "group_policy_disabled") {
2022
- logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
2023
- return;
2024
- }
2025
- if (accessDecision.ingress.reasonCode === "group_policy_empty_allowlist") {
2026
- logVerboseMessage("mattermost: drop group message (no group allowlist)");
2027
- return;
2028
- }
2029
- if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
2030
- logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
2031
- return;
2032
- }
2033
- logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
2034
- return;
2035
- }
2036
- if (kind !== "direct" && accessDecision.commandAccess.shouldBlockControlCommand) {
2037
- logInboundDrop({
2038
- log: logVerboseMessage,
2318
+ direction: "inbound"
2319
+ });
2320
+ const fromLabel = formatInboundFromLabel$1({
2321
+ isGroup: kind !== "direct",
2322
+ groupLabel: channelDisplay || roomLabel,
2323
+ groupId: channelId,
2324
+ groupFallback: roomLabel || "Channel",
2325
+ directLabel: senderName,
2326
+ directId: senderId
2327
+ });
2328
+ const textWithId = `${bodyText}\n[mattermost message id: ${post.id ?? "unknown"} channel: ${channelId}]`;
2329
+ let combinedBody = formatInboundEnvelope({
2330
+ channel: "Mattermost",
2331
+ from: fromLabel,
2332
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2333
+ body: textWithId,
2334
+ chatType,
2335
+ sender: {
2336
+ name: senderName,
2337
+ id: senderId
2338
+ }
2339
+ });
2340
+ if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2341
+ historyKey,
2342
+ limit: historyLimit,
2343
+ currentMessage: combinedBody,
2344
+ formatEntry: (entry) => formatInboundEnvelope({
2345
+ channel: "Mattermost",
2346
+ from: fromLabel,
2347
+ timestamp: entry.timestamp,
2348
+ body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2349
+ chatType,
2350
+ senderLabel: entry.sender
2351
+ })
2352
+ });
2353
+ const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
2354
+ const mediaPayload = buildAgentMediaPayload(mediaList);
2355
+ const commandBody = rawText.trim();
2356
+ const inboundHistory = historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: channelHistories }).buildInboundHistory({
2357
+ historyKey,
2358
+ limit: historyLimit
2359
+ }) : void 0;
2360
+ const ctxPayload = finalizeInboundContext({
2361
+ Body: combinedBody,
2362
+ BodyForAgent: bodyForAgent,
2363
+ InboundHistory: inboundHistory,
2364
+ RawBody: commandBody,
2365
+ CommandBody: commandBody,
2366
+ BodyForCommands: commandBody,
2367
+ From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
2368
+ To: to,
2369
+ SessionKey: sessionKey,
2370
+ DmScope: route.dmScope,
2371
+ ParentSessionKey: parentSessionKey,
2372
+ AccountId: route.accountId,
2373
+ ChatType: chatType,
2374
+ ConversationLabel: fromLabel,
2375
+ GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
2376
+ GroupChannel: channelName ? `#${channelName}` : void 0,
2377
+ GroupSpace: teamId,
2378
+ SenderName: senderName,
2379
+ SenderId: senderId,
2380
+ Provider: "mattermost",
2381
+ Surface: "mattermost",
2382
+ MessageSid: post.id ?? void 0,
2383
+ MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2384
+ MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2385
+ MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2386
+ ReplyToId: effectiveReplyToId,
2387
+ MessageThreadId: effectiveReplyToId,
2388
+ Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2389
+ WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2390
+ CommandAuthorized: commandAuthorized,
2391
+ CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2392
+ OriginatingChannel: "mattermost",
2393
+ OriginatingTo: to,
2394
+ ...mediaPayload
2395
+ });
2396
+ const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2397
+ dmScope: cfg.session?.dmScope,
2398
+ allowFrom: account.config.allowFrom,
2399
+ normalizeEntry: normalizeMattermostAllowEntry
2400
+ }) : null;
2401
+ const previewLine = truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n");
2402
+ logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
2403
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
2404
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2405
+ cfg,
2406
+ channel: "mattermost",
2407
+ accountId: account.accountId
2408
+ });
2409
+ const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
2410
+ const { onModelSelected, typingCallbacks, resolveResponsePrefix, ...replyPipeline } = createChannelMessageReplyPipeline({
2411
+ cfg,
2412
+ agentId: route.agentId,
2413
+ channel: "mattermost",
2414
+ accountId: account.accountId,
2415
+ typing: {
2416
+ start: () => sendTypingIndicator(channelId, effectiveReplyToId),
2417
+ onStartError: (err) => {
2418
+ logTypingFailure({
2419
+ log: (message) => logger.debug?.(message),
2039
2420
  channel: "mattermost",
2040
- reason: "control command (unauthorized)",
2041
- target: senderId
2421
+ target: channelId,
2422
+ error: err
2042
2423
  });
2043
- return;
2044
2424
  }
2045
- const teamId = payload.data?.team_id ?? channelInfo?.team_id ?? void 0;
2046
- const channelName = payload.data?.channel_name ?? channelInfo?.name ?? "";
2047
- const channelDisplay = payload.data?.channel_display_name ?? channelInfo?.display_name ?? channelName;
2048
- const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${channelId}`;
2049
- const route = core.channel.routing.resolveAgentRoute({
2050
- cfg,
2051
- channel: "mattermost",
2052
- accountId: account.accountId,
2053
- teamId,
2054
- peer: {
2055
- kind,
2056
- id: kind === "direct" ? senderId : channelId
2057
- }
2058
- });
2059
- const baseSessionKey = route.sessionKey;
2060
- const threadRootId = normalizeOptionalString(post.root_id);
2061
- const replyToMode = resolveMattermostReplyToMode(account, kind);
2062
- const { effectiveReplyToId, sessionKey, parentSessionKey } = resolveMattermostThreadSessionContext({
2063
- baseSessionKey,
2064
- kind,
2065
- postId: post.id,
2066
- replyToMode,
2067
- threadRootId
2068
- });
2069
- const historyKey = resolveMattermostPendingHistoryKey({
2070
- kind,
2071
- sessionKey
2072
- });
2073
- const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
2074
- const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
2075
- const pendingBody = rawText || (post.file_ids?.length ? `[Mattermost ${post.file_ids.length === 1 ? "file" : "files"}]` : "");
2076
- const pendingSender = senderName;
2077
- const recordPendingHistory = () => {
2078
- const trimmed = pendingBody.trim();
2079
- createChannelHistoryWindow({ historyMap: channelHistories }).record({
2080
- limit: historyLimit,
2081
- historyKey: historyKey ?? "",
2082
- entry: historyKey && trimmed ? {
2083
- sender: pendingSender,
2084
- body: trimmed,
2085
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2086
- messageId: post.id ?? void 0
2087
- } : null
2088
- });
2089
- };
2090
- const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
2091
- const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
2092
- const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
2093
- triggered: false,
2094
- stripped: rawText
2425
+ }
2426
+ });
2427
+ const draftPreviewEnabled = account.streamingMode !== "off";
2428
+ const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
2429
+ const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
2430
+ const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
2431
+ client,
2432
+ channelId,
2433
+ rootId: effectiveReplyToId,
2434
+ throttleMs: 1200,
2435
+ chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(core.channel.text.convertMarkdownTables(value, tableMode), textLimit, chunkMode),
2436
+ log: logVerboseMessage,
2437
+ warn: logVerboseMessage
2438
+ }) : createDisabledMattermostDraftStream();
2439
+ const previewBoundaryController = createMattermostDraftPreviewBoundaryController({
2440
+ enabled: draftPreviewEnabled && account.streamingMode === "block",
2441
+ forceNewMessage: async () => {
2442
+ await draftStream.forceNewMessage();
2443
+ }
2444
+ });
2445
+ let lastPartialText = "";
2446
+ let firstAssistantPreviewPrefix;
2447
+ let firstAssistantPreviewPrefixPending = true;
2448
+ let currentAssistantPreviewUsesPrefix = false;
2449
+ let blockPreviewActivity = "none";
2450
+ let blockPreviewAssistantMessagePending = false;
2451
+ const progressDraft = createChannelProgressDraftCompositor({
2452
+ entry: account.config,
2453
+ mode: account.streamingMode,
2454
+ active: draftPreviewEnabled,
2455
+ seed: `${account.accountId}:${channelId}`,
2456
+ update: async (previewText, options) => {
2457
+ draftStream.update(previewText);
2458
+ if (options?.flush) await draftStream.flush();
2459
+ }
2460
+ });
2461
+ const enterBlockPreviewActivity = (activity) => {
2462
+ if (account.streamingMode !== "block") return;
2463
+ const continuesCurrentActivity = activity === "tool" && blockPreviewActivity === "tool" || activity === "text" && blockPreviewActivity === "text" && !blockPreviewAssistantMessagePending || activity === "reasoning" && blockPreviewActivity === "reasoning";
2464
+ const startsNewGeneration = !continuesCurrentActivity && !(blockPreviewActivity === "reasoning");
2465
+ if (startsNewGeneration) currentAssistantPreviewUsesPrefix = false;
2466
+ const boundarySettled = startsNewGeneration ? previewBoundaryController.noteBoundary() : void 0;
2467
+ if (!continuesCurrentActivity) progressDraft.reset();
2468
+ blockPreviewActivity = activity;
2469
+ blockPreviewAssistantMessagePending = false;
2470
+ if (activity === "tool") lastPartialText = "";
2471
+ return boundarySettled;
2472
+ };
2473
+ const previewState = { finalizedViaPreviewPost: false };
2474
+ const resolveFinalDeliveryText = (text) => {
2475
+ if (typeof text !== "string") return;
2476
+ const resolution = draftStream.resolveFinalText(text);
2477
+ return resolution.kind === "already-delivered" ? "" : resolution.text;
2478
+ };
2479
+ const resolvePreviewFinalText = (text) => {
2480
+ const deliveryText = resolveFinalDeliveryText(text);
2481
+ if (typeof deliveryText !== "string") return;
2482
+ const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
2483
+ const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
2484
+ if (!chunks.length && formatted) chunks.push(formatted);
2485
+ if (chunks.length != 1) return;
2486
+ const trimmed = chunks[0]?.trim();
2487
+ if (!trimmed) return;
2488
+ if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
2489
+ return trimmed;
2490
+ };
2491
+ const updateDraftFromPartial = (text) => {
2492
+ const cleaned = text?.trim();
2493
+ if (!cleaned) return;
2494
+ if (cleaned === lastPartialText) return;
2495
+ if (lastPartialText && lastPartialText.startsWith(cleaned) && cleaned.length < lastPartialText.length) return;
2496
+ const boundarySettled = enterBlockPreviewActivity("text");
2497
+ lastPartialText = cleaned;
2498
+ if (firstAssistantPreviewPrefixPending) {
2499
+ firstAssistantPreviewPrefix = resolveResponsePrefix?.();
2500
+ firstAssistantPreviewPrefixPending = false;
2501
+ currentAssistantPreviewUsesPrefix = Boolean(firstAssistantPreviewPrefix);
2502
+ }
2503
+ const previewText = currentAssistantPreviewUsesPrefix && firstAssistantPreviewPrefix ? cleaned.startsWith(firstAssistantPreviewPrefix) ? cleaned : `${firstAssistantPreviewPrefix} ${cleaned}` : cleaned;
2504
+ draftStream.updateAssistantText(previewText);
2505
+ previewBoundaryController.noteUpdate();
2506
+ return boundarySettled;
2507
+ };
2508
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
2509
+ isDirect: kind === "direct",
2510
+ dmRetryOptions: account.config.dmChannelRetry
2511
+ });
2512
+ const dispatcherOptions = {
2513
+ ...replyPipeline,
2514
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
2515
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
2516
+ humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
2517
+ typingCallbacks
2518
+ };
2519
+ const delivery = {
2520
+ deliver: async (payloadEntry, info) => {
2521
+ if (info.kind === "final") {
2522
+ await enterBlockPreviewActivity("text");
2523
+ await draftStream.settleBoundaries();
2524
+ progressDraft.markFinalReplyStarted();
2525
+ }
2526
+ const markThreadParticipation = () => {
2527
+ if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
2095
2528
  };
2096
- const oncharTriggered = oncharResult.triggered;
2097
- const canDetectMention = Boolean(botUsername) || mentionRegexes.length > 0;
2098
- const threadAlreadyEngaged = kind !== "direct" && effectiveReplyToId ? await hasMattermostThreadParticipationWithPersistence({
2099
- accountId: account.accountId,
2100
- channelId,
2101
- threadRootId: effectiveReplyToId
2102
- }) : false;
2103
- const mentionDecision = evaluateMattermostMentionGate({
2529
+ await deliverMattermostReplyWithDraftPreview({
2530
+ payload: payloadEntry,
2531
+ info,
2104
2532
  kind,
2105
- cfg,
2106
- accountId: account.accountId,
2107
- channelId,
2108
- threadRootId,
2109
- requireMentionOverride: account.requireMention,
2110
- resolveRequireMention: core.channel.groups.resolveRequireMention,
2111
- wasMentioned,
2112
- threadAlreadyEngaged,
2113
- isControlCommand,
2114
- commandAuthorized,
2115
- oncharEnabled,
2116
- oncharTriggered,
2117
- canDetectMention
2118
- });
2119
- const { shouldRequireMention, shouldBypassMention } = mentionDecision;
2120
- if (mentionDecision.dropReason === "onchar-not-triggered") {
2121
- logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
2122
- recordPendingHistory();
2123
- return;
2124
- }
2125
- if (mentionDecision.dropReason === "missing-mention") {
2126
- logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
2127
- recordPendingHistory();
2128
- return;
2129
- }
2130
- const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2131
- const mediaList = await resolveMattermostMedia(fileIds);
2132
- const mediaPlaceholder = buildMattermostAttachmentPlaceholder(mediaList);
2133
- const bodyText = normalizeMention(formatMattermostInboundMediaText({
2134
- body: [oncharTriggered ? oncharResult.stripped : rawText, mediaPlaceholder].filter(Boolean).join("\n").trim(),
2135
- mediaPlaceholder,
2136
- expectedCount: fileIds.length,
2137
- mediaCount: mediaList.length
2138
- }), botUsername);
2139
- if (shouldDropEmptyMattermostBody({
2140
- bodyText,
2141
- rawText: rawPostText,
2142
- botUsername
2143
- })) {
2144
- logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
2145
- return;
2146
- }
2147
- const bodyForAgent = bodyText || rawText.trim();
2148
- core.channel.activity.record({
2149
- channel: "mattermost",
2150
- accountId: account.accountId,
2151
- direction: "inbound"
2152
- });
2153
- const fromLabel = formatInboundFromLabel$1({
2154
- isGroup: kind !== "direct",
2155
- groupLabel: channelDisplay || roomLabel,
2156
- groupId: channelId,
2157
- groupFallback: roomLabel || "Channel",
2158
- directLabel: senderName,
2159
- directId: senderId
2160
- });
2161
- const textWithId = `${bodyText}\n[mattermost message id: ${post.id ?? "unknown"} channel: ${channelId}]`;
2162
- let combinedBody = core.channel.reply.formatInboundEnvelope({
2163
- channel: "Mattermost",
2164
- from: fromLabel,
2165
- timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2166
- body: textWithId,
2167
- chatType,
2168
- sender: {
2169
- name: senderName,
2170
- id: senderId
2171
- }
2172
- });
2173
- if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2174
- historyKey,
2175
- limit: historyLimit,
2176
- currentMessage: combinedBody,
2177
- formatEntry: (entry) => core.channel.reply.formatInboundEnvelope({
2178
- channel: "Mattermost",
2179
- from: fromLabel,
2180
- timestamp: entry.timestamp,
2181
- body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2182
- chatType,
2183
- senderLabel: entry.sender
2184
- })
2185
- });
2186
- const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
2187
- const mediaPayload = buildAgentMediaPayload(mediaList);
2188
- const commandBody = rawText.trim();
2189
- const inboundHistory = historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: channelHistories }).buildInboundHistory({
2190
- historyKey,
2191
- limit: historyLimit
2192
- }) : void 0;
2193
- const ctxPayload = core.channel.reply.finalizeInboundContext({
2194
- Body: combinedBody,
2195
- BodyForAgent: bodyForAgent,
2196
- InboundHistory: inboundHistory,
2197
- RawBody: commandBody,
2198
- CommandBody: commandBody,
2199
- BodyForCommands: commandBody,
2200
- From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
2201
- To: to,
2202
- SessionKey: sessionKey,
2203
- ParentSessionKey: parentSessionKey,
2204
- AccountId: route.accountId,
2205
- ChatType: chatType,
2206
- ConversationLabel: fromLabel,
2207
- GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
2208
- GroupChannel: channelName ? `#${channelName}` : void 0,
2209
- GroupSpace: teamId,
2210
- SenderName: senderName,
2211
- SenderId: senderId,
2212
- Provider: "mattermost",
2213
- Surface: "mattermost",
2214
- MessageSid: post.id ?? void 0,
2215
- MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2216
- MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2217
- MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2218
- ReplyToId: effectiveReplyToId,
2219
- MessageThreadId: effectiveReplyToId,
2220
- Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2221
- WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2222
- CommandAuthorized: commandAuthorized,
2223
- CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2224
- OriginatingChannel: "mattermost",
2225
- OriginatingTo: to,
2226
- ...mediaPayload
2227
- });
2228
- const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2229
- dmScope: cfg.session?.dmScope,
2230
- allowFrom: account.config.allowFrom,
2231
- normalizeEntry: normalizeMattermostAllowEntry
2232
- }) : null;
2233
- const storePath = core.channel.session.resolveStorePath(cfg.session?.store, { agentId: route.agentId });
2234
- const previewLine = truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n");
2235
- logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
2236
- const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
2237
- const tableMode = core.channel.text.resolveMarkdownTableMode({
2238
- cfg,
2239
- channel: "mattermost",
2240
- accountId: account.accountId
2241
- });
2242
- const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
2243
- const { onModelSelected, typingCallbacks, resolveResponsePrefix, ...replyPipeline } = createChannelMessageReplyPipeline({
2244
- cfg,
2245
- agentId: route.agentId,
2246
- channel: "mattermost",
2247
- accountId: account.accountId,
2248
- typing: {
2249
- start: () => sendTypingIndicator(channelId, effectiveReplyToId),
2250
- onStartError: (err) => {
2251
- logTypingFailure({
2252
- log: (message) => logger.debug?.(message),
2253
- channel: "mattermost",
2254
- target: channelId,
2255
- error: err
2256
- });
2257
- }
2258
- }
2259
- });
2260
- const draftPreviewEnabled = account.streamingMode !== "off";
2261
- const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
2262
- const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
2263
- const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
2264
2533
  client,
2265
- channelId,
2266
- rootId: effectiveReplyToId,
2267
- throttleMs: 1200,
2268
- chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(core.channel.text.convertMarkdownTables(value, tableMode), textLimit, chunkMode),
2269
- log: logVerboseMessage,
2270
- warn: logVerboseMessage
2271
- }) : createDisabledMattermostDraftStream();
2272
- const previewBoundaryController = createMattermostDraftPreviewBoundaryController({
2273
- enabled: draftPreviewEnabled && account.streamingMode === "block",
2274
- forceNewMessage: async () => {
2275
- await draftStream.forceNewMessage();
2276
- }
2277
- });
2278
- let lastPartialText = "";
2279
- let firstAssistantPreviewPrefix;
2280
- let firstAssistantPreviewPrefixPending = true;
2281
- let currentAssistantPreviewUsesPrefix = false;
2282
- let blockPreviewActivity = "none";
2283
- let blockPreviewAssistantMessagePending = false;
2284
- const progressDraft = createChannelProgressDraftCompositor({
2285
- entry: account.config,
2286
- mode: account.streamingMode,
2287
- active: draftPreviewEnabled,
2288
- seed: `${account.accountId}:${channelId}`,
2289
- update: async (previewText, options) => {
2290
- draftStream.update(previewText);
2291
- if (options?.flush) await draftStream.flush();
2292
- }
2293
- });
2294
- const enterBlockPreviewActivity = (activity) => {
2295
- if (account.streamingMode !== "block") return;
2296
- const continuesCurrentActivity = activity === "tool" && blockPreviewActivity === "tool" || activity === "text" && blockPreviewActivity === "text" && !blockPreviewAssistantMessagePending || activity === "reasoning" && blockPreviewActivity === "reasoning";
2297
- const startsNewGeneration = !continuesCurrentActivity && !(blockPreviewActivity === "reasoning");
2298
- if (startsNewGeneration) currentAssistantPreviewUsesPrefix = false;
2299
- const boundarySettled = startsNewGeneration ? previewBoundaryController.noteBoundary() : void 0;
2300
- if (!continuesCurrentActivity) progressDraft.reset();
2301
- blockPreviewActivity = activity;
2302
- blockPreviewAssistantMessagePending = false;
2303
- if (activity === "tool") lastPartialText = "";
2304
- return boundarySettled;
2305
- };
2306
- const previewState = { finalizedViaPreviewPost: false };
2307
- const resolveFinalDeliveryText = (text) => {
2308
- if (typeof text !== "string") return;
2309
- const resolution = draftStream.resolveFinalText(text);
2310
- return resolution.kind === "already-delivered" ? "" : resolution.text;
2311
- };
2312
- const resolvePreviewFinalText = (text) => {
2313
- const deliveryText = resolveFinalDeliveryText(text);
2314
- if (typeof deliveryText !== "string") return;
2315
- const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
2316
- const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
2317
- if (!chunks.length && formatted) chunks.push(formatted);
2318
- if (chunks.length != 1) return;
2319
- const trimmed = chunks[0]?.trim();
2320
- if (!trimmed) return;
2321
- if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
2322
- return trimmed;
2323
- };
2324
- const updateDraftFromPartial = (text) => {
2325
- const cleaned = text?.trim();
2326
- if (!cleaned) return;
2327
- if (cleaned === lastPartialText) return;
2328
- if (lastPartialText && lastPartialText.startsWith(cleaned) && cleaned.length < lastPartialText.length) return;
2329
- const boundarySettled = enterBlockPreviewActivity("text");
2330
- lastPartialText = cleaned;
2331
- if (firstAssistantPreviewPrefixPending) {
2332
- firstAssistantPreviewPrefix = resolveResponsePrefix?.();
2333
- firstAssistantPreviewPrefixPending = false;
2334
- currentAssistantPreviewUsesPrefix = Boolean(firstAssistantPreviewPrefix);
2335
- }
2336
- const previewText = currentAssistantPreviewUsesPrefix && firstAssistantPreviewPrefix ? cleaned.startsWith(firstAssistantPreviewPrefix) ? cleaned : `${firstAssistantPreviewPrefix} ${cleaned}` : cleaned;
2337
- draftStream.updateAssistantText(previewText);
2338
- previewBoundaryController.noteUpdate();
2339
- return boundarySettled;
2340
- };
2341
- const deliveryBarrier = createMattermostReplyDeliveryBarrier({
2342
- isDirect: kind === "direct",
2343
- dmRetryOptions: account.config.dmChannelRetry
2344
- });
2345
- const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } = core.channel.reply.createReplyDispatcherWithTyping({
2346
- ...replyPipeline,
2347
- resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
2348
- onDeliverySettled: deliveryBarrier.markDeliverySettled,
2349
- humanDelay: core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId),
2350
- typingCallbacks,
2351
- deliver: async (payloadEntry, info) => {
2352
- if (info.kind === "final") {
2353
- await enterBlockPreviewActivity("text");
2354
- await draftStream.settleBoundaries();
2355
- progressDraft.markFinalReplyStarted();
2356
- }
2357
- const markThreadParticipation = () => {
2358
- if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
2359
- };
2360
- await deliverMattermostReplyWithDraftPreview({
2361
- payload: payloadEntry,
2362
- info,
2363
- kind,
2364
- client,
2365
- draftStream,
2366
- effectiveReplyToId,
2367
- resolvePreviewFinalText,
2368
- previewState,
2369
- logVerboseMessage,
2370
- recordThreadParticipation: markThreadParticipation,
2371
- deliverPayload: async (payloadToDeliver) => {
2372
- const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && typeof payloadToDeliver.text === "string" ? draftStream.resolveFinalText(payloadToDeliver.text) : void 0;
2373
- const resolvedPayload = finalTextResolution ? {
2374
- ...payloadToDeliver,
2375
- text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
2376
- } : payloadToDeliver;
2377
- const outcome = await deliverMattermostReplyPayload({
2378
- core,
2379
- cfg,
2380
- payload: resolvedPayload,
2381
- to,
2382
- accountId: account.accountId,
2383
- agentId: route.agentId,
2384
- replyToId: resolveMattermostReplyRootId({
2385
- kind,
2386
- threadRootId: effectiveReplyToId,
2387
- replyToId: payloadToDeliver.replyToId
2388
- }),
2389
- textLimit,
2390
- tableMode,
2391
- sendMessage: sendMessageMattermost,
2392
- onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2393
- });
2394
- if (outcome === "text" || outcome === "media") markThreadParticipation();
2395
- else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
2396
- const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
2397
- outcome,
2398
- payload: resolvedPayload,
2399
- to,
2400
- accountId: account.accountId,
2401
- agentId: route.agentId
2402
- });
2403
- if (deliveryLog) runtime.log?.(deliveryLog);
2404
- }
2534
+ draftStream,
2535
+ effectiveReplyToId,
2536
+ resolvePreviewFinalText,
2537
+ previewState,
2538
+ logVerboseMessage,
2539
+ recordThreadParticipation: markThreadParticipation,
2540
+ deliverPayload: async (payloadToDeliver) => {
2541
+ const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && typeof payloadToDeliver.text === "string" ? draftStream.resolveFinalText(payloadToDeliver.text) : void 0;
2542
+ const resolvedPayload = finalTextResolution ? {
2543
+ ...payloadToDeliver,
2544
+ text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
2545
+ } : payloadToDeliver;
2546
+ const outcome = await deliverMattermostReplyPayload({
2547
+ core,
2548
+ cfg,
2549
+ payload: resolvedPayload,
2550
+ to,
2551
+ accountId: account.accountId,
2552
+ agentId: route.agentId,
2553
+ replyToId: resolveMattermostReplyRootId({
2554
+ kind,
2555
+ threadRootId: effectiveReplyToId,
2556
+ replyToId: payloadToDeliver.replyToId
2557
+ }),
2558
+ textLimit,
2559
+ tableMode,
2560
+ sendMessage: sendMessageMattermost,
2561
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2405
2562
  });
2406
- if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2407
- },
2408
- onError: (err, info) => {
2409
- runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
2563
+ if (outcome === "text" || outcome === "media") markThreadParticipation();
2564
+ else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
2565
+ const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
2566
+ outcome,
2567
+ payload: resolvedPayload,
2568
+ to,
2569
+ accountId: account.accountId,
2570
+ agentId: route.agentId
2571
+ });
2572
+ if (deliveryLog) runtime.log?.(deliveryLog);
2410
2573
  }
2411
2574
  });
2412
- const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
2413
- route,
2414
- sessionKey: route.sessionKey
2415
- });
2416
- let dispatchSettledBeforeStart = false;
2417
- try {
2418
- await core.channel.inbound.run({
2575
+ if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2576
+ },
2577
+ onError: (err, info) => {
2578
+ runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
2579
+ }
2580
+ };
2581
+ const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
2582
+ route,
2583
+ sessionKey: route.sessionKey
2584
+ });
2585
+ try {
2586
+ await core.channel.inbound.run({
2587
+ channel: "mattermost",
2588
+ accountId: route.accountId,
2589
+ raw: post,
2590
+ adapter: {
2591
+ ingest: () => ({
2592
+ id: post.id ?? `${to}:${Date.now()}`,
2593
+ timestamp: post.create_at ?? void 0,
2594
+ rawText,
2595
+ textForAgent: ctxPayload.BodyForAgent,
2596
+ textForCommands: ctxPayload.CommandBody,
2597
+ raw: post
2598
+ }),
2599
+ resolveTurn: () => ({
2600
+ cfg,
2419
2601
  channel: "mattermost",
2420
2602
  accountId: route.accountId,
2421
- raw: post,
2422
- adapter: {
2423
- ingest: () => ({
2424
- id: post.id ?? `${to}:${Date.now()}`,
2425
- timestamp: post.create_at ?? void 0,
2426
- rawText,
2427
- textForAgent: ctxPayload.BodyForAgent,
2428
- textForCommands: ctxPayload.CommandBody,
2429
- raw: post
2430
- }),
2431
- resolveTurn: () => ({
2603
+ route: {
2604
+ agentId: route.agentId,
2605
+ dmScope: route.dmScope,
2606
+ sessionKey: route.sessionKey
2607
+ },
2608
+ ctxPayload,
2609
+ record: {
2610
+ updateLastRoute: kind === "direct" ? {
2611
+ sessionKey: inboundLastRouteSessionKey,
2432
2612
  channel: "mattermost",
2613
+ to,
2433
2614
  accountId: route.accountId,
2434
- routeSessionKey: route.sessionKey,
2435
- storePath,
2436
- ctxPayload,
2437
- recordInboundSession: core.channel.session.recordInboundSession,
2438
- record: {
2439
- updateLastRoute: kind === "direct" ? {
2440
- sessionKey: inboundLastRouteSessionKey,
2441
- channel: "mattermost",
2442
- to,
2443
- accountId: route.accountId,
2444
- mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
2445
- ownerRecipient: pinnedMainDmOwner,
2446
- senderRecipient: normalizeMattermostAllowEntry(senderId),
2447
- onSkip: ({ ownerRecipient, senderRecipient }) => {
2448
- logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
2449
- }
2450
- } : void 0
2451
- } : void 0,
2452
- onRecordError: (err) => {
2453
- logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
2615
+ mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
2616
+ ownerRecipient: pinnedMainDmOwner,
2617
+ senderRecipient: normalizeMattermostAllowEntry(senderId),
2618
+ onSkip: ({ ownerRecipient, senderRecipient }) => {
2619
+ logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
2454
2620
  }
2455
- },
2456
- history: {
2457
- isGroup: Boolean(historyKey),
2458
- historyKey: historyKey ?? void 0,
2459
- historyMap: channelHistories,
2460
- limit: historyLimit
2461
- },
2462
- onPreDispatchFailure: async () => {
2463
- dispatchSettledBeforeStart = true;
2464
- await core.channel.reply.settleReplyDispatcher({
2465
- dispatcher,
2466
- onSettled: () => {
2467
- markRunComplete();
2468
- markDispatchIdle();
2469
- }
2470
- });
2471
- },
2472
- runDispatch: () => core.channel.reply.withReplyDispatcher({
2473
- dispatcher,
2474
- onSettled: () => {
2475
- markDispatchIdle();
2476
- },
2477
- run: () => core.channel.reply.dispatchReplyFromConfig({
2478
- ctx: ctxPayload,
2479
- cfg,
2480
- dispatcher,
2481
- replyOptions: {
2482
- ...replyOptions,
2483
- allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
2484
- preserveProgressCallbackStartOrder: draftPreviewEnabled ? true : void 0,
2485
- onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
2486
- disableBlockStreaming: draftPreviewEnabled ? true : typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
2487
- ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2488
- onModelSelected,
2489
- onPartialReply: (payloadResult) => {
2490
- if (account.streamingMode !== "progress") return updateDraftFromPartial(payloadResult.text);
2491
- },
2492
- onAssistantMessageStart: () => {
2493
- lastPartialText = "";
2494
- progressDraft.resetReasoningProgress();
2495
- if (account.streamingMode === "block") {
2496
- blockPreviewAssistantMessagePending = true;
2497
- return;
2498
- }
2499
- if (account.streamingMode !== "progress") progressDraft.reset();
2500
- },
2501
- onReasoningEnd: () => {
2502
- lastPartialText = "";
2503
- progressDraft.resetReasoningProgress();
2504
- if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
2505
- },
2506
- onReasoningStream: async (payloadResult) => {
2507
- if (account.streamingMode === "progress") {
2508
- await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2509
- return;
2510
- }
2511
- if (!lastPartialText) {
2512
- const boundarySettled = enterBlockPreviewActivity("reasoning");
2513
- draftStream.update("Thinking…");
2514
- previewBoundaryController.noteUpdate();
2515
- await boundarySettled;
2516
- }
2517
- },
2518
- onToolStart: async (payloadValue) => {
2519
- if (!draftToolProgressEnabled) return;
2520
- const boundarySettled = enterBlockPreviewActivity("tool");
2521
- const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2522
- event: "tool",
2523
- itemId: payloadValue.itemId,
2524
- toolCallId: payloadValue.toolCallId,
2525
- name: payloadValue.name,
2526
- phase: payloadValue.phase,
2527
- args: payloadValue.args
2528
- }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
2529
- previewBoundaryController.noteUpdate();
2530
- await Promise.all([boundarySettled, progressSettled]);
2531
- },
2532
- onItemEvent: async (payloadLocal) => {
2533
- if (!draftToolProgressEnabled) return;
2534
- const boundarySettled = enterBlockPreviewActivity("tool");
2535
- const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2536
- event: "item",
2537
- itemId: payloadLocal.itemId,
2538
- itemKind: payloadLocal.kind,
2539
- title: payloadLocal.title,
2540
- name: payloadLocal.name,
2541
- phase: payloadLocal.phase,
2542
- status: payloadLocal.status,
2543
- summary: payloadLocal.summary,
2544
- progressText: payloadLocal.progressText,
2545
- meta: payloadLocal.meta
2546
- }), { startImmediately: true });
2547
- previewBoundaryController.noteUpdate();
2548
- await Promise.all([boundarySettled, progressSettled]);
2549
- }
2550
- }
2551
- })
2552
- })
2553
- })
2621
+ } : void 0
2622
+ } : void 0,
2623
+ onRecordError: (err) => {
2624
+ logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
2625
+ }
2626
+ },
2627
+ history: {
2628
+ isGroup: Boolean(historyKey),
2629
+ historyKey: historyKey ?? void 0,
2630
+ historyMap: channelHistories,
2631
+ limit: historyLimit
2632
+ },
2633
+ dispatcherOptions,
2634
+ delivery,
2635
+ replyOptions: {
2636
+ ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
2637
+ allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
2638
+ preserveProgressCallbackStartOrder: draftPreviewEnabled ? true : void 0,
2639
+ onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
2640
+ disableBlockStreaming: draftPreviewEnabled ? true : typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
2641
+ ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2642
+ onModelSelected,
2643
+ onPartialReply: (payloadResult) => {
2644
+ if (account.streamingMode !== "progress") return updateDraftFromPartial(payloadResult.text);
2645
+ },
2646
+ onAssistantMessageStart: () => {
2647
+ lastPartialText = "";
2648
+ progressDraft.resetReasoningProgress();
2649
+ if (account.streamingMode === "block") {
2650
+ blockPreviewAssistantMessagePending = true;
2651
+ return;
2652
+ }
2653
+ if (account.streamingMode !== "progress") progressDraft.reset();
2654
+ },
2655
+ onReasoningEnd: () => {
2656
+ lastPartialText = "";
2657
+ progressDraft.resetReasoningProgress();
2658
+ if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
2659
+ },
2660
+ onReasoningStream: async (payloadResult) => {
2661
+ if (account.streamingMode === "progress") {
2662
+ await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2663
+ return;
2664
+ }
2665
+ if (!lastPartialText) {
2666
+ const boundarySettled = enterBlockPreviewActivity("reasoning");
2667
+ draftStream.update("Thinking…");
2668
+ previewBoundaryController.noteUpdate();
2669
+ await boundarySettled;
2670
+ }
2671
+ },
2672
+ onToolStart: async (payloadValue) => {
2673
+ if (!draftToolProgressEnabled) return;
2674
+ const boundarySettled = enterBlockPreviewActivity("tool");
2675
+ const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2676
+ event: "tool",
2677
+ itemId: payloadValue.itemId,
2678
+ toolCallId: payloadValue.toolCallId,
2679
+ name: payloadValue.name,
2680
+ phase: payloadValue.phase,
2681
+ args: payloadValue.args
2682
+ }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
2683
+ previewBoundaryController.noteUpdate();
2684
+ await Promise.all([boundarySettled, progressSettled]);
2685
+ },
2686
+ onItemEvent: async (payloadLocal) => {
2687
+ if (!draftToolProgressEnabled) return;
2688
+ const boundarySettled = enterBlockPreviewActivity("tool");
2689
+ const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2690
+ event: "item",
2691
+ itemId: payloadLocal.itemId,
2692
+ itemKind: payloadLocal.kind,
2693
+ title: payloadLocal.title,
2694
+ name: payloadLocal.name,
2695
+ phase: payloadLocal.phase,
2696
+ status: payloadLocal.status,
2697
+ summary: payloadLocal.summary,
2698
+ progressText: payloadLocal.progressText,
2699
+ meta: payloadLocal.meta
2700
+ }), { startImmediately: true });
2701
+ previewBoundaryController.noteUpdate();
2702
+ await Promise.all([boundarySettled, progressSettled]);
2703
+ }
2554
2704
  }
2555
- });
2556
- } finally {
2557
- try {
2558
- await draftStream.stop();
2559
- } catch (err) {
2560
- logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
2561
- }
2562
- if (!dispatchSettledBeforeStart) markRunComplete();
2705
+ })
2563
2706
  }
2707
+ });
2708
+ } finally {
2709
+ try {
2710
+ await draftStream.stop();
2711
+ } catch (err) {
2712
+ logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
2564
2713
  }
2565
- }) === "duplicate") logVerboseMessage(`mattermost: drop post (dedupe account=${account.accountId} ids=${allMessageIds.length})`);
2714
+ }
2566
2715
  };
2567
2716
  const handleReactionEvent = async (payload) => {
2568
2717
  const reactionData = payload.data?.reaction;
@@ -2652,23 +2801,43 @@ async function monitorMattermostProvider(opts = {}) {
2652
2801
  onFlush: async (entries) => {
2653
2802
  const last = entries.at(-1);
2654
2803
  if (!last) return;
2655
- if (entries.length === 1) {
2656
- await handlePost(last.post, last.payload);
2657
- return;
2804
+ const { lifecycle, settle } = buildMattermostFlushIngressLifecycle(entries);
2805
+ try {
2806
+ if (entries.length === 1) {
2807
+ await handlePost(last.post, last.payload, lifecycle);
2808
+ await settle();
2809
+ return;
2810
+ }
2811
+ const combinedText = entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n");
2812
+ const mergedPost = {
2813
+ ...last.post,
2814
+ message: combinedText,
2815
+ file_ids: []
2816
+ };
2817
+ await handlePost(mergedPost, last.payload, lifecycle, entries.map((entry) => entry.post.id));
2818
+ await settle();
2819
+ } catch (error) {
2820
+ await lifecycle?.onAbandoned();
2821
+ throw error;
2658
2822
  }
2659
- const combinedText = entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n");
2660
- const mergedPost = {
2661
- ...last.post,
2662
- message: combinedText,
2663
- file_ids: []
2664
- };
2665
- const ids = entries.map((entry) => entry.post.id).filter(Boolean);
2666
- await handlePost(mergedPost, last.payload, ids.length > 0 ? ids : void 0);
2667
2823
  },
2668
2824
  onError: (err) => {
2669
2825
  runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
2670
2826
  }
2671
2827
  });
2828
+ const ingress = createMattermostIngressMonitor({
2829
+ accountId: account.accountId,
2830
+ runtime,
2831
+ abortSignal: opts.abortSignal,
2832
+ dispatch: async (post, payload, turnAdoptionLifecycle) => {
2833
+ await debouncer.enqueue({
2834
+ post,
2835
+ payload,
2836
+ turnAdoptionLifecycle
2837
+ });
2838
+ return { kind: "deferred" };
2839
+ }
2840
+ });
2672
2841
  const wsUrl = buildMattermostWsUrl(baseUrl);
2673
2842
  let seq = 1;
2674
2843
  const connectOnce = createMattermostConnectOnce({
@@ -2682,12 +2851,7 @@ async function monitorMattermostProvider(opts = {}) {
2682
2851
  getBotUpdateAt: async () => {
2683
2852
  return (await fetchMattermostMe(client)).update_at ?? 0;
2684
2853
  },
2685
- onPosted: async (post, payload) => {
2686
- await debouncer.enqueue({
2687
- post,
2688
- payload
2689
- });
2690
- },
2854
+ onPosted: ingress.receive,
2691
2855
  onReaction: async (payload) => {
2692
2856
  await handleReactionEvent(payload);
2693
2857
  }
@@ -2725,6 +2889,7 @@ async function monitorMattermostProvider(opts = {}) {
2725
2889
  }
2726
2890
  });
2727
2891
  } finally {
2892
+ await ingress.stop();
2728
2893
  unregisterInteractions?.();
2729
2894
  }
2730
2895
  const slashShutdownCleanupPromise = slashShutdownCleanup;