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

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