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

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 resolveAllowlistProviderRuntimeGroupPolicy, D as warnMissingProviderGroupPolicyFallbackOnce, E as resolveDefaultGroupPolicy, S as registerPluginHttpRoute, a as normalizeMattermostAllowEntry, b as parseTcpPort, c as resolveMattermostTrustedChatKind, d as createChannelHistoryWindow, f as createChannelMessageReplyPipeline, g as listSkillCommandsForAgents, i as mapMattermostChannelTypeToChatType, l as DEFAULT_GROUP_HISTORY_LIMIT, n as formatMattermostDirectMessageDropLog, p as createChannelPairingController, s as resolveMattermostMonitorInboundAccess, t as authorizeMattermostCommandInvocation, u as buildModelsProviderData, v as logInboundDrop, w as resolveChannelMediaMaxBytes, y as logTypingFailure } from "./monitor-auth-4zjr5tXP.js";
4
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-DODXaHdE.js";
5
+ import { i as resolveMattermostReplyToMode, r as resolveMattermostAccount, t as listMattermostAccountIds } from "./accounts-B-GrNVwP.js";
6
+ import { a as normalizeMattermostMessagingTarget } from "./channel-plugin-runtime-CgRXlOvV.js";
7
+ import { _ as registerSlashCommands, a as sendMessageMattermost, c as deliverMattermostReplyPayload, d as renderMattermostModelsPickerView, f as renderMattermostProviderPickerView, g as isSlashCommandsEnabled, h as cleanupSlashCommands, l as buildMattermostAllowedModelRefs, m as DEFAULT_COMMAND_SPECS, n as deactivateSlashCommands, o as resolveMattermostOpaqueTarget, p as resolveMattermostModelPickerCurrentModel, r as getSlashCommandState, s as createMattermostReplyDeliveryBarrier, t as activateSlashCommands, u as parseMattermostModelPickerContext, v as resolveCallbackUrl, y as resolveSlashCommandConfig } from "./slash-state-CFEaCLnp.js";
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 { buildChannelInboundMediaPayload, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, resolveInboundMentionDecision, toInboundMediaFacts } from "openclaw/plugin-sdk/channel-inbound";
17
+ import { bindIngressLifecycleToReplyOptions, buildChannelProgressDraftLineForEntry, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, defineFinalizableLivePreviewAdapter, deliverWithFinalizableLivePreviewAdapter, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
18
18
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
19
+ import { resolveChannelImplicitMentions } from "openclaw/plugin-sdk/channel-ingress-runtime";
19
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,125 +863,570 @@ 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);
1201
- }
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++;
1214
- }
1215
- }
1216
- function createReconnectBackoff(initialDelayMs, maxDelayMs) {
1217
- let retryDelay = initialDelayMs;
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
+ };
1218
886
  return {
1219
- current: () => retryDelay,
1220
- reset: () => {
1221
- retryDelay = initialDelayMs;
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
+ }
1222
906
  },
1223
- increase: () => {
1224
- retryDelay = Math.min(retryDelay * 2, maxDelayMs);
907
+ settle: async () => {
908
+ if (!handedOff) await adoptAll();
1225
909
  }
1226
910
  };
1227
911
  }
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));
1233
- }
1234
- function sleepAbortable(ms, signal) {
1235
- return new Promise((resolve) => {
1236
- if (signal?.aborted) {
1237
- resolve();
1238
- return;
1239
- }
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
- });
912
+ var MattermostIngressPermanentError = class extends Error {
913
+ constructor(reason, message, options) {
914
+ super(message, options);
915
+ this.reason = reason;
916
+ this.name = "MattermostIngressPermanentError";
917
+ }
918
+ };
919
+ function isRecord(value) {
920
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1250
921
  }
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) => {
1262
- 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 {}
1268
- }
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 });
1269
928
  }
1270
- });
1271
- function makeKey(accountId, channelId, threadRootId) {
1272
- return `${accountId}:${channelId}:${threadRootId}`;
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;
948
+ return {
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")}`
951
+ };
1273
952
  }
1274
- function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
1275
- if (!accountId || !channelId || !threadRootId) return;
1276
- threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
1277
- ...opts?.agentId ? { agentId: opts.agentId } : {},
1278
- repliedAt: Date.now()
1279
- });
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
+ };
1280
963
  }
1281
- async function hasMattermostThreadParticipationWithPersistence(params) {
1282
- if (!params.accountId || !params.channelId || !params.threadRootId) return false;
1283
- return await threadParticipation.lookup(makeKey(params.accountId, params.channelId, params.threadRootId));
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
+ const monitor = createChannelIngressMonitor({
977
+ queue: options.queue ?? (() => getMattermostRuntime().state.openChannelIngressQueue({ accountId: options.accountId })),
978
+ inspect: (rawEvent) => inspectMattermostIngressEvent(rawEvent),
979
+ payload: {
980
+ version: MATTERMOST_INGRESS_PAYLOAD_VERSION,
981
+ serialize: (rawEvent, { receivedAt }) => ({
982
+ receivedAt,
983
+ rawEvent
984
+ }),
985
+ deserialize: (body) => body.rawEvent,
986
+ encode: ({ body }) => ({
987
+ version: MATTERMOST_INGRESS_PAYLOAD_VERSION,
988
+ ...body
989
+ }),
990
+ decode: (payload) => ({
991
+ version: payload.version,
992
+ body: {
993
+ receivedAt: payload.receivedAt,
994
+ rawEvent: payload.rawEvent
995
+ }
996
+ }),
997
+ createClaimError: (kind, claim) => new MattermostIngressPermanentError("invalid-event", kind === "invalid-version" ? `Mattermost ingress row ${claim.id} has an unsupported version.` : `Mattermost ingress row ${claim.id} has invalid post identity.`)
998
+ },
999
+ deliver: async (rawEvent, lifecycle, claim) => {
1000
+ const { post, payload } = parseClaimedEvent(rawEvent, claim.id);
1001
+ return await options.dispatch(post, payload, lifecycle);
1002
+ },
1003
+ pollIntervalMs: options.pollIntervalMs ?? MATTERMOST_INGRESS_POLL_INTERVAL_MS,
1004
+ waitForDeliveryIdleBeforeRepump: true,
1005
+ retention: {
1006
+ pruneIntervalMs: MATTERMOST_INGRESS_PRUNE_INTERVAL_MS,
1007
+ completedTtlMs: MATTERMOST_INGRESS_COMPLETED_TTL_MS,
1008
+ completedMaxEntries: MATTERMOST_INGRESS_COMPLETED_MAX_ENTRIES,
1009
+ failedTtlMs: MATTERMOST_INGRESS_FAILED_TTL_MS,
1010
+ failedMaxEntries: MATTERMOST_INGRESS_FAILED_MAX_ENTRIES
1011
+ },
1012
+ drain: {
1013
+ resolveNonRetryableFailure: resolveMattermostIngressNonRetryableFailure,
1014
+ ...options.adoptionStallTimeoutMs === void 0 ? {} : { adoptionStallTimeoutMs: options.adoptionStallTimeoutMs },
1015
+ onLog: (message) => options.runtime.log?.(`mattermost ${message}`)
1016
+ },
1017
+ ...options.abortSignal ? { abortSignal: options.abortSignal } : {},
1018
+ createStoppedError: () => /* @__PURE__ */ new Error("Mattermost ingress is stopped."),
1019
+ onError: (error) => options.runtime.error?.(`mattermost ingress drain failed: ${formatErrorMessage(error)}`)
1020
+ });
1021
+ monitor.start();
1022
+ return {
1023
+ receive: (rawEvent) => monitor.admit(rawEvent).then(() => void 0),
1024
+ stop: monitor.stop,
1025
+ waitForIdle: monitor.waitForIdle
1026
+ };
1284
1027
  }
1285
1028
  //#endregion
1286
- //#region extensions/mattermost/src/mattermost/monitor.ts
1287
- function normalizeInteractionSourceIps(values) {
1288
- return normalizeTrimmedStringList(values);
1029
+ //#region extensions/mattermost/src/mattermost/monitor-onchar.ts
1030
+ const DEFAULT_ONCHAR_PREFIXES = [">", "!"];
1031
+ function resolveOncharPrefixes(prefixes) {
1032
+ const cleaned = prefixes ? normalizeStringEntries(prefixes) : DEFAULT_ONCHAR_PREFIXES;
1033
+ return cleaned.length > 0 ? cleaned : DEFAULT_ONCHAR_PREFIXES;
1289
1034
  }
1290
- function resolveRuntime(opts) {
1291
- return opts.runtime ?? {
1292
- log: console.log,
1293
- error: console.error,
1035
+ function stripOncharPrefix(text, prefixes) {
1036
+ const trimmed = text.trimStart();
1037
+ for (const prefix of prefixes) {
1038
+ if (!prefix) continue;
1039
+ if (trimmed.startsWith(prefix)) return {
1040
+ triggered: true,
1041
+ stripped: trimmed.slice(prefix.length).trimStart()
1042
+ };
1043
+ }
1044
+ return {
1045
+ triggered: false,
1046
+ stripped: text
1047
+ };
1048
+ }
1049
+ //#endregion
1050
+ //#region extensions/mattermost/src/mattermost/monitor-resources.ts
1051
+ function buildMattermostInboundMediaPayload(media) {
1052
+ return buildChannelInboundMediaPayload(toInboundMediaFacts(media));
1053
+ }
1054
+ function formatMattermostPendingMediaText(params) {
1055
+ return [params.body, formatMediaPlaceholderText(params.media)].filter(Boolean).join("\n").trim();
1056
+ }
1057
+ function formatMattermostInboundMediaText(params) {
1058
+ const materializedCount = params.materializedMedia.filter((media) => Boolean(media.path) || Boolean(media.url)).length;
1059
+ const unavailableCount = Math.max(0, params.nativeMedia.length - materializedCount);
1060
+ if (unavailableCount === 0) return params.body;
1061
+ return formatInboundMediaUnavailableText({
1062
+ body: params.body,
1063
+ notice: `[mattermost ${unavailableCount > 1 ? `${unavailableCount} attachments` : "attachment"} unavailable]`
1064
+ });
1065
+ }
1066
+ const CHANNEL_CACHE_TTL_MS = 5 * 6e4;
1067
+ const USER_CACHE_TTL_MS = 10 * 6e4;
1068
+ const MONITOR_RESOURCE_CACHE_MAX_ENTRIES = 1e3;
1069
+ const MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS = 12e4;
1070
+ const MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS = 3e4;
1071
+ function createMattermostMonitorResources(params) {
1072
+ const { accountId, callbackUrl, client, logger, mediaMaxBytes, saveRemoteMedia, mediaKindFromMime } = params;
1073
+ const channelCache = /* @__PURE__ */ new Map();
1074
+ const userCache = /* @__PURE__ */ new Map();
1075
+ const getCachedValue = (cache, key, nowMs) => {
1076
+ const cached = cache.get(key);
1077
+ if (!cached) return;
1078
+ if (nowMs !== void 0 && cached.expiresAt > nowMs) return cached.value;
1079
+ cache.delete(key);
1080
+ };
1081
+ const setCachedValue = (cache, key, value, ttlMs, rawNowMs) => {
1082
+ const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNowMs });
1083
+ if (expiresAt !== void 0) {
1084
+ cache.delete(key);
1085
+ cache.set(key, {
1086
+ value,
1087
+ expiresAt
1088
+ });
1089
+ pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
1090
+ }
1091
+ };
1092
+ const resolveMattermostMedia = async (fileIds) => {
1093
+ const ids = normalizeStringEntries(fileIds ?? []);
1094
+ if (ids.length === 0) return [];
1095
+ const out = [];
1096
+ for (const fileId of ids) {
1097
+ let downloadUrl;
1098
+ try {
1099
+ downloadUrl = buildMattermostApiUrl(client.baseUrl, `/files/${fileId}`);
1100
+ } catch (err) {
1101
+ logger.debug?.(`mattermost: failed to resolve file ${fileId}: ${String(err)}`);
1102
+ out.push({ kind: "unknown" });
1103
+ continue;
1104
+ }
1105
+ try {
1106
+ const saved = await saveRemoteMedia({
1107
+ url: downloadUrl,
1108
+ requestInit: { headers: { Authorization: `Bearer ${client.token}` } },
1109
+ filePathHint: fileId,
1110
+ maxBytes: mediaMaxBytes,
1111
+ ssrfPolicy: { allowedHostnames: [new URL(client.baseUrl).hostname] },
1112
+ responseHeaderTimeoutMs: MATTERMOST_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
1113
+ readIdleTimeoutMs: MATTERMOST_MEDIA_READ_IDLE_TIMEOUT_MS
1114
+ });
1115
+ const contentType = saved.contentType ?? void 0;
1116
+ out.push({
1117
+ path: saved.path,
1118
+ contentType,
1119
+ kind: mediaKindFromMime(contentType) ?? "unknown"
1120
+ });
1121
+ } catch (err) {
1122
+ logger.debug?.(`mattermost: failed to download file ${fileId}: ${String(err)}`);
1123
+ let contentType;
1124
+ try {
1125
+ contentType = (await client.request(`/files/${fileId}/info`)).mime_type?.trim() || void 0;
1126
+ } catch (infoErr) {
1127
+ logger.debug?.(`mattermost: failed to resolve metadata for file ${fileId}: ${String(infoErr)}`);
1128
+ }
1129
+ out.push({
1130
+ contentType,
1131
+ kind: mediaKindFromMime(contentType) ?? "unknown"
1132
+ });
1133
+ }
1134
+ }
1135
+ return out;
1136
+ };
1137
+ const sendTypingIndicator = async (channelId, parentId) => {
1138
+ await sendMattermostTyping(client, {
1139
+ channelId,
1140
+ parentId
1141
+ });
1142
+ };
1143
+ const resolveChannelInfo = async (channelId) => {
1144
+ const rawNow = Date.now();
1145
+ const cached = getCachedValue(channelCache, channelId, asDateTimestampMs(rawNow));
1146
+ if (cached !== void 0) return cached;
1147
+ try {
1148
+ const info = await fetchMattermostChannel(client, channelId);
1149
+ setCachedValue(channelCache, channelId, info, CHANNEL_CACHE_TTL_MS, rawNow);
1150
+ return info;
1151
+ } catch (err) {
1152
+ logger.debug?.(`mattermost: channel lookup failed: ${String(err)}`);
1153
+ setCachedValue(channelCache, channelId, null, CHANNEL_CACHE_TTL_MS, rawNow);
1154
+ return null;
1155
+ }
1156
+ };
1157
+ const resolveUserInfo = async (userId) => {
1158
+ const rawNow = Date.now();
1159
+ const cached = getCachedValue(userCache, userId, asDateTimestampMs(rawNow));
1160
+ if (cached !== void 0) return cached;
1161
+ try {
1162
+ const info = await fetchMattermostUser(client, userId);
1163
+ setCachedValue(userCache, userId, info, USER_CACHE_TTL_MS, rawNow);
1164
+ return info;
1165
+ } catch (err) {
1166
+ logger.debug?.(`mattermost: user lookup failed: ${String(err)}`);
1167
+ setCachedValue(userCache, userId, null, USER_CACHE_TTL_MS, rawNow);
1168
+ return null;
1169
+ }
1170
+ };
1171
+ const buildModelPickerProps = (channelId, buttons) => buildButtonProps({
1172
+ callbackUrl,
1173
+ accountId,
1174
+ channelId,
1175
+ buttons
1176
+ });
1177
+ const updateModelPickerPost = async (paramsLocal) => {
1178
+ const props = buildModelPickerProps(paramsLocal.channelId, paramsLocal.buttons ?? []) ?? { attachments: [] };
1179
+ await updateMattermostPost(client, paramsLocal.postId, {
1180
+ message: paramsLocal.message,
1181
+ props
1182
+ });
1183
+ return {};
1184
+ };
1185
+ return {
1186
+ resolveMattermostMedia,
1187
+ sendTypingIndicator,
1188
+ resolveChannelInfo,
1189
+ resolveUserInfo,
1190
+ updateModelPickerPost
1191
+ };
1192
+ }
1193
+ //#endregion
1194
+ //#region extensions/mattermost/src/mattermost/monitor-slash.ts
1195
+ function buildSlashCommands(params) {
1196
+ const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
1197
+ if (!params.nativeSkills) return commandsToRegister;
1198
+ try {
1199
+ const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
1200
+ for (const spec of skillCommands) {
1201
+ const name = typeof spec.name === "string" ? spec.name.trim() : "";
1202
+ if (!name) continue;
1203
+ const trigger = name.startsWith("oc_") ? name : `oc_${name}`;
1204
+ commandsToRegister.push({
1205
+ trigger,
1206
+ description: spec.description || `Run skill ${name}`,
1207
+ autoComplete: true,
1208
+ autoCompleteHint: "[args]",
1209
+ originalName: name
1210
+ });
1211
+ }
1212
+ } catch (err) {
1213
+ params.runtime.error?.(`mattermost: failed to list skill commands: ${String(err)}`);
1214
+ }
1215
+ return commandsToRegister;
1216
+ }
1217
+ function dedupeSlashCommands(commands) {
1218
+ const seen = /* @__PURE__ */ new Set();
1219
+ return commands.filter((cmd) => {
1220
+ const key = cmd.trigger.trim();
1221
+ if (!key || seen.has(key)) return false;
1222
+ seen.add(key);
1223
+ return true;
1224
+ });
1225
+ }
1226
+ function buildTriggerMap(commands) {
1227
+ const triggerMap = /* @__PURE__ */ new Map();
1228
+ for (const cmd of commands) if (cmd.originalName) triggerMap.set(cmd.trigger, cmd.originalName);
1229
+ return triggerMap;
1230
+ }
1231
+ function warnOnSuspiciousCallbackUrl(params) {
1232
+ try {
1233
+ const mmHost = new URL(normalizeMattermostBaseUrl(params.baseUrl) ?? params.baseUrl).hostname;
1234
+ const callbackHost = new URL(params.callbackUrl).hostname;
1235
+ if (isLoopbackHost(callbackHost) && !isLoopbackHost(mmHost)) params.runtime.error?.(`mattermost: slash commands callbackUrl resolved to ${params.callbackUrl} (loopback) while baseUrl is ${params.baseUrl}. This MAY be unreachable depending on your deployment. If native slash commands don't work, set channels.mattermost.commands.callbackUrl to a URL reachable from the Mattermost server (e.g. your public reverse proxy URL).`);
1236
+ } catch {}
1237
+ }
1238
+ async function registerSlashCommandsAcrossTeams(params) {
1239
+ const registered = [];
1240
+ let teamRegistrationFailures = 0;
1241
+ for (const team of params.teams) try {
1242
+ const created = await registerSlashCommands({
1243
+ client: params.client,
1244
+ teamId: team.id,
1245
+ creatorUserId: params.botUserId,
1246
+ callbackUrl: params.callbackUrl,
1247
+ commands: params.commands,
1248
+ log: (msg) => params.runtime.log?.(msg)
1249
+ });
1250
+ registered.push(...created);
1251
+ } catch (err) {
1252
+ teamRegistrationFailures += 1;
1253
+ params.runtime.error?.(`mattermost: failed to register slash commands for team ${team.id}: ${String(err)}`);
1254
+ }
1255
+ return {
1256
+ registered,
1257
+ teamRegistrationFailures
1258
+ };
1259
+ }
1260
+ async function registerMattermostMonitorSlashCommands(params) {
1261
+ const commandsRaw = params.account.config.commands;
1262
+ const slashConfig = resolveSlashCommandConfig(commandsRaw);
1263
+ if (!isSlashCommandsEnabled(slashConfig)) return;
1264
+ try {
1265
+ const teams = await fetchMattermostUserTeams(params.client, params.botUserId);
1266
+ const slashCallbackUrl = resolveCallbackUrl({
1267
+ config: slashConfig,
1268
+ gatewayPort: parseTcpPort(process.env.OPENCLAW_GATEWAY_PORT) ?? params.cfg.gateway?.port ?? 18789,
1269
+ gatewayHost: params.cfg.gateway?.customBindHost ?? void 0
1270
+ });
1271
+ warnOnSuspiciousCallbackUrl({
1272
+ runtime: params.runtime,
1273
+ baseUrl: params.baseUrl,
1274
+ callbackUrl: slashCallbackUrl
1275
+ });
1276
+ const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
1277
+ cfg: params.cfg,
1278
+ runtime: params.runtime,
1279
+ nativeSkills: slashConfig.nativeSkills === true
1280
+ }));
1281
+ const { registered, teamRegistrationFailures } = await registerSlashCommandsAcrossTeams({
1282
+ client: params.client,
1283
+ teams,
1284
+ botUserId: params.botUserId,
1285
+ callbackUrl: slashCallbackUrl,
1286
+ commands: dedupedCommands,
1287
+ runtime: params.runtime
1288
+ });
1289
+ if (registered.length === 0) {
1290
+ params.runtime.error?.("mattermost: native slash commands enabled but no commands could be registered; keeping slash callbacks inactive");
1291
+ return;
1292
+ }
1293
+ if (teamRegistrationFailures > 0) params.runtime.error?.(`mattermost: slash command registration completed with ${teamRegistrationFailures} team error(s)`);
1294
+ activateSlashCommands({
1295
+ account: params.account,
1296
+ commandTokens: registered.map((cmd) => cmd.token).filter(Boolean),
1297
+ registeredCommands: registered,
1298
+ triggerMap: buildTriggerMap(dedupedCommands),
1299
+ api: {
1300
+ cfg: params.cfg,
1301
+ runtime: params.runtime
1302
+ },
1303
+ log: (msg) => params.runtime.log?.(msg)
1304
+ });
1305
+ params.runtime.log?.(`mattermost: slash commands registered (${registered.length} commands across ${teams.length} teams, callback=${slashCallbackUrl})`);
1306
+ } catch (err) {
1307
+ params.runtime.error?.(`mattermost: failed to register slash commands: ${String(err)}`);
1308
+ }
1309
+ }
1310
+ //#endregion
1311
+ //#region extensions/mattermost/src/mattermost/reconnect.ts
1312
+ /**
1313
+ * Reconnection loop with exponential backoff.
1314
+ *
1315
+ * Calls `connectFn` in a while loop. On normal resolve (connection closed),
1316
+ * the backoff resets. On thrown error (connection failed), the current delay is
1317
+ * used, then doubled for the next retry.
1318
+ * The loop exits when `abortSignal` fires.
1319
+ */
1320
+ async function runWithReconnect(connectFn, opts = {}) {
1321
+ const { initialDelayMs = 2e3, maxDelayMs = 6e4 } = opts;
1322
+ const jitterRatio = Math.max(0, opts.jitterRatio ?? 0);
1323
+ const random = opts.random ?? Math.random;
1324
+ const backoff = createReconnectBackoff(initialDelayMs, maxDelayMs);
1325
+ let attempt = 0;
1326
+ while (!opts.abortSignal?.aborted) {
1327
+ let outcome = "resolved";
1328
+ let error;
1329
+ try {
1330
+ await connectFn();
1331
+ backoff.reset();
1332
+ } catch (err) {
1333
+ if (opts.abortSignal?.aborted) return;
1334
+ outcome = "rejected";
1335
+ error = err;
1336
+ opts.onError?.(err);
1337
+ }
1338
+ if (opts.abortSignal?.aborted) return;
1339
+ const delayMs = withJitter(backoff.current(), jitterRatio, random);
1340
+ if (!(opts.shouldReconnect?.({
1341
+ attempt,
1342
+ delayMs,
1343
+ outcome,
1344
+ error
1345
+ }) ?? true)) return;
1346
+ opts.onReconnect?.(delayMs);
1347
+ await sleepAbortable(delayMs, opts.abortSignal);
1348
+ if (outcome === "rejected") backoff.increase();
1349
+ attempt++;
1350
+ }
1351
+ }
1352
+ function createReconnectBackoff(initialDelayMs, maxDelayMs) {
1353
+ let retryDelay = initialDelayMs;
1354
+ return {
1355
+ current: () => retryDelay,
1356
+ reset: () => {
1357
+ retryDelay = initialDelayMs;
1358
+ },
1359
+ increase: () => {
1360
+ retryDelay = Math.min(retryDelay * 2, maxDelayMs);
1361
+ }
1362
+ };
1363
+ }
1364
+ function withJitter(baseMs, jitterRatio, random) {
1365
+ if (jitterRatio <= 0) return baseMs;
1366
+ const normalized = Math.max(0, Math.min(1, random()));
1367
+ const spread = baseMs * jitterRatio;
1368
+ return Math.max(1, Math.round(baseMs - spread + normalized * spread * 2));
1369
+ }
1370
+ function sleepAbortable(ms, signal) {
1371
+ return new Promise((resolve) => {
1372
+ if (signal?.aborted) {
1373
+ resolve();
1374
+ return;
1375
+ }
1376
+ const onAbort = () => {
1377
+ clearTimeout(timer);
1378
+ resolve();
1379
+ };
1380
+ const timer = setTimeout(() => {
1381
+ signal?.removeEventListener("abort", onAbort);
1382
+ resolve();
1383
+ }, ms);
1384
+ signal?.addEventListener("abort", onAbort, { once: true });
1385
+ });
1386
+ }
1387
+ //#endregion
1388
+ //#region extensions/mattermost/src/mattermost/thread-participation.ts
1389
+ const threadParticipation = createPersistentDedupeCache({
1390
+ globalKey: Symbol.for("openclaw.mattermostThreadParticipation"),
1391
+ ttlMs: 10080 * 60 * 1e3,
1392
+ maxSize: 5e3,
1393
+ persistent: {
1394
+ namespace: "mattermost.thread-participation",
1395
+ maxEntries: 1e3,
1396
+ openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
1397
+ logError: (error) => {
1398
+ try {
1399
+ getOptionalMattermostRuntime()?.logging.getChildLogger({
1400
+ plugin: "mattermost",
1401
+ feature: "thread-participation-state"
1402
+ }).warn("Mattermost persistent thread participation state failed", { error: String(error) });
1403
+ } catch {}
1404
+ }
1405
+ }
1406
+ });
1407
+ function makeKey(accountId, channelId, threadRootId) {
1408
+ return `${accountId}:${channelId}:${threadRootId}`;
1409
+ }
1410
+ function recordMattermostThreadParticipation(accountId, channelId, threadRootId, opts) {
1411
+ if (!accountId || !channelId || !threadRootId) return;
1412
+ threadParticipation.register(makeKey(accountId, channelId, threadRootId), {
1413
+ ...opts?.agentId ? { agentId: opts.agentId } : {},
1414
+ repliedAt: Date.now()
1415
+ });
1416
+ }
1417
+ async function hasMattermostThreadParticipationWithPersistence(params) {
1418
+ if (!params.accountId || !params.channelId || !params.threadRootId) return false;
1419
+ return await threadParticipation.lookup(makeKey(params.accountId, params.channelId, params.threadRootId));
1420
+ }
1421
+ //#endregion
1422
+ //#region extensions/mattermost/src/mattermost/monitor.ts
1423
+ function normalizeInteractionSourceIps(values) {
1424
+ return normalizeTrimmedStringList(values);
1425
+ }
1426
+ function resolveRuntime(opts) {
1427
+ return opts.runtime ?? {
1428
+ log: console.log,
1429
+ error: console.error,
1294
1430
  exit: (code) => {
1295
1431
  throw new Error(`exit ${code}`);
1296
1432
  }
@@ -1323,18 +1459,6 @@ function createDisabledMattermostDraftStream() {
1323
1459
  })
1324
1460
  };
1325
1461
  }
1326
- function buildMattermostAttachmentPlaceholder(mediaList) {
1327
- if (mediaList.length === 0) return "";
1328
- if (mediaList.length === 1) {
1329
- const media = mediaList[0];
1330
- if (!media) return "";
1331
- return `<media:${media.kind === "unknown" ? "document" : media.kind}>`;
1332
- }
1333
- const allImages = mediaList.every((media) => media.kind === "image");
1334
- const label = allImages ? "image" : "file";
1335
- const suffix = mediaList.length === 1 ? label : `${label}s`;
1336
- return `${allImages ? "<media:image>" : "<media:document>"} (${mediaList.length} ${suffix})`;
1337
- }
1338
1462
  function buildMattermostWsUrl(baseUrl) {
1339
1463
  const normalized = normalizeMattermostBaseUrl(baseUrl);
1340
1464
  if (!normalized) throw new Error("Mattermost baseUrl is required");
@@ -1507,7 +1631,7 @@ async function monitorMattermostProvider(opts = {}) {
1507
1631
  });
1508
1632
  const to = kind === "direct" ? `user:${optsLocal.userId}` : `channel:${optsLocal.channelId}`;
1509
1633
  const bodyText = `[Button click: user @${optsLocal.userName} selected "${optsLocal.actionName}"]`;
1510
- const ctxPayload = core.channel.reply.finalizeInboundContext({
1634
+ const ctxPayload = finalizeInboundContext({
1511
1635
  Body: bodyText,
1512
1636
  BodyForAgent: bodyText,
1513
1637
  RawBody: bodyText,
@@ -1515,6 +1639,7 @@ async function monitorMattermostProvider(opts = {}) {
1515
1639
  From: kind === "direct" ? `mattermost:${optsLocal.userId}` : kind === "group" ? `mattermost:group:${optsLocal.channelId}` : `mattermost:channel:${optsLocal.channelId}`,
1516
1640
  To: to,
1517
1641
  SessionKey: threadContext.sessionKey,
1642
+ DmScope: route.dmScope,
1518
1643
  ParentSessionKey: threadContext.parentSessionKey,
1519
1644
  AccountId: route.accountId,
1520
1645
  ChatType: chatType,
@@ -1561,51 +1686,43 @@ async function monitorMattermostProvider(opts = {}) {
1561
1686
  isDirect: kind === "direct",
1562
1687
  dmRetryOptions: account.config.dmChannelRetry
1563
1688
  });
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();
1689
+ await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1690
+ ctx: ctxPayload,
1691
+ cfg,
1692
+ dispatcherOptions: {
1693
+ ...replyPipeline,
1694
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1695
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1696
+ humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
1697
+ deliver: async (payload) => {
1698
+ await deliverMattermostReplyPayload({
1699
+ core,
1700
+ cfg,
1701
+ payload,
1702
+ to,
1703
+ accountId: account.accountId,
1704
+ agentId: route.agentId,
1705
+ replyToId: resolveMattermostReplyRootId({
1706
+ kind,
1707
+ threadRootId: threadContext.effectiveReplyToId,
1708
+ replyToId: payload.replyToId
1709
+ }),
1710
+ textLimit,
1711
+ tableMode,
1712
+ sendMessage: sendMessageMattermost,
1713
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1714
+ });
1715
+ runtime.log?.(`delivered button-click reply to ${to}`);
1716
+ },
1717
+ onError: (err, info) => {
1718
+ runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
1719
+ },
1720
+ typingCallbacks
1598
1721
  },
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
- })
1722
+ replyOptions: {
1723
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1724
+ onModelSelected
1725
+ }
1609
1726
  });
1610
1727
  },
1611
1728
  log: (msg) => runtime.log?.(msg)
@@ -1652,7 +1769,7 @@ async function monitorMattermostProvider(opts = {}) {
1652
1769
  const runModelPickerCommand = async (params) => {
1653
1770
  const to = params.kind === "direct" ? `user:${params.senderId}` : `channel:${params.channelId}`;
1654
1771
  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({
1772
+ const ctxPayload = finalizeInboundContext({
1656
1773
  Body: params.commandText,
1657
1774
  BodyForAgent: params.commandText,
1658
1775
  RawBody: params.commandText,
@@ -1660,6 +1777,7 @@ async function monitorMattermostProvider(opts = {}) {
1660
1777
  From: params.kind === "direct" ? `mattermost:${params.senderId}` : params.kind === "group" ? `mattermost:group:${params.channelId}` : `mattermost:channel:${params.channelId}`,
1661
1778
  To: to,
1662
1779
  SessionKey: params.sessionKey,
1780
+ DmScope: params.route.dmScope,
1663
1781
  ParentSessionKey: params.parentSessionKey,
1664
1782
  AccountId: params.route.accountId,
1665
1783
  ChatType: params.chatType,
@@ -1710,57 +1828,49 @@ async function monitorMattermostProvider(opts = {}) {
1710
1828
  isDirect: params.kind === "direct",
1711
1829
  dmRetryOptions: account.config.dmChannelRetry
1712
1830
  });
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();
1831
+ await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1832
+ ctx: ctxPayload,
1833
+ cfg,
1834
+ dispatcherOptions: {
1835
+ ...replyPipeline,
1836
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
1837
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
1838
+ deliver: async (payload) => {
1839
+ const trimmedPayload = {
1840
+ ...payload,
1841
+ text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
1842
+ };
1843
+ if (!shouldDeliverReplies) {
1844
+ if (trimmedPayload.text) capturedTexts.push(trimmedPayload.text);
1845
+ return;
1846
+ }
1847
+ await deliverMattermostReplyPayload({
1848
+ core,
1849
+ cfg,
1850
+ payload: trimmedPayload,
1851
+ to,
1852
+ accountId: account.accountId,
1853
+ agentId: params.route.agentId,
1854
+ replyToId: resolveMattermostReplyRootId({
1855
+ kind: params.kind,
1856
+ threadRootId: params.effectiveReplyToId,
1857
+ replyToId: trimmedPayload.replyToId
1858
+ }),
1859
+ textLimit,
1860
+ tableMode: "off",
1861
+ sendMessage: sendMessageMattermost,
1862
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
1863
+ });
1864
+ },
1865
+ onError: (err, info) => {
1866
+ runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
1867
+ },
1868
+ typingCallbacks
1753
1869
  },
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
- })
1870
+ replyOptions: {
1871
+ disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
1872
+ onModelSelected
1873
+ }
1764
1874
  });
1765
1875
  return capturedTexts.join("\n\n").trim();
1766
1876
  };
@@ -1925,644 +2035,628 @@ async function monitorMattermostProvider(opts = {}) {
1925
2035
  })();
1926
2036
  return {};
1927
2037
  }
1928
- const handlePost = async (post, payload, messageIds) => {
2038
+ const handlePost = async (post, payload, turnAdoptionLifecycle, messageIds) => {
1929
2039
  const channelId = post.channel_id ?? payload.data?.channel_id ?? payload.broadcast?.channel_id;
1930
2040
  if (!channelId) {
1931
2041
  logVerboseMessage("mattermost: drop post (missing channel id)");
1932
2042
  return;
1933
2043
  }
1934
- const allMessageIds = messageIds?.length ? messageIds : post.id ? [post.id] : [];
1935
- if (allMessageIds.length === 0) {
1936
- logVerboseMessage("mattermost: drop post (missing message id)");
2044
+ if (!post.id) {
2045
+ logVerboseMessage("mattermost: drop post (missing message id)");
2046
+ return;
2047
+ }
2048
+ const allMessageIds = messageIds?.length ? messageIds : [post.id];
2049
+ const senderId = post.user_id ?? payload.broadcast?.user_id;
2050
+ if (!senderId) {
2051
+ logVerboseMessage("mattermost: drop post (missing sender id)");
2052
+ return;
2053
+ }
2054
+ if (senderId === botUserId) {
2055
+ logVerboseMessage(`mattermost: drop post (self sender=${senderId})`);
2056
+ return;
2057
+ }
2058
+ if (isSystemPost(post)) {
2059
+ logVerboseMessage(`mattermost: drop post (system post type=${post.type ?? "unknown"})`);
2060
+ return;
2061
+ }
2062
+ const channelInfo = await resolveChannelInfo(channelId);
2063
+ const channelType = normalizeOptionalString(channelInfo?.type) ?? normalizeOptionalString(payload.data?.channel_type);
2064
+ if (!channelType) {
2065
+ logVerboseMessage(`mattermost: drop post (cannot resolve channel type for ${channelId})`);
2066
+ return;
2067
+ }
2068
+ const kind = resolveMattermostTrustedChatKind({ channelType });
2069
+ const chatType = channelChatType(kind);
2070
+ const senderName = normalizeOptionalString(payload.data?.sender_name) ?? normalizeOptionalString((await resolveUserInfo(senderId))?.username) ?? senderId;
2071
+ const rawPostText = typeof post.message === "string" ? post.message : "";
2072
+ const rawText = normalizeOptionalString(rawPostText) ?? "";
2073
+ const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
2074
+ cfg,
2075
+ surface: "mattermost"
2076
+ });
2077
+ const isControlCommand = allowTextCommands && core.channel.commands.isControlCommandMessage(rawText, cfg);
2078
+ const accessDecision = await resolveMattermostMonitorInboundAccess({
2079
+ account,
2080
+ cfg,
2081
+ senderId,
2082
+ senderName,
2083
+ channelId,
2084
+ kind,
2085
+ groupPolicy,
2086
+ readStoreAllowFrom: pairing.readAllowFromStore,
2087
+ allowTextCommands,
2088
+ hasControlCommand: isControlCommand,
2089
+ eventKind: "message",
2090
+ mayPair: true
2091
+ });
2092
+ const commandAuthorized = accessDecision.commandAccess.authorized;
2093
+ if (accessDecision.ingress.decision !== "allow") {
2094
+ if (kind === "direct") {
2095
+ if (accessDecision.ingress.reasonCode === "dm_policy_disabled") {
2096
+ logVerboseMessage(`mattermost: drop dm (dmPolicy=disabled sender=${senderId})`);
2097
+ return;
2098
+ }
2099
+ if (accessDecision.ingress.decision === "pairing") {
2100
+ const { code, created } = await pairing.upsertPairingRequest({
2101
+ id: senderId,
2102
+ meta: { name: senderName }
2103
+ });
2104
+ logVerboseMessage(`mattermost: pairing request sender=${senderId} created=${created}`);
2105
+ if (created) try {
2106
+ await sendMessageMattermost(`user:${senderId}`, core.channel.pairing.buildPairingReply({
2107
+ channel: "mattermost",
2108
+ idLine: `Your Mattermost user id: ${senderId}`,
2109
+ code
2110
+ }), {
2111
+ cfg,
2112
+ accountId: account.accountId
2113
+ });
2114
+ opts.statusSink?.({ lastOutboundAt: Date.now() });
2115
+ } catch (err) {
2116
+ logVerboseMessage(`mattermost: pairing reply failed for ${senderId}: ${String(err)}`);
2117
+ }
2118
+ return;
2119
+ }
2120
+ logVerboseMessage(formatMattermostDirectMessageDropLog({
2121
+ senderId,
2122
+ dmPolicy,
2123
+ reasonCode: accessDecision.senderAccess.reasonCode
2124
+ }));
2125
+ return;
2126
+ }
2127
+ if (accessDecision.ingress.reasonCode === "group_policy_disabled") {
2128
+ logVerboseMessage("mattermost: drop group message (groupPolicy=disabled)");
2129
+ return;
2130
+ }
2131
+ if (accessDecision.ingress.reasonCode === "group_policy_empty_allowlist") {
2132
+ logVerboseMessage("mattermost: drop group message (no group allowlist)");
2133
+ return;
2134
+ }
2135
+ if (accessDecision.ingress.reasonCode === "group_policy_not_allowlisted") {
2136
+ logVerboseMessage(`mattermost: drop group sender=${senderId} (not in groupAllowFrom)`);
2137
+ return;
2138
+ }
2139
+ logVerboseMessage(`mattermost: drop group message (groupPolicy=${groupPolicy} reason=${accessDecision.senderAccess.reasonCode})`);
2140
+ return;
2141
+ }
2142
+ if (kind !== "direct" && accessDecision.commandAccess.shouldBlockControlCommand) {
2143
+ logInboundDrop({
2144
+ log: logVerboseMessage,
2145
+ channel: "mattermost",
2146
+ reason: "control command (unauthorized)",
2147
+ target: senderId
2148
+ });
2149
+ return;
2150
+ }
2151
+ const teamId = payload.data?.team_id ?? channelInfo?.team_id ?? void 0;
2152
+ const channelName = payload.data?.channel_name ?? channelInfo?.name ?? "";
2153
+ const channelDisplay = payload.data?.channel_display_name ?? channelInfo?.display_name ?? channelName;
2154
+ const roomLabel = channelName ? `#${channelName}` : channelDisplay || `#${channelId}`;
2155
+ const route = core.channel.routing.resolveAgentRoute({
2156
+ cfg,
2157
+ channel: "mattermost",
2158
+ accountId: account.accountId,
2159
+ teamId,
2160
+ peer: {
2161
+ kind,
2162
+ id: kind === "direct" ? senderId : channelId
2163
+ }
2164
+ });
2165
+ const baseSessionKey = route.sessionKey;
2166
+ const threadRootId = normalizeOptionalString(post.root_id);
2167
+ const replyToMode = resolveMattermostReplyToMode(account, kind);
2168
+ const { effectiveReplyToId, sessionKey, parentSessionKey } = resolveMattermostThreadSessionContext({
2169
+ baseSessionKey,
2170
+ kind,
2171
+ postId: post.id,
2172
+ replyToMode,
2173
+ threadRootId
2174
+ });
2175
+ const historyKey = resolveMattermostPendingHistoryKey({
2176
+ kind,
2177
+ sessionKey
2178
+ });
2179
+ const fileIds = uniqueStrings(normalizeTrimmedStringList(post.file_ids ?? []));
2180
+ const nativeMedia = fileIds.map(() => ({}));
2181
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(cfg, route.agentId);
2182
+ const wasMentioned = kind !== "direct" && ((botUsername ? normalizeLowercaseStringOrEmpty(rawText).includes(`@${normalizeLowercaseStringOrEmpty(botUsername)}`) : false) || core.channel.mentions.matchesMentionPatterns(rawText, mentionRegexes));
2183
+ const pendingBody = formatMattermostPendingMediaText({
2184
+ body: rawText,
2185
+ media: nativeMedia
2186
+ });
2187
+ const pendingSender = senderName;
2188
+ const recordPendingHistory = () => {
2189
+ const trimmed = pendingBody.trim();
2190
+ createChannelHistoryWindow({ historyMap: channelHistories }).record({
2191
+ limit: historyLimit,
2192
+ historyKey: historyKey ?? "",
2193
+ entry: historyKey && trimmed ? {
2194
+ sender: pendingSender,
2195
+ body: trimmed,
2196
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2197
+ messageId: post.id ?? void 0
2198
+ } : null
2199
+ });
2200
+ };
2201
+ const oncharEnabled = account.chatmode === "onchar" && kind !== "direct";
2202
+ const oncharPrefixes = oncharEnabled ? resolveOncharPrefixes(account.oncharPrefixes) : [];
2203
+ const oncharResult = oncharEnabled ? stripOncharPrefix(rawText, oncharPrefixes) : {
2204
+ triggered: false,
2205
+ stripped: rawText
2206
+ };
2207
+ const oncharTriggered = oncharResult.triggered;
2208
+ const canDetectMention = Boolean(botUsername) || mentionRegexes.length > 0;
2209
+ const threadAlreadyEngaged = kind !== "direct" && effectiveReplyToId ? await hasMattermostThreadParticipationWithPersistence({
2210
+ accountId: account.accountId,
2211
+ channelId,
2212
+ threadRootId: effectiveReplyToId
2213
+ }) : false;
2214
+ const shouldRequireMention = kind !== "direct" && core.channel.groups.resolveRequireMention({
2215
+ cfg,
2216
+ channel: "mattermost",
2217
+ accountId: account.accountId,
2218
+ groupId: channelId,
2219
+ requireMentionOverride: account.requireMention
2220
+ });
2221
+ const implicitMentionKinds = implicitMentionKindWhen("bot_thread_participant", threadAlreadyEngaged);
2222
+ const mentionDecision = resolveMattermostInboundMentionDecision({
2223
+ cfg,
2224
+ accountId: account.accountId,
2225
+ kind,
2226
+ requireMention: shouldRequireMention || oncharEnabled,
2227
+ canDetectMention: canDetectMention || oncharEnabled,
2228
+ wasMentioned: wasMentioned || oncharTriggered,
2229
+ implicitMentionKinds,
2230
+ allowTextCommands,
2231
+ hasControlCommand: isControlCommand,
2232
+ commandAuthorized
2233
+ });
2234
+ const { shouldBypassMention } = mentionDecision;
2235
+ if (mentionDecision.shouldSkip && oncharEnabled && !oncharTriggered && !wasMentioned && !shouldBypassMention) {
2236
+ logVerboseMessage(`mattermost: drop group message (onchar not triggered channel=${channelId} sender=${senderId})`);
2237
+ recordPendingHistory();
2238
+ return;
2239
+ }
2240
+ if (mentionDecision.shouldSkip) {
2241
+ logVerboseMessage(`mattermost: drop group message (missing mention channel=${channelId} sender=${senderId} requireMention=${shouldRequireMention} bypass=${shouldBypassMention} canDetectMention=${canDetectMention})`);
2242
+ recordPendingHistory();
2243
+ return;
2244
+ }
2245
+ const mediaList = await resolveMattermostMedia(fileIds);
2246
+ const bodyText = normalizeMention(formatMattermostInboundMediaText({
2247
+ body: oncharTriggered ? oncharResult.stripped : rawText,
2248
+ nativeMedia,
2249
+ materializedMedia: mediaList
2250
+ }), botUsername);
2251
+ if (mediaList.length === 0 && shouldDropEmptyMattermostBody({
2252
+ bodyText,
2253
+ rawText: rawPostText,
2254
+ botUsername
2255
+ })) {
2256
+ logVerboseMessage(`mattermost: drop message (empty body after normalization channel=${channelId} sender=${senderId} wasMentioned=${wasMentioned})`);
1937
2257
  return;
1938
2258
  }
1939
- if (await processMattermostReplayGuardedPost({
2259
+ const bodyForAgent = bodyText || rawText.trim();
2260
+ core.channel.activity.record({
2261
+ channel: "mattermost",
1940
2262
  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,
2263
+ direction: "inbound"
2264
+ });
2265
+ const fromLabel = formatInboundFromLabel$1({
2266
+ isGroup: kind !== "direct",
2267
+ groupLabel: channelDisplay || roomLabel,
2268
+ groupId: channelId,
2269
+ groupFallback: roomLabel || "Channel",
2270
+ directLabel: senderName,
2271
+ directId: senderId
2272
+ });
2273
+ const textWithId = `${bodyText}\n[mattermost message id: ${post.id ?? "unknown"} channel: ${channelId}]`;
2274
+ let combinedBody = formatInboundEnvelope({
2275
+ channel: "Mattermost",
2276
+ from: fromLabel,
2277
+ timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2278
+ body: textWithId,
2279
+ chatType,
2280
+ sender: {
2281
+ name: senderName,
2282
+ id: senderId
2283
+ }
2284
+ });
2285
+ if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: channelHistories }).buildPendingContext({
2286
+ historyKey,
2287
+ limit: historyLimit,
2288
+ currentMessage: combinedBody,
2289
+ formatEntry: (entry) => formatInboundEnvelope({
2290
+ channel: "Mattermost",
2291
+ from: fromLabel,
2292
+ timestamp: entry.timestamp,
2293
+ body: `${entry.body}${entry.messageId ? ` [id:${entry.messageId} channel:${channelId}]` : ""}`,
2294
+ chatType,
2295
+ senderLabel: entry.sender
2296
+ })
2297
+ });
2298
+ const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
2299
+ const mediaPayload = buildMattermostInboundMediaPayload(mediaList);
2300
+ const commandBody = rawText.trim();
2301
+ const inboundHistory = historyKey && historyLimit > 0 ? createChannelHistoryWindow({ historyMap: channelHistories }).buildInboundHistory({
2302
+ historyKey,
2303
+ limit: historyLimit
2304
+ }) : void 0;
2305
+ const ctxPayload = finalizeInboundContext({
2306
+ Body: combinedBody,
2307
+ BodyForAgent: bodyForAgent,
2308
+ InboundHistory: inboundHistory,
2309
+ RawBody: commandBody,
2310
+ CommandBody: commandBody,
2311
+ BodyForCommands: commandBody,
2312
+ From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
2313
+ To: to,
2314
+ SessionKey: sessionKey,
2315
+ DmScope: route.dmScope,
2316
+ ParentSessionKey: parentSessionKey,
2317
+ AccountId: route.accountId,
2318
+ ChatType: chatType,
2319
+ ConversationLabel: fromLabel,
2320
+ GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
2321
+ GroupChannel: channelName ? `#${channelName}` : void 0,
2322
+ GroupSpace: teamId,
2323
+ SenderName: senderName,
2324
+ SenderId: senderId,
2325
+ Provider: "mattermost",
2326
+ Surface: "mattermost",
2327
+ MessageSid: post.id ?? void 0,
2328
+ MessageSids: allMessageIds.length > 1 ? allMessageIds : void 0,
2329
+ MessageSidFirst: allMessageIds.length > 1 ? allMessageIds[0] : void 0,
2330
+ MessageSidLast: allMessageIds.length > 1 ? allMessageIds[allMessageIds.length - 1] : void 0,
2331
+ ReplyToId: effectiveReplyToId,
2332
+ MessageThreadId: effectiveReplyToId,
2333
+ Timestamp: typeof post.create_at === "number" ? post.create_at : void 0,
2334
+ WasMentioned: kind !== "direct" ? mentionDecision.effectiveWasMentioned : void 0,
2335
+ CommandAuthorized: commandAuthorized,
2336
+ CommandSource: commandAuthorized && isControlCommand ? "text" : void 0,
2337
+ OriginatingChannel: "mattermost",
2338
+ OriginatingTo: to,
2339
+ ...mediaPayload
2340
+ });
2341
+ const pinnedMainDmOwner = kind === "direct" ? resolvePinnedMainDmOwnerFromAllowlist({
2342
+ dmScope: cfg.session?.dmScope,
2343
+ allowFrom: account.config.allowFrom,
2344
+ normalizeEntry: normalizeMattermostAllowEntry
2345
+ }) : null;
2346
+ const previewLine = truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n");
2347
+ logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
2348
+ const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
2349
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2350
+ cfg,
2351
+ channel: "mattermost",
2352
+ accountId: account.accountId
2353
+ });
2354
+ const chunkMode = core.channel.text.resolveChunkMode(cfg, "mattermost", account.accountId);
2355
+ const { onModelSelected, typingCallbacks, resolveResponsePrefix, ...replyPipeline } = createChannelMessageReplyPipeline({
2356
+ cfg,
2357
+ agentId: route.agentId,
2358
+ channel: "mattermost",
2359
+ accountId: account.accountId,
2360
+ typing: {
2361
+ start: () => sendTypingIndicator(channelId, effectiveReplyToId),
2362
+ onStartError: (err) => {
2363
+ logTypingFailure({
2364
+ log: (message) => logger.debug?.(message),
2039
2365
  channel: "mattermost",
2040
- reason: "control command (unauthorized)",
2041
- target: senderId
2366
+ target: channelId,
2367
+ error: err
2042
2368
  });
2043
- return;
2044
2369
  }
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
2370
+ }
2371
+ });
2372
+ const draftPreviewEnabled = account.streamingMode !== "off";
2373
+ const draftToolProgressEnabled = shouldUpdateMattermostDraftToolProgress(account);
2374
+ const suppressDefaultToolProgressMessages = shouldSuppressMattermostDefaultToolProgressMessages(account);
2375
+ const draftStream = draftPreviewEnabled ? createMattermostDraftStream({
2376
+ client,
2377
+ channelId,
2378
+ rootId: effectiveReplyToId,
2379
+ throttleMs: 1200,
2380
+ chunkText: (value) => core.channel.text.chunkMarkdownTextWithMode(core.channel.text.convertMarkdownTables(value, tableMode), textLimit, chunkMode),
2381
+ log: logVerboseMessage,
2382
+ warn: logVerboseMessage
2383
+ }) : createDisabledMattermostDraftStream();
2384
+ const previewBoundaryController = createMattermostDraftPreviewBoundaryController({
2385
+ enabled: draftPreviewEnabled && account.streamingMode === "block",
2386
+ forceNewMessage: async () => {
2387
+ await draftStream.forceNewMessage();
2388
+ }
2389
+ });
2390
+ let lastPartialText = "";
2391
+ let firstAssistantPreviewPrefix;
2392
+ let firstAssistantPreviewPrefixPending = true;
2393
+ let currentAssistantPreviewUsesPrefix = false;
2394
+ let blockPreviewActivity = "none";
2395
+ let blockPreviewAssistantMessagePending = false;
2396
+ const progressDraft = createChannelProgressDraftCompositor({
2397
+ entry: account.config,
2398
+ mode: account.streamingMode,
2399
+ active: draftPreviewEnabled,
2400
+ seed: `${account.accountId}:${channelId}`,
2401
+ update: async (previewText, options) => {
2402
+ draftStream.update(previewText);
2403
+ if (options?.flush) await draftStream.flush();
2404
+ }
2405
+ });
2406
+ const enterBlockPreviewActivity = (activity) => {
2407
+ if (account.streamingMode !== "block") return;
2408
+ const continuesCurrentActivity = activity === "tool" && blockPreviewActivity === "tool" || activity === "text" && blockPreviewActivity === "text" && !blockPreviewAssistantMessagePending || activity === "reasoning" && blockPreviewActivity === "reasoning";
2409
+ const startsNewGeneration = !continuesCurrentActivity && !(blockPreviewActivity === "reasoning");
2410
+ if (startsNewGeneration) currentAssistantPreviewUsesPrefix = false;
2411
+ const boundarySettled = startsNewGeneration ? previewBoundaryController.noteBoundary() : void 0;
2412
+ if (!continuesCurrentActivity) progressDraft.reset();
2413
+ blockPreviewActivity = activity;
2414
+ blockPreviewAssistantMessagePending = false;
2415
+ if (activity === "tool") lastPartialText = "";
2416
+ return boundarySettled;
2417
+ };
2418
+ const previewState = { finalizedViaPreviewPost: false };
2419
+ const resolveFinalDeliveryText = (text) => {
2420
+ if (typeof text !== "string") return;
2421
+ const resolution = draftStream.resolveFinalText(text);
2422
+ return resolution.kind === "already-delivered" ? "" : resolution.text;
2423
+ };
2424
+ const resolvePreviewFinalText = (text) => {
2425
+ const deliveryText = resolveFinalDeliveryText(text);
2426
+ if (typeof deliveryText !== "string") return;
2427
+ const formatted = core.channel.text.convertMarkdownTables(deliveryText, tableMode);
2428
+ const chunks = core.channel.text.chunkMarkdownTextWithMode(formatted, textLimit, chunkMode);
2429
+ if (!chunks.length && formatted) chunks.push(formatted);
2430
+ if (chunks.length != 1) return;
2431
+ const trimmed = chunks[0]?.trim();
2432
+ if (!trimmed) return;
2433
+ if (lastPartialText && lastPartialText.startsWith(trimmed) && trimmed.length < lastPartialText.length) return;
2434
+ return trimmed;
2435
+ };
2436
+ const updateDraftFromPartial = (text) => {
2437
+ const cleaned = text?.trim();
2438
+ if (!cleaned) return;
2439
+ if (cleaned === lastPartialText) return;
2440
+ if (lastPartialText && lastPartialText.startsWith(cleaned) && cleaned.length < lastPartialText.length) return;
2441
+ const boundarySettled = enterBlockPreviewActivity("text");
2442
+ lastPartialText = cleaned;
2443
+ if (firstAssistantPreviewPrefixPending) {
2444
+ firstAssistantPreviewPrefix = resolveResponsePrefix?.();
2445
+ firstAssistantPreviewPrefixPending = false;
2446
+ currentAssistantPreviewUsesPrefix = Boolean(firstAssistantPreviewPrefix);
2447
+ }
2448
+ const previewText = currentAssistantPreviewUsesPrefix && firstAssistantPreviewPrefix ? cleaned.startsWith(firstAssistantPreviewPrefix) ? cleaned : `${firstAssistantPreviewPrefix} ${cleaned}` : cleaned;
2449
+ draftStream.updateAssistantText(previewText);
2450
+ previewBoundaryController.noteUpdate();
2451
+ return boundarySettled;
2452
+ };
2453
+ const deliveryBarrier = createMattermostReplyDeliveryBarrier({
2454
+ isDirect: kind === "direct",
2455
+ dmRetryOptions: account.config.dmChannelRetry
2456
+ });
2457
+ const dispatcherOptions = {
2458
+ ...replyPipeline,
2459
+ resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
2460
+ onDeliverySettled: deliveryBarrier.markDeliverySettled,
2461
+ humanDelay: resolveHumanDelayConfig(cfg, route.agentId),
2462
+ typingCallbacks
2463
+ };
2464
+ const delivery = {
2465
+ deliver: async (payloadEntry, info) => {
2466
+ if (info.kind === "final") {
2467
+ await enterBlockPreviewActivity("text");
2468
+ await draftStream.settleBoundaries();
2469
+ progressDraft.markFinalReplyStarted();
2470
+ }
2471
+ const markThreadParticipation = () => {
2472
+ if (kind !== "direct" && effectiveReplyToId) recordMattermostThreadParticipation(account.accountId, channelId, effectiveReplyToId, { agentId: route.agentId });
2095
2473
  };
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({
2474
+ await deliverMattermostReplyWithDraftPreview({
2475
+ payload: payloadEntry,
2476
+ info,
2104
2477
  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
2478
  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
- }
2479
+ draftStream,
2480
+ effectiveReplyToId,
2481
+ resolvePreviewFinalText,
2482
+ previewState,
2483
+ logVerboseMessage,
2484
+ recordThreadParticipation: markThreadParticipation,
2485
+ deliverPayload: async (payloadToDeliver) => {
2486
+ const finalTextResolution = info.kind === "final" && !payloadToDeliver.isError && typeof payloadToDeliver.text === "string" ? draftStream.resolveFinalText(payloadToDeliver.text) : void 0;
2487
+ const resolvedPayload = finalTextResolution ? {
2488
+ ...payloadToDeliver,
2489
+ text: finalTextResolution.kind === "already-delivered" ? "" : finalTextResolution.text
2490
+ } : payloadToDeliver;
2491
+ const outcome = await deliverMattermostReplyPayload({
2492
+ core,
2493
+ cfg,
2494
+ payload: resolvedPayload,
2495
+ to,
2496
+ accountId: account.accountId,
2497
+ agentId: route.agentId,
2498
+ replyToId: resolveMattermostReplyRootId({
2499
+ kind,
2500
+ threadRootId: effectiveReplyToId,
2501
+ replyToId: payloadToDeliver.replyToId
2502
+ }),
2503
+ textLimit,
2504
+ tableMode,
2505
+ sendMessage: sendMessageMattermost,
2506
+ onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
2405
2507
  });
2406
- if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2407
- },
2408
- onError: (err, info) => {
2409
- runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
2508
+ if (outcome === "text" || outcome === "media") markThreadParticipation();
2509
+ else if (outcome === "empty" && finalTextResolution?.kind === "already-delivered") markThreadParticipation();
2510
+ const deliveryLog = formatMattermostFinalDeliveryOutcomeLog({
2511
+ outcome,
2512
+ payload: resolvedPayload,
2513
+ to,
2514
+ accountId: account.accountId,
2515
+ agentId: route.agentId
2516
+ });
2517
+ if (deliveryLog) runtime.log?.(deliveryLog);
2410
2518
  }
2411
2519
  });
2412
- const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
2413
- route,
2414
- sessionKey: route.sessionKey
2415
- });
2416
- let dispatchSettledBeforeStart = false;
2417
- try {
2418
- await core.channel.inbound.run({
2520
+ if (info.kind === "final") progressDraft.markFinalReplyDelivered();
2521
+ },
2522
+ onError: (err, info) => {
2523
+ runtime.error?.(`mattermost ${info.kind} reply failed: ${String(err)}`);
2524
+ }
2525
+ };
2526
+ const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
2527
+ route,
2528
+ sessionKey: route.sessionKey
2529
+ });
2530
+ try {
2531
+ await core.channel.inbound.run({
2532
+ channel: "mattermost",
2533
+ accountId: route.accountId,
2534
+ raw: post,
2535
+ adapter: {
2536
+ ingest: () => ({
2537
+ id: post.id ?? `${to}:${Date.now()}`,
2538
+ timestamp: post.create_at ?? void 0,
2539
+ rawText,
2540
+ textForAgent: ctxPayload.BodyForAgent,
2541
+ textForCommands: ctxPayload.CommandBody,
2542
+ raw: post
2543
+ }),
2544
+ resolveTurn: () => ({
2545
+ cfg,
2419
2546
  channel: "mattermost",
2420
2547
  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: () => ({
2548
+ route: {
2549
+ agentId: route.agentId,
2550
+ dmScope: route.dmScope,
2551
+ sessionKey: route.sessionKey
2552
+ },
2553
+ ctxPayload,
2554
+ record: {
2555
+ updateLastRoute: kind === "direct" ? {
2556
+ sessionKey: inboundLastRouteSessionKey,
2432
2557
  channel: "mattermost",
2558
+ to,
2433
2559
  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)}`);
2560
+ mainDmOwnerPin: inboundLastRouteSessionKey === route.mainSessionKey && pinnedMainDmOwner ? {
2561
+ ownerRecipient: pinnedMainDmOwner,
2562
+ senderRecipient: normalizeMattermostAllowEntry(senderId),
2563
+ onSkip: ({ ownerRecipient, senderRecipient }) => {
2564
+ logVerboseMessage(`mattermost: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
2454
2565
  }
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
- })
2566
+ } : void 0
2567
+ } : void 0,
2568
+ onRecordError: (err) => {
2569
+ logVerboseMessage(`mattermost: failed updating session meta id=${post.id ?? "unknown"}: ${String(err)}`);
2570
+ }
2571
+ },
2572
+ history: {
2573
+ isGroup: Boolean(historyKey),
2574
+ historyKey: historyKey ?? void 0,
2575
+ historyMap: channelHistories,
2576
+ limit: historyLimit
2577
+ },
2578
+ dispatcherOptions,
2579
+ delivery,
2580
+ replyOptions: {
2581
+ ...turnAdoptionLifecycle ? bindIngressLifecycleToReplyOptions(turnAdoptionLifecycle) : {},
2582
+ allowProgressCallbacksWhenSourceDeliverySuppressed: draftToolProgressEnabled ? true : void 0,
2583
+ preserveProgressCallbackStartOrder: draftPreviewEnabled ? true : void 0,
2584
+ onObservedReplyDelivery: draftToolProgressEnabled ? () => draftStream.clear() : void 0,
2585
+ disableBlockStreaming: draftPreviewEnabled ? true : typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
2586
+ ...suppressDefaultToolProgressMessages ? { suppressDefaultToolProgressMessages: true } : {},
2587
+ onModelSelected,
2588
+ onPartialReply: (payloadResult) => {
2589
+ if (account.streamingMode !== "progress") return updateDraftFromPartial(payloadResult.text);
2590
+ },
2591
+ onAssistantMessageStart: () => {
2592
+ lastPartialText = "";
2593
+ progressDraft.resetReasoningProgress();
2594
+ if (account.streamingMode === "block") {
2595
+ blockPreviewAssistantMessagePending = true;
2596
+ return;
2597
+ }
2598
+ if (account.streamingMode !== "progress") progressDraft.reset();
2599
+ },
2600
+ onReasoningEnd: () => {
2601
+ lastPartialText = "";
2602
+ progressDraft.resetReasoningProgress();
2603
+ if (account.streamingMode !== "block" && account.streamingMode !== "progress") progressDraft.reset();
2604
+ },
2605
+ onReasoningStream: async (payloadResult) => {
2606
+ if (account.streamingMode === "progress") {
2607
+ await progressDraft.pushReasoningProgress(payloadResult.text || "Thinking…", { snapshot: payloadResult.isReasoningSnapshot === true });
2608
+ return;
2609
+ }
2610
+ if (!lastPartialText) {
2611
+ const boundarySettled = enterBlockPreviewActivity("reasoning");
2612
+ draftStream.update("Thinking…");
2613
+ previewBoundaryController.noteUpdate();
2614
+ await boundarySettled;
2615
+ }
2616
+ },
2617
+ onToolStart: async (payloadValue) => {
2618
+ if (!draftToolProgressEnabled) return;
2619
+ const boundarySettled = enterBlockPreviewActivity("tool");
2620
+ const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2621
+ event: "tool",
2622
+ itemId: payloadValue.itemId,
2623
+ toolCallId: payloadValue.toolCallId,
2624
+ name: payloadValue.name,
2625
+ phase: payloadValue.phase,
2626
+ args: payloadValue.args
2627
+ }, payloadValue.detailMode ? { detailMode: payloadValue.detailMode } : void 0), { startImmediately: true });
2628
+ previewBoundaryController.noteUpdate();
2629
+ await Promise.all([boundarySettled, progressSettled]);
2630
+ },
2631
+ onItemEvent: async (payloadLocal) => {
2632
+ if (!draftToolProgressEnabled) return;
2633
+ const boundarySettled = enterBlockPreviewActivity("tool");
2634
+ const progressSettled = progressDraft.pushToolProgress(buildChannelProgressDraftLineForEntry(account.config, {
2635
+ event: "item",
2636
+ itemId: payloadLocal.itemId,
2637
+ itemKind: payloadLocal.kind,
2638
+ title: payloadLocal.title,
2639
+ name: payloadLocal.name,
2640
+ phase: payloadLocal.phase,
2641
+ status: payloadLocal.status,
2642
+ summary: payloadLocal.summary,
2643
+ progressText: payloadLocal.progressText,
2644
+ meta: payloadLocal.meta
2645
+ }), { startImmediately: true });
2646
+ previewBoundaryController.noteUpdate();
2647
+ await Promise.all([boundarySettled, progressSettled]);
2648
+ }
2554
2649
  }
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();
2650
+ })
2563
2651
  }
2652
+ });
2653
+ } finally {
2654
+ try {
2655
+ await draftStream.stop();
2656
+ } catch (err) {
2657
+ logVerboseMessage(`mattermost draft preview cleanup failed: ${String(err)}`);
2564
2658
  }
2565
- }) === "duplicate") logVerboseMessage(`mattermost: drop post (dedupe account=${account.accountId} ids=${allMessageIds.length})`);
2659
+ }
2566
2660
  };
2567
2661
  const handleReactionEvent = async (payload) => {
2568
2662
  const reactionData = payload.data?.reaction;
@@ -2652,23 +2746,43 @@ async function monitorMattermostProvider(opts = {}) {
2652
2746
  onFlush: async (entries) => {
2653
2747
  const last = entries.at(-1);
2654
2748
  if (!last) return;
2655
- if (entries.length === 1) {
2656
- await handlePost(last.post, last.payload);
2657
- return;
2749
+ const { lifecycle, settle } = buildMattermostFlushIngressLifecycle(entries);
2750
+ try {
2751
+ if (entries.length === 1) {
2752
+ await handlePost(last.post, last.payload, lifecycle);
2753
+ await settle();
2754
+ return;
2755
+ }
2756
+ const combinedText = entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n");
2757
+ const mergedPost = {
2758
+ ...last.post,
2759
+ message: combinedText,
2760
+ file_ids: []
2761
+ };
2762
+ await handlePost(mergedPost, last.payload, lifecycle, entries.map((entry) => entry.post.id));
2763
+ await settle();
2764
+ } catch (error) {
2765
+ await lifecycle?.onAbandoned();
2766
+ throw error;
2658
2767
  }
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
2768
  },
2668
2769
  onError: (err) => {
2669
2770
  runtime.error?.(`mattermost debounce flush failed: ${String(err)}`);
2670
2771
  }
2671
2772
  });
2773
+ const ingress = createMattermostIngressMonitor({
2774
+ accountId: account.accountId,
2775
+ runtime,
2776
+ abortSignal: opts.abortSignal,
2777
+ dispatch: async (post, payload, turnAdoptionLifecycle) => {
2778
+ await debouncer.enqueue({
2779
+ post,
2780
+ payload,
2781
+ turnAdoptionLifecycle
2782
+ });
2783
+ return { kind: "deferred" };
2784
+ }
2785
+ });
2672
2786
  const wsUrl = buildMattermostWsUrl(baseUrl);
2673
2787
  let seq = 1;
2674
2788
  const connectOnce = createMattermostConnectOnce({
@@ -2682,12 +2796,7 @@ async function monitorMattermostProvider(opts = {}) {
2682
2796
  getBotUpdateAt: async () => {
2683
2797
  return (await fetchMattermostMe(client)).update_at ?? 0;
2684
2798
  },
2685
- onPosted: async (post, payload) => {
2686
- await debouncer.enqueue({
2687
- post,
2688
- payload
2689
- });
2690
- },
2799
+ onPosted: ingress.receive,
2691
2800
  onReaction: async (payload) => {
2692
2801
  await handleReactionEvent(payload);
2693
2802
  }
@@ -2725,6 +2834,7 @@ async function monitorMattermostProvider(opts = {}) {
2725
2834
  }
2726
2835
  });
2727
2836
  } finally {
2837
+ await ingress.stop();
2728
2838
  unregisterInteractions?.();
2729
2839
  }
2730
2840
  const slashShutdownCleanupPromise = slashShutdownCleanup;
@@ -2732,7 +2842,7 @@ async function monitorMattermostProvider(opts = {}) {
2732
2842
  }
2733
2843
  //#endregion
2734
2844
  //#region extensions/mattermost/src/mattermost/probe.ts
2735
- async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivateNetwork = false) {
2845
+ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivateNetwork = false, deps) {
2736
2846
  const normalized = normalizeMattermostBaseUrl(baseUrl);
2737
2847
  if (!normalized) return {
2738
2848
  ok: false,
@@ -2740,19 +2850,16 @@ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivate
2740
2850
  };
2741
2851
  const url = `${normalized}/api/v4/users/me`;
2742
2852
  const start = Date.now();
2743
- const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : 0;
2744
- const controller = resolvedTimeoutMs > 0 ? new AbortController() : void 0;
2745
- let timer = null;
2746
- if (controller) timer = setTimeout(() => controller.abort(), resolvedTimeoutMs);
2853
+ const resolvedTimeoutMs = timeoutMs > 0 ? resolveTimerTimeoutMs(timeoutMs, 2500) : void 0;
2747
2854
  try {
2748
2855
  const { response: res, release } = await fetchWithSsrFGuard({
2749
2856
  url,
2750
- init: {
2751
- headers: { Authorization: `Bearer ${botToken}` },
2752
- signal: controller?.signal
2753
- },
2857
+ init: { headers: { Authorization: `Bearer ${botToken}` } },
2754
2858
  auditContext: "mattermost-probe",
2755
- policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork)
2859
+ policy: ssrfPolicyFromPrivateNetworkOptIn(allowPrivateNetwork),
2860
+ ...resolvedTimeoutMs !== void 0 ? { timeoutMs: resolvedTimeoutMs } : {},
2861
+ ...deps?.fetchImpl ? { fetchImpl: deps.fetchImpl } : {},
2862
+ ...deps?.lookupFn ? { lookupFn: deps.lookupFn } : {}
2756
2863
  });
2757
2864
  try {
2758
2865
  const elapsedMs = Date.now() - start;
@@ -2782,8 +2889,6 @@ async function probeMattermost(baseUrl, botToken, timeoutMs = 2500, allowPrivate
2782
2889
  error: formatErrorMessage(err),
2783
2890
  elapsedMs: Date.now() - start
2784
2891
  };
2785
- } finally {
2786
- if (timer) clearTimeout(timer);
2787
2892
  }
2788
2893
  }
2789
2894
  //#endregion