@openclaw/mattermost 2026.7.2-beta.7 → 2026.7.33
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.
- package/dist/{client-CqqzTcno.js → .setup/accounts-CkvUBI7I.mjs} +101 -55
- package/dist/.setup/channel-plugin-api-DQ6gNcH0.mjs +31 -0
- package/dist/.setup/channel-plugin-api-jFFWYXht.mjs +3 -0
- package/dist/{channel-plugin-runtime-DlrMaSIu.js → .setup/channel-plugin-runtime-BLOKRsgT.mjs} +260 -344
- package/dist/.setup/channel.runtime-CK6s04r7.mjs +2653 -0
- package/dist/.setup/doctor-contract-ttH0DCuq.mjs +7 -0
- package/dist/{gateway-auth-bypass-CL1PxV3z.js → .setup/gateway-auth-bypass-BIXLORHU.mjs} +2 -3
- package/dist/{monitor-auth-rctDliGZ.js → .setup/monitor-auth-CeakcTAO.mjs} +13 -14
- package/dist/.setup/secret-contract-Cx0LUNXy.mjs +44 -0
- package/dist/.setup/secret-contract-api-BLTnjVCZ.mjs +3 -0
- package/dist/{slash-state-DM8qmFJR.js → .setup/slash-state-D1e1_KaK.mjs} +572 -311
- package/dist/api.js +2 -3
- package/dist/channel-plugin-api.js +2 -38
- package/dist/channel-plugin-runtime.js +1 -1
- package/dist/doctor-contract-api.js +1 -1
- package/dist/gateway-auth-api.js +1 -1
- package/dist/policy-api.js +1 -1
- package/dist/runtime-api.js +3 -2
- package/dist/secret-contract-api.js +1 -1
- package/dist/setup-entry.js +3 -2
- package/dist/slash-route-api.js +1 -1
- package/node_modules/ws/lib/permessage-deflate.js +3 -1
- package/node_modules/ws/package.json +1 -1
- package/openclaw.plugin.json +231 -277
- package/package.json +6 -52
- package/dist/accounts-NaMdx9yF.js +0 -86
- package/dist/channel.runtime-DndW9G7T.js +0 -3207
- package/dist/doctor-contract-BaUvVh8e.js +0 -19
- package/dist/interactions-BQXY_48h.js +0 -375
- package/dist/secret-contract-B4R5Bmhv.js +0 -28
- /package/dist/{runtime-CNB4YGqJ.js → .setup/runtime-CNB4YGqJ.mjs} +0 -0
|
@@ -1,28 +1,22 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { c as setInteractionSecret, n as buildButtonProps, o as resolveInteractionCallbackUrl } from "./interactions-BQXY_48h.js";
|
|
5
|
-
import { i as resolveMattermostAccount } from "./accounts-NaMdx9yF.js";
|
|
6
|
-
import { createHash } from "node:crypto";
|
|
7
|
-
import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
|
|
1
|
+
import { a as normalizeMattermostAllowList, b as readRequestBodyWithLimit, d as createChannelMessageReplyPipeline, g as loadOutboundMediaFromUrl, l as buildModelsProviderData, m as isTrustedProxyAddress, p as isRequestBodyLimitError, t as authorizeMattermostCommandInvocation, v as logTypingFailure, w as resolveClientIp } from "./monitor-auth-CeakcTAO.mjs";
|
|
2
|
+
import { b as updateMattermostPost, c as createMattermostPost, d as fetchMattermostChannelByName, f as fetchMattermostMe, g as normalizeMattermostBaseUrl, h as fetchMattermostUserTeams, m as fetchMattermostUserByUsername, o as createMattermostClient, p as fetchMattermostUser, r as resolveMattermostAccount, s as createMattermostDirectChannelWithRetry, u as fetchMattermostChannel, v as resolveMattermostReplyDeliveryBarrierTimeoutMs, x as uploadMattermostFile, y as sendMattermostTyping } from "./accounts-CkvUBI7I.mjs";
|
|
3
|
+
import { t as getMattermostRuntime } from "./runtime-CNB4YGqJ.mjs";
|
|
8
4
|
import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringifiedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
9
|
-
import {
|
|
10
|
-
import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
11
|
-
import { createChannelPartialDeliveryError, isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
|
|
12
|
-
import { createMessageReceiptFromOutboundResults, listMessageReceiptPlatformIds } from "openclaw/plugin-sdk/channel-outbound";
|
|
5
|
+
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
|
|
13
6
|
import { resolveStoredModelOverride } from "openclaw/plugin-sdk/command-auth-native";
|
|
14
7
|
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
|
|
8
|
+
import { asDateTimestampMs, parseStrictInteger, resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
|
|
15
9
|
import { deliverTextOrMediaReply, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
|
|
16
|
-
import {
|
|
10
|
+
import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
11
|
+
import { convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";
|
|
17
12
|
import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
|
|
18
13
|
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
19
14
|
import { Readable } from "node:stream";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
23
|
-
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
15
|
+
import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
|
|
16
|
+
import { createHash, createHmac } from "node:crypto";
|
|
24
17
|
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
|
|
25
18
|
import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
|
|
19
|
+
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
26
20
|
const MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES = 128;
|
|
27
21
|
function truncateMattermostCommandDescription(description) {
|
|
28
22
|
if (Buffer.byteLength(description, "utf8") <= MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES) return description;
|
|
@@ -376,9 +370,7 @@ const ACTION_IDS = {
|
|
|
376
370
|
function splitModelRef(modelRef) {
|
|
377
371
|
const match = normalizeOptionalString(modelRef)?.match(/^([^/]+)\/(.+)$/u);
|
|
378
372
|
if (!match) return null;
|
|
379
|
-
const
|
|
380
|
-
if (!rawProvider) return null;
|
|
381
|
-
const provider = normalizeProviderId(rawProvider);
|
|
373
|
+
const provider = normalizeProviderId(match[1]);
|
|
382
374
|
const model = normalizeOptionalString(match[2]);
|
|
383
375
|
if (!provider || !model) return null;
|
|
384
376
|
return {
|
|
@@ -662,104 +654,413 @@ function createMattermostReplyDeliveryBarrier(params) {
|
|
|
662
654
|
resolveTimeoutPolicy
|
|
663
655
|
};
|
|
664
656
|
}
|
|
665
|
-
/** Represents distinct provider posts without collapsing their visible boundary. */
|
|
666
|
-
function joinMattermostVisibleContent(contents) {
|
|
667
|
-
return contents.filter((content) => Boolean(content)).join("\n");
|
|
668
|
-
}
|
|
669
657
|
async function deliverMattermostReplyPayload(params) {
|
|
670
|
-
if (isReasoningReplyPayload(params.payload)) return
|
|
671
|
-
outcome: "reasoning_skipped",
|
|
672
|
-
visibleReplySent: false,
|
|
673
|
-
suppression: { reason: "no_visible_result" }
|
|
674
|
-
};
|
|
658
|
+
if (isReasoningReplyPayload(params.payload)) return "reasoning_skipped";
|
|
675
659
|
const reply = resolveSendableOutboundReplyParts(params.payload, { text: params.core.channel.text.convertMarkdownTables(params.payload.text ?? "", params.tableMode) });
|
|
676
660
|
const mediaLocalRoots = getAgentScopedMediaLocalRoots(params.cfg, params.agentId);
|
|
677
661
|
const chunkMode = params.core.channel.text.resolveChunkMode(params.cfg, "mattermost", params.accountId);
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
662
|
+
return await deliverTextOrMediaReply({
|
|
663
|
+
payload: params.payload,
|
|
664
|
+
text: reply.text,
|
|
665
|
+
chunkText: (value) => params.core.channel.text.chunkMarkdownTextWithMode(value, params.textLimit, chunkMode),
|
|
666
|
+
sendText: async (chunk) => {
|
|
667
|
+
await params.sendMessage(params.to, chunk, {
|
|
668
|
+
cfg: params.cfg,
|
|
669
|
+
accountId: params.accountId,
|
|
670
|
+
replyToId: params.replyToId,
|
|
671
|
+
...params.onDmChannelResolution ? { onDmChannelResolution: params.onDmChannelResolution } : {}
|
|
672
|
+
});
|
|
673
|
+
},
|
|
674
|
+
sendMedia: async ({ mediaUrl, caption }) => {
|
|
675
|
+
await params.sendMessage(params.to, caption ?? "", {
|
|
676
|
+
cfg: params.cfg,
|
|
677
|
+
accountId: params.accountId,
|
|
678
|
+
mediaUrl,
|
|
679
|
+
mediaLocalRoots,
|
|
680
|
+
replyToId: params.replyToId,
|
|
681
|
+
...params.onDmChannelResolution ? { onDmChannelResolution: params.onDmChannelResolution } : {}
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region extensions/mattermost/src/mattermost/interactions.ts
|
|
688
|
+
const INTERACTION_MAX_BODY_BYTES = 65536;
|
|
689
|
+
const INTERACTION_BODY_TIMEOUT_MS = 1e4;
|
|
690
|
+
const SIGNED_CHANNEL_ID_CONTEXT_KEY = "__openclaw_channel_id";
|
|
691
|
+
const callbackUrls = /* @__PURE__ */ new Map();
|
|
692
|
+
function setInteractionCallbackUrl(accountId, url) {
|
|
693
|
+
callbackUrls.set(accountId, url);
|
|
694
|
+
}
|
|
695
|
+
function resolveInteractionCallbackPath(accountId) {
|
|
696
|
+
return `/mattermost/interactions/${accountId}`;
|
|
697
|
+
}
|
|
698
|
+
function isWildcardBindHost(rawHost) {
|
|
699
|
+
const trimmed = rawHost.trim();
|
|
700
|
+
if (!trimmed) return false;
|
|
701
|
+
const host = trimmed.startsWith("[") && trimmed.endsWith("]") ? trimmed.slice(1, -1) : trimmed;
|
|
702
|
+
return host === "0.0.0.0" || host === "::" || host === "0:0:0:0:0:0:0:0" || host === "::0";
|
|
703
|
+
}
|
|
704
|
+
function normalizeCallbackBaseUrl(baseUrl) {
|
|
705
|
+
return baseUrl.trim().replace(/\/+$/, "");
|
|
706
|
+
}
|
|
707
|
+
function headerValue(value) {
|
|
708
|
+
if (Array.isArray(value)) return normalizeOptionalString(value[0]);
|
|
709
|
+
return normalizeOptionalString(value);
|
|
710
|
+
}
|
|
711
|
+
function isAllowedInteractionSource(params) {
|
|
712
|
+
const { allowedSourceIps } = params;
|
|
713
|
+
if (!allowedSourceIps?.length) return true;
|
|
714
|
+
const clientIp = resolveClientIp({
|
|
715
|
+
remoteAddr: params.req.socket?.remoteAddress,
|
|
716
|
+
forwardedFor: headerValue(params.req.headers["x-forwarded-for"]),
|
|
717
|
+
realIp: headerValue(params.req.headers["x-real-ip"]),
|
|
718
|
+
trustedProxies: params.trustedProxies,
|
|
719
|
+
allowRealIpFallback: params.allowRealIpFallback
|
|
720
|
+
});
|
|
721
|
+
return isTrustedProxyAddress(clientIp, allowedSourceIps);
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Resolve the interaction callback URL for an account.
|
|
725
|
+
* Falls back to computing it from interactions.callbackBaseUrl or gateway host config.
|
|
726
|
+
*/
|
|
727
|
+
function computeInteractionCallbackUrl(accountId, cfg) {
|
|
728
|
+
const path = resolveInteractionCallbackPath(accountId);
|
|
729
|
+
const callbackBaseUrl = normalizeOptionalString(cfg?.interactions?.callbackBaseUrl) ?? normalizeOptionalString(cfg?.channels?.mattermost?.interactions?.callbackBaseUrl);
|
|
730
|
+
if (callbackBaseUrl) return `${normalizeCallbackBaseUrl(callbackBaseUrl)}${path}`;
|
|
731
|
+
const port = typeof cfg?.gateway?.port === "number" ? cfg.gateway.port : 18789;
|
|
732
|
+
let host = cfg?.gateway?.customBindHost && !isWildcardBindHost(cfg.gateway.customBindHost) ? cfg.gateway.customBindHost.trim() : "localhost";
|
|
733
|
+
if (host.includes(":") && !(host.startsWith("[") && host.endsWith("]"))) host = `[${host}]`;
|
|
734
|
+
return `http://${host}:${port}${path}`;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Resolve the interaction callback URL for an account.
|
|
738
|
+
* Prefers the in-memory registered URL (set by the gateway monitor) so callers outside the
|
|
739
|
+
* monitor lifecycle can reuse the runtime-validated callback destination.
|
|
740
|
+
*/
|
|
741
|
+
function resolveInteractionCallbackUrl(accountId, cfg) {
|
|
742
|
+
const cached = callbackUrls.get(accountId);
|
|
743
|
+
if (cached) return cached;
|
|
744
|
+
return computeInteractionCallbackUrl(accountId, cfg);
|
|
745
|
+
}
|
|
746
|
+
const interactionSecrets = /* @__PURE__ */ new Map();
|
|
747
|
+
let defaultInteractionSecret;
|
|
748
|
+
function deriveInteractionSecret(botToken) {
|
|
749
|
+
return createHmac("sha256", "openclaw-mattermost-interactions").update(botToken).digest("hex");
|
|
750
|
+
}
|
|
751
|
+
function setInteractionSecret(accountIdOrBotToken, botToken) {
|
|
752
|
+
if (typeof botToken === "string") {
|
|
753
|
+
interactionSecrets.set(accountIdOrBotToken, deriveInteractionSecret(botToken));
|
|
754
|
+
return;
|
|
723
755
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
756
|
+
defaultInteractionSecret = deriveInteractionSecret(accountIdOrBotToken);
|
|
757
|
+
}
|
|
758
|
+
function getInteractionSecret(accountId) {
|
|
759
|
+
const scoped = accountId ? interactionSecrets.get(accountId) : void 0;
|
|
760
|
+
if (scoped) return scoped;
|
|
761
|
+
if (defaultInteractionSecret) return defaultInteractionSecret;
|
|
762
|
+
if (interactionSecrets.size === 1) {
|
|
763
|
+
const first = interactionSecrets.values().next().value;
|
|
764
|
+
if (typeof first === "string") return first;
|
|
765
|
+
}
|
|
766
|
+
throw new Error("Interaction secret not initialized — call setInteractionSecret(accountId, botToken) first");
|
|
767
|
+
}
|
|
768
|
+
function canonicalizeInteractionContext(value) {
|
|
769
|
+
if (Array.isArray(value)) return value.map((item) => canonicalizeInteractionContext(item));
|
|
770
|
+
if (value && typeof value === "object") {
|
|
771
|
+
const entries = Object.entries(value).filter(([, entryValue]) => entryValue !== void 0).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, entryValue]) => [key, canonicalizeInteractionContext(entryValue)]);
|
|
772
|
+
return Object.fromEntries(entries);
|
|
773
|
+
}
|
|
774
|
+
return value;
|
|
775
|
+
}
|
|
776
|
+
function generateInteractionToken(context, accountId) {
|
|
777
|
+
const secret = getInteractionSecret(accountId);
|
|
778
|
+
const payload = JSON.stringify(canonicalizeInteractionContext(context));
|
|
779
|
+
return createHmac("sha256", secret).update(payload).digest("hex");
|
|
780
|
+
}
|
|
781
|
+
function verifyInteractionToken(context, token, accountId) {
|
|
782
|
+
const expected = generateInteractionToken(context, accountId);
|
|
783
|
+
return safeEqualSecret(expected, token);
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Build Mattermost `props.attachments` with interactive buttons.
|
|
787
|
+
*
|
|
788
|
+
* Each button includes an HMAC token in its integration context so the
|
|
789
|
+
* callback handler can verify the request originated from a legitimate
|
|
790
|
+
* button click (Mattermost's recommended security pattern).
|
|
791
|
+
*/
|
|
792
|
+
/**
|
|
793
|
+
* Sanitize a button ID so Mattermost's action router can match it.
|
|
794
|
+
* Mattermost uses the action ID in the URL path `/api/v4/posts/{id}/actions/{actionId}`
|
|
795
|
+
* and IDs containing hyphens or underscores break the server-side routing.
|
|
796
|
+
* See: https://github.com/mattermost/mattermost/issues/25747
|
|
797
|
+
*/
|
|
798
|
+
function sanitizeActionId(id) {
|
|
799
|
+
return id.replace(/[-_]/g, "");
|
|
800
|
+
}
|
|
801
|
+
function buildButtonAttachments(params) {
|
|
802
|
+
const actions = params.buttons.map((btn) => {
|
|
803
|
+
const safeId = sanitizeActionId(btn.id);
|
|
804
|
+
const context = {
|
|
805
|
+
action_id: safeId,
|
|
806
|
+
...btn.context
|
|
807
|
+
};
|
|
808
|
+
const token = generateInteractionToken(context, params.accountId);
|
|
809
|
+
return {
|
|
810
|
+
id: safeId,
|
|
811
|
+
type: "button",
|
|
812
|
+
name: btn.name,
|
|
813
|
+
style: btn.style,
|
|
814
|
+
integration: {
|
|
815
|
+
url: params.callbackUrl,
|
|
816
|
+
context: {
|
|
817
|
+
...context,
|
|
818
|
+
_token: token
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
};
|
|
733
822
|
});
|
|
734
|
-
return {
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
823
|
+
return [{
|
|
824
|
+
text: params.text ?? "",
|
|
825
|
+
actions
|
|
826
|
+
}];
|
|
827
|
+
}
|
|
828
|
+
function buildButtonProps(params) {
|
|
829
|
+
const buttons = params.buttons.flatMap((item) => Array.isArray(item) ? item : [item]).map((btn) => ({
|
|
830
|
+
id: normalizeStringifiedOptionalString(btn.id ?? btn.callback_data) ?? "",
|
|
831
|
+
name: normalizeStringifiedOptionalString(btn.text ?? btn.name ?? btn.label) ?? "",
|
|
832
|
+
style: btn.style ?? "default",
|
|
833
|
+
context: typeof btn.context === "object" && btn.context !== null ? {
|
|
834
|
+
...btn.context,
|
|
835
|
+
[SIGNED_CHANNEL_ID_CONTEXT_KEY]: params.channelId
|
|
836
|
+
} : { [SIGNED_CHANNEL_ID_CONTEXT_KEY]: params.channelId }
|
|
837
|
+
})).filter((btn) => btn.id && btn.name);
|
|
838
|
+
if (buttons.length === 0) return;
|
|
839
|
+
return { attachments: buildButtonAttachments({
|
|
840
|
+
callbackUrl: params.callbackUrl,
|
|
841
|
+
accountId: params.accountId,
|
|
842
|
+
buttons,
|
|
843
|
+
text: params.text
|
|
844
|
+
}) };
|
|
845
|
+
}
|
|
846
|
+
function readInteractionBody(req) {
|
|
847
|
+
return readRequestBodyWithLimit(req, {
|
|
848
|
+
maxBytes: INTERACTION_MAX_BODY_BYTES,
|
|
849
|
+
timeoutMs: INTERACTION_BODY_TIMEOUT_MS
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
function createMattermostInteractionHandler(params) {
|
|
853
|
+
const { client, accountId, log } = params;
|
|
854
|
+
const core = getMattermostRuntime();
|
|
855
|
+
function parseInteractionPayload(raw) {
|
|
856
|
+
try {
|
|
857
|
+
return JSON.parse(raw);
|
|
858
|
+
} catch {
|
|
859
|
+
throw new Error("Mattermost interaction body was malformed JSON");
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
return async (req, res) => {
|
|
863
|
+
if (req.method !== "POST") {
|
|
864
|
+
res.statusCode = 405;
|
|
865
|
+
res.setHeader("Allow", "POST");
|
|
866
|
+
res.setHeader("Content-Type", "application/json");
|
|
867
|
+
res.end(JSON.stringify({ error: "Method Not Allowed" }));
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
if (!isAllowedInteractionSource({
|
|
871
|
+
req,
|
|
872
|
+
allowedSourceIps: params.allowedSourceIps,
|
|
873
|
+
trustedProxies: params.trustedProxies,
|
|
874
|
+
allowRealIpFallback: params.allowRealIpFallback
|
|
875
|
+
})) {
|
|
876
|
+
log?.(`mattermost interaction: rejected callback source remote=${req.socket?.remoteAddress ?? "?"}`);
|
|
877
|
+
res.statusCode = 403;
|
|
878
|
+
res.setHeader("Content-Type", "application/json");
|
|
879
|
+
res.end(JSON.stringify({ error: "Forbidden origin" }));
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
let payload;
|
|
883
|
+
try {
|
|
884
|
+
payload = parseInteractionPayload(await readInteractionBody(req));
|
|
885
|
+
} catch (err) {
|
|
886
|
+
log?.(`mattermost interaction: failed to parse body: ${String(err)}`);
|
|
887
|
+
res.statusCode = 400;
|
|
888
|
+
res.setHeader("Content-Type", "application/json");
|
|
889
|
+
res.end(JSON.stringify({ error: "Invalid request body" }));
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
const context = payload.context;
|
|
893
|
+
if (!context) {
|
|
894
|
+
res.statusCode = 400;
|
|
895
|
+
res.setHeader("Content-Type", "application/json");
|
|
896
|
+
res.end(JSON.stringify({ error: "Missing context" }));
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
const token = context["_token"];
|
|
900
|
+
if (typeof token !== "string") {
|
|
901
|
+
log?.("mattermost interaction: missing _token in context");
|
|
902
|
+
res.statusCode = 403;
|
|
903
|
+
res.setHeader("Content-Type", "application/json");
|
|
904
|
+
res.end(JSON.stringify({ error: "Missing token" }));
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
const { _token, ...contextWithoutToken } = context;
|
|
908
|
+
if (!verifyInteractionToken(contextWithoutToken, token, accountId)) {
|
|
909
|
+
log?.("mattermost interaction: invalid _token");
|
|
910
|
+
res.statusCode = 403;
|
|
911
|
+
res.setHeader("Content-Type", "application/json");
|
|
912
|
+
res.end(JSON.stringify({ error: "Invalid token" }));
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
const actionId = context.action_id;
|
|
916
|
+
if (typeof actionId !== "string") {
|
|
917
|
+
res.statusCode = 400;
|
|
918
|
+
res.setHeader("Content-Type", "application/json");
|
|
919
|
+
res.end(JSON.stringify({ error: "Missing action_id in context" }));
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
const signedChannelId = typeof contextWithoutToken[SIGNED_CHANNEL_ID_CONTEXT_KEY] === "string" ? contextWithoutToken[SIGNED_CHANNEL_ID_CONTEXT_KEY].trim() : "";
|
|
923
|
+
if (signedChannelId && signedChannelId !== payload.channel_id) {
|
|
924
|
+
log?.(`mattermost interaction: signed channel mismatch payload=${payload.channel_id} signed=${signedChannelId}`);
|
|
925
|
+
res.statusCode = 403;
|
|
926
|
+
res.setHeader("Content-Type", "application/json");
|
|
927
|
+
res.end(JSON.stringify({ error: "Channel mismatch" }));
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
const userName = payload.user_name ?? payload.user_id;
|
|
931
|
+
let originalMessage;
|
|
932
|
+
let originalPost;
|
|
933
|
+
let clickedButtonName = null;
|
|
934
|
+
try {
|
|
935
|
+
originalPost = await client.request(`/posts/${payload.post_id}`);
|
|
936
|
+
const postChannelId = originalPost.channel_id?.trim();
|
|
937
|
+
if (!postChannelId || postChannelId !== payload.channel_id) {
|
|
938
|
+
log?.(`mattermost interaction: post channel mismatch payload=${payload.channel_id} post=${postChannelId ?? "<missing>"}`);
|
|
939
|
+
res.statusCode = 403;
|
|
940
|
+
res.setHeader("Content-Type", "application/json");
|
|
941
|
+
res.end(JSON.stringify({ error: "Post/channel mismatch" }));
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
originalMessage = originalPost.message ?? "";
|
|
945
|
+
const postAttachments = Array.isArray(originalPost?.props?.attachments) ? originalPost.props.attachments : [];
|
|
946
|
+
for (const att of postAttachments) {
|
|
947
|
+
const match = att.actions?.find((a) => a.id === actionId);
|
|
948
|
+
if (match?.name) {
|
|
949
|
+
clickedButtonName = match.name;
|
|
950
|
+
break;
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
if (clickedButtonName === null) {
|
|
954
|
+
log?.(`mattermost interaction: action ${actionId} not found in post ${payload.post_id}`);
|
|
955
|
+
res.statusCode = 403;
|
|
956
|
+
res.setHeader("Content-Type", "application/json");
|
|
957
|
+
res.end(JSON.stringify({ error: "Unknown action" }));
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
} catch (err) {
|
|
961
|
+
log?.(`mattermost interaction: failed to validate post ${payload.post_id}: ${String(err)}`);
|
|
962
|
+
res.statusCode = 500;
|
|
963
|
+
res.setHeader("Content-Type", "application/json");
|
|
964
|
+
res.end(JSON.stringify({ error: "Failed to validate interaction" }));
|
|
965
|
+
return;
|
|
966
|
+
}
|
|
967
|
+
if (!originalPost) {
|
|
968
|
+
log?.(`mattermost interaction: missing fetched post ${payload.post_id}`);
|
|
969
|
+
res.statusCode = 500;
|
|
970
|
+
res.setHeader("Content-Type", "application/json");
|
|
971
|
+
res.end(JSON.stringify({ error: "Failed to load interaction post" }));
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
log?.(`mattermost interaction: action=${actionId} user=${payload.user_name ?? payload.user_id} post=${payload.post_id} channel=${payload.channel_id}`);
|
|
975
|
+
if (params.authorizeButtonClick) try {
|
|
976
|
+
const authorization = await params.authorizeButtonClick({
|
|
977
|
+
payload,
|
|
978
|
+
post: originalPost
|
|
979
|
+
});
|
|
980
|
+
if (!authorization.ok) {
|
|
981
|
+
res.statusCode = authorization.statusCode ?? 200;
|
|
982
|
+
res.setHeader("Content-Type", "application/json");
|
|
983
|
+
res.end(JSON.stringify(authorization.response ?? { ephemeral_text: "You are not allowed to use this action here." }));
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
} catch (err) {
|
|
987
|
+
log?.(`mattermost interaction: authorization failed: ${String(err)}`);
|
|
988
|
+
res.statusCode = 500;
|
|
989
|
+
res.setHeader("Content-Type", "application/json");
|
|
990
|
+
res.end(JSON.stringify({ error: "Interaction authorization failed" }));
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
if (params.handleInteraction) try {
|
|
994
|
+
const response = await params.handleInteraction({
|
|
995
|
+
payload,
|
|
996
|
+
userName,
|
|
997
|
+
actionId,
|
|
998
|
+
actionName: clickedButtonName,
|
|
999
|
+
originalMessage,
|
|
1000
|
+
context: contextWithoutToken,
|
|
1001
|
+
post: originalPost
|
|
1002
|
+
});
|
|
1003
|
+
if (response !== null) {
|
|
1004
|
+
res.statusCode = 200;
|
|
1005
|
+
res.setHeader("Content-Type", "application/json");
|
|
1006
|
+
res.end(JSON.stringify(response));
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
} catch (err) {
|
|
1010
|
+
log?.(`mattermost interaction: custom handler failed: ${String(err)}`);
|
|
1011
|
+
res.statusCode = 500;
|
|
1012
|
+
res.setHeader("Content-Type", "application/json");
|
|
1013
|
+
res.end(JSON.stringify({ error: "Interaction handler failed" }));
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
try {
|
|
1017
|
+
const eventLabel = `Mattermost button click: action="${actionId}" by ${payload.user_name ?? payload.user_id} in channel ${payload.channel_id}`;
|
|
1018
|
+
const sessionKey = params.resolveSessionKey ? await params.resolveSessionKey({
|
|
1019
|
+
channelId: payload.channel_id,
|
|
1020
|
+
userId: payload.user_id,
|
|
1021
|
+
post: originalPost
|
|
1022
|
+
}) : `agent:main:mattermost:${accountId}:${payload.channel_id}`;
|
|
1023
|
+
core.system.enqueueSystemEvent(eventLabel, {
|
|
1024
|
+
sessionKey,
|
|
1025
|
+
contextKey: `mattermost:interaction:${payload.post_id}:${actionId}`
|
|
1026
|
+
});
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
log?.(`mattermost interaction: system event dispatch failed: ${String(err)}`);
|
|
1029
|
+
}
|
|
1030
|
+
try {
|
|
1031
|
+
await updateMattermostPost(client, payload.post_id, {
|
|
1032
|
+
message: originalMessage,
|
|
1033
|
+
props: { attachments: [{ text: `✓ **${clickedButtonName}** selected by @${userName}` }] }
|
|
1034
|
+
});
|
|
1035
|
+
} catch (err) {
|
|
1036
|
+
log?.(`mattermost interaction: failed to update post ${payload.post_id}: ${String(err)}`);
|
|
1037
|
+
}
|
|
1038
|
+
res.statusCode = 200;
|
|
1039
|
+
res.setHeader("Content-Type", "application/json");
|
|
1040
|
+
res.end("{}");
|
|
1041
|
+
if (params.dispatchButtonClick) try {
|
|
1042
|
+
await params.dispatchButtonClick({
|
|
1043
|
+
channelId: payload.channel_id,
|
|
1044
|
+
userId: payload.user_id,
|
|
1045
|
+
userName,
|
|
1046
|
+
actionId,
|
|
1047
|
+
actionName: clickedButtonName,
|
|
1048
|
+
postId: payload.post_id,
|
|
1049
|
+
post: originalPost
|
|
1050
|
+
});
|
|
1051
|
+
} catch (err) {
|
|
1052
|
+
log?.(`mattermost interaction: dispatchButtonClick failed: ${String(err)}`);
|
|
1053
|
+
}
|
|
740
1054
|
};
|
|
741
1055
|
}
|
|
742
1056
|
//#endregion
|
|
743
1057
|
//#region extensions/mattermost/src/mattermost/target-resolution.ts
|
|
744
1058
|
const MATTERMOST_OPAQUE_TARGET_CACHE_MAX_ENTRIES = 1024;
|
|
745
|
-
const MATTERMOST_OPAQUE_TARGET_CACHE_TTL_MS = 300 * 1e3;
|
|
746
1059
|
const mattermostOpaqueTargetCache = /* @__PURE__ */ new Map();
|
|
747
1060
|
function cacheMattermostOpaqueTarget(key, kind) {
|
|
748
|
-
mattermostOpaqueTargetCache.set(key,
|
|
749
|
-
kind,
|
|
750
|
-
expiresAt: Date.now() + MATTERMOST_OPAQUE_TARGET_CACHE_TTL_MS
|
|
751
|
-
});
|
|
1061
|
+
mattermostOpaqueTargetCache.set(key, kind);
|
|
752
1062
|
pruneMapToMaxSize(mattermostOpaqueTargetCache, MATTERMOST_OPAQUE_TARGET_CACHE_MAX_ENTRIES);
|
|
753
1063
|
}
|
|
754
|
-
function getCachedMattermostOpaqueTargetKind(key) {
|
|
755
|
-
const cached = mattermostOpaqueTargetCache.get(key);
|
|
756
|
-
if (!cached) return;
|
|
757
|
-
if (cached.expiresAt <= Date.now()) {
|
|
758
|
-
mattermostOpaqueTargetCache.delete(key);
|
|
759
|
-
return;
|
|
760
|
-
}
|
|
761
|
-
return cached.kind;
|
|
762
|
-
}
|
|
763
1064
|
function cacheKey$1(baseUrl, token, id) {
|
|
764
1065
|
return `${baseUrl}::${token}::${id}`;
|
|
765
1066
|
}
|
|
@@ -767,71 +1068,6 @@ function cacheKey$1(baseUrl, token, id) {
|
|
|
767
1068
|
function isMattermostId(value) {
|
|
768
1069
|
return /^[a-z0-9]{26}$/.test(value);
|
|
769
1070
|
}
|
|
770
|
-
function parseMattermostTarget(raw) {
|
|
771
|
-
const trimmed = raw.trim();
|
|
772
|
-
if (!trimmed) throw new Error("Recipient is required for Mattermost sends");
|
|
773
|
-
const lower = normalizeLowercaseStringOrEmpty(trimmed);
|
|
774
|
-
if (lower.startsWith("channel:")) {
|
|
775
|
-
const id = trimmed.slice(8).trim();
|
|
776
|
-
if (!id) throw new Error("Channel id is required for Mattermost sends");
|
|
777
|
-
if (id.startsWith("#")) {
|
|
778
|
-
const name = id.slice(1).trim();
|
|
779
|
-
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
780
|
-
return {
|
|
781
|
-
kind: "channel-name",
|
|
782
|
-
name
|
|
783
|
-
};
|
|
784
|
-
}
|
|
785
|
-
if (!isMattermostId(id)) return {
|
|
786
|
-
kind: "channel-name",
|
|
787
|
-
name: id
|
|
788
|
-
};
|
|
789
|
-
return {
|
|
790
|
-
kind: "channel",
|
|
791
|
-
id
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
if (lower.startsWith("user:")) {
|
|
795
|
-
const id = trimmed.slice(5).trim();
|
|
796
|
-
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
797
|
-
return {
|
|
798
|
-
kind: "user",
|
|
799
|
-
id
|
|
800
|
-
};
|
|
801
|
-
}
|
|
802
|
-
if (lower.startsWith("mattermost:")) {
|
|
803
|
-
const id = trimmed.slice(11).trim();
|
|
804
|
-
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
805
|
-
return {
|
|
806
|
-
kind: "user",
|
|
807
|
-
id
|
|
808
|
-
};
|
|
809
|
-
}
|
|
810
|
-
if (trimmed.startsWith("@")) {
|
|
811
|
-
const username = trimmed.slice(1).trim();
|
|
812
|
-
if (!username) throw new Error("Username is required for Mattermost sends");
|
|
813
|
-
return {
|
|
814
|
-
kind: "user",
|
|
815
|
-
username
|
|
816
|
-
};
|
|
817
|
-
}
|
|
818
|
-
if (trimmed.startsWith("#")) {
|
|
819
|
-
const name = trimmed.slice(1).trim();
|
|
820
|
-
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
821
|
-
return {
|
|
822
|
-
kind: "channel-name",
|
|
823
|
-
name
|
|
824
|
-
};
|
|
825
|
-
}
|
|
826
|
-
if (!isMattermostId(trimmed)) return {
|
|
827
|
-
kind: "channel-name",
|
|
828
|
-
name: trimmed
|
|
829
|
-
};
|
|
830
|
-
return {
|
|
831
|
-
kind: "channel",
|
|
832
|
-
id: trimmed
|
|
833
|
-
};
|
|
834
|
-
}
|
|
835
1071
|
function isExplicitMattermostTarget(raw) {
|
|
836
1072
|
const trimmed = raw.trim();
|
|
837
1073
|
if (!trimmed) return false;
|
|
@@ -852,16 +1088,15 @@ async function resolveMattermostOpaqueTarget(params) {
|
|
|
852
1088
|
cfg: params.cfg,
|
|
853
1089
|
accountId: params.accountId
|
|
854
1090
|
}) : null;
|
|
855
|
-
if (account && !account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
|
|
856
1091
|
const token = normalizeOptionalString(params.token) ?? normalizeOptionalString(account?.botToken);
|
|
857
1092
|
const baseUrl = normalizeMattermostBaseUrl(params.baseUrl ?? account?.baseUrl);
|
|
858
1093
|
if (!token || !baseUrl) return null;
|
|
859
1094
|
const key = cacheKey$1(baseUrl, token, input);
|
|
860
|
-
const cachedKind =
|
|
1095
|
+
const cachedKind = mattermostOpaqueTargetCache.get(key);
|
|
861
1096
|
if (cachedKind) return {
|
|
862
1097
|
kind: cachedKind,
|
|
863
1098
|
id: input,
|
|
864
|
-
to: cachedKind
|
|
1099
|
+
to: `${cachedKind}:${input}`
|
|
865
1100
|
};
|
|
866
1101
|
const client = createMattermostClient({
|
|
867
1102
|
baseUrl,
|
|
@@ -877,21 +1112,7 @@ async function resolveMattermostOpaqueTarget(params) {
|
|
|
877
1112
|
to: `user:${input}`
|
|
878
1113
|
};
|
|
879
1114
|
} catch (err) {
|
|
880
|
-
if (parseMattermostApiStatus(err)
|
|
881
|
-
kind: "channel",
|
|
882
|
-
id: input,
|
|
883
|
-
to: `channel:${input}`
|
|
884
|
-
};
|
|
885
|
-
}
|
|
886
|
-
try {
|
|
887
|
-
const channelKind = resolveMattermostTrustedChatKind({ channelType: (await fetchMattermostChannel(client, input)).type }) === "group" ? "group" : "channel";
|
|
888
|
-
cacheMattermostOpaqueTarget(key, channelKind);
|
|
889
|
-
return {
|
|
890
|
-
kind: channelKind,
|
|
891
|
-
id: input,
|
|
892
|
-
to: `channel:${input}`
|
|
893
|
-
};
|
|
894
|
-
} catch {
|
|
1115
|
+
if (parseMattermostApiStatus(err) === 404) cacheMattermostOpaqueTarget(key, "channel");
|
|
895
1116
|
return {
|
|
896
1117
|
kind: "channel",
|
|
897
1118
|
id: input,
|
|
@@ -901,27 +1122,10 @@ async function resolveMattermostOpaqueTarget(params) {
|
|
|
901
1122
|
}
|
|
902
1123
|
//#endregion
|
|
903
1124
|
//#region extensions/mattermost/src/mattermost/send.ts
|
|
904
|
-
const MATTERMOST_BOT_USER_CACHE_MAX_ENTRIES = 64;
|
|
905
|
-
const MATTERMOST_TARGET_CACHE_MAX_ENTRIES = 1024;
|
|
906
|
-
const MATTERMOST_FORMAT_PROFILE = FormatCapabilityProfile.define({
|
|
907
|
-
mechanism: "markdown",
|
|
908
|
-
chunk: {
|
|
909
|
-
limit: 16383,
|
|
910
|
-
unit: "chars"
|
|
911
|
-
}
|
|
912
|
-
});
|
|
913
|
-
function renderMattermostMarkdown(markdown, tableMode) {
|
|
914
|
-
return tableMode === "off" && MATTERMOST_FORMAT_PROFILE.constructs.table === "native" ? markdown : convertMarkdownTables(markdown, tableMode);
|
|
915
|
-
}
|
|
916
1125
|
const botUserCache = /* @__PURE__ */ new Map();
|
|
917
1126
|
const userByNameCache = /* @__PURE__ */ new Map();
|
|
918
1127
|
const channelByNameCache = /* @__PURE__ */ new Map();
|
|
919
1128
|
const dmChannelCache = /* @__PURE__ */ new Map();
|
|
920
|
-
function cacheOutboundEntry(cache, key, value, maxEntries) {
|
|
921
|
-
cache.delete(key);
|
|
922
|
-
cache.set(key, value);
|
|
923
|
-
pruneMapToMaxSize(cache, maxEntries);
|
|
924
|
-
}
|
|
925
1129
|
const getCore = () => getMattermostRuntime();
|
|
926
1130
|
function createMattermostSendReceipt(params) {
|
|
927
1131
|
const messageIds = params.messageId.trim() && params.messageId !== "unknown" ? [params.messageId] : [];
|
|
@@ -960,16 +1164,82 @@ function normalizeMessage(text, mediaUrl) {
|
|
|
960
1164
|
function isHttpUrl(value) {
|
|
961
1165
|
return /^https?:\/\//i.test(value);
|
|
962
1166
|
}
|
|
1167
|
+
function parseMattermostTarget(raw) {
|
|
1168
|
+
const trimmed = raw.trim();
|
|
1169
|
+
if (!trimmed) throw new Error("Recipient is required for Mattermost sends");
|
|
1170
|
+
const lower = normalizeLowercaseStringOrEmpty(trimmed);
|
|
1171
|
+
if (lower.startsWith("channel:")) {
|
|
1172
|
+
const id = trimmed.slice(8).trim();
|
|
1173
|
+
if (!id) throw new Error("Channel id is required for Mattermost sends");
|
|
1174
|
+
if (id.startsWith("#")) {
|
|
1175
|
+
const name = id.slice(1).trim();
|
|
1176
|
+
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
1177
|
+
return {
|
|
1178
|
+
kind: "channel-name",
|
|
1179
|
+
name
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
if (!isMattermostId(id)) return {
|
|
1183
|
+
kind: "channel-name",
|
|
1184
|
+
name: id
|
|
1185
|
+
};
|
|
1186
|
+
return {
|
|
1187
|
+
kind: "channel",
|
|
1188
|
+
id
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
if (lower.startsWith("user:")) {
|
|
1192
|
+
const id = trimmed.slice(5).trim();
|
|
1193
|
+
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
1194
|
+
return {
|
|
1195
|
+
kind: "user",
|
|
1196
|
+
id
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
if (lower.startsWith("mattermost:")) {
|
|
1200
|
+
const id = trimmed.slice(11).trim();
|
|
1201
|
+
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
1202
|
+
return {
|
|
1203
|
+
kind: "user",
|
|
1204
|
+
id
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
if (trimmed.startsWith("@")) {
|
|
1208
|
+
const username = trimmed.slice(1).trim();
|
|
1209
|
+
if (!username) throw new Error("Username is required for Mattermost sends");
|
|
1210
|
+
return {
|
|
1211
|
+
kind: "user",
|
|
1212
|
+
username
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
if (trimmed.startsWith("#")) {
|
|
1216
|
+
const name = trimmed.slice(1).trim();
|
|
1217
|
+
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
1218
|
+
return {
|
|
1219
|
+
kind: "channel-name",
|
|
1220
|
+
name
|
|
1221
|
+
};
|
|
1222
|
+
}
|
|
1223
|
+
if (!isMattermostId(trimmed)) return {
|
|
1224
|
+
kind: "channel-name",
|
|
1225
|
+
name: trimmed
|
|
1226
|
+
};
|
|
1227
|
+
return {
|
|
1228
|
+
kind: "channel",
|
|
1229
|
+
id: trimmed
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
963
1232
|
async function resolveBotUser(baseUrl, token, allowPrivateNetwork) {
|
|
964
1233
|
const key = cacheKey(baseUrl, token);
|
|
965
1234
|
const cached = botUserCache.get(key);
|
|
966
1235
|
if (cached) return cached;
|
|
967
|
-
const
|
|
1236
|
+
const client = createMattermostClient({
|
|
968
1237
|
baseUrl,
|
|
969
1238
|
botToken: token,
|
|
970
1239
|
allowPrivateNetwork
|
|
971
|
-
})
|
|
972
|
-
|
|
1240
|
+
});
|
|
1241
|
+
const user = await fetchMattermostMe(client);
|
|
1242
|
+
botUserCache.set(key, user);
|
|
973
1243
|
return user;
|
|
974
1244
|
}
|
|
975
1245
|
async function resolveUserIdByUsername(params) {
|
|
@@ -977,12 +1247,13 @@ async function resolveUserIdByUsername(params) {
|
|
|
977
1247
|
const key = `${cacheKey(baseUrl, token)}::${normalizeLowercaseStringOrEmpty(username)}`;
|
|
978
1248
|
const cached = userByNameCache.get(key);
|
|
979
1249
|
if (cached?.id) return cached.id;
|
|
980
|
-
const
|
|
1250
|
+
const client = createMattermostClient({
|
|
981
1251
|
baseUrl,
|
|
982
1252
|
botToken: token,
|
|
983
1253
|
allowPrivateNetwork: params.allowPrivateNetwork
|
|
984
|
-
})
|
|
985
|
-
|
|
1254
|
+
});
|
|
1255
|
+
const user = await fetchMattermostUserByUsername(client, username);
|
|
1256
|
+
userByNameCache.set(key, user);
|
|
986
1257
|
return user.id;
|
|
987
1258
|
}
|
|
988
1259
|
async function resolveChannelIdByName(params) {
|
|
@@ -995,11 +1266,12 @@ async function resolveChannelIdByName(params) {
|
|
|
995
1266
|
botToken: token,
|
|
996
1267
|
allowPrivateNetwork: params.allowPrivateNetwork
|
|
997
1268
|
});
|
|
998
|
-
const
|
|
1269
|
+
const me = await fetchMattermostMe(client);
|
|
1270
|
+
const teams = await fetchMattermostUserTeams(client, me.id);
|
|
999
1271
|
for (const team of teams) try {
|
|
1000
1272
|
const channel = await fetchMattermostChannelByName(client, team.id, name);
|
|
1001
1273
|
if (channel?.id) {
|
|
1002
|
-
|
|
1274
|
+
channelByNameCache.set(key, channel.id);
|
|
1003
1275
|
return channel.id;
|
|
1004
1276
|
}
|
|
1005
1277
|
} catch {}
|
|
@@ -1034,11 +1306,12 @@ async function resolveTargetChannelId(params) {
|
|
|
1034
1306
|
const cachedDm = dmChannelCache.get(dmKey);
|
|
1035
1307
|
if (cachedDm) return cachedDm;
|
|
1036
1308
|
const botUser = await resolveBotUser(params.baseUrl, params.token, params.allowPrivateNetwork);
|
|
1037
|
-
const
|
|
1309
|
+
const client = createMattermostClient({
|
|
1038
1310
|
baseUrl: params.baseUrl,
|
|
1039
1311
|
botToken: params.token,
|
|
1040
1312
|
allowPrivateNetwork: params.allowPrivateNetwork
|
|
1041
|
-
})
|
|
1313
|
+
});
|
|
1314
|
+
const resolution = createMattermostDirectChannelWithRetry(client, [botUser.id, userId], {
|
|
1042
1315
|
...params.dmRetryOptions,
|
|
1043
1316
|
onRetry: (attempt, delayMs, error) => {
|
|
1044
1317
|
params.dmRetryOptions?.onRetry?.(attempt, delayMs, error);
|
|
@@ -1047,7 +1320,7 @@ async function resolveTargetChannelId(params) {
|
|
|
1047
1320
|
});
|
|
1048
1321
|
params.onDmChannelResolution?.(resolution);
|
|
1049
1322
|
const channel = await resolution;
|
|
1050
|
-
|
|
1323
|
+
dmChannelCache.set(dmKey, channel.id);
|
|
1051
1324
|
return channel.id;
|
|
1052
1325
|
}
|
|
1053
1326
|
async function resolveMattermostSendContext(to, opts) {
|
|
@@ -1155,7 +1428,7 @@ async function sendMessageMattermost(to, text, opts) {
|
|
|
1155
1428
|
channel: "mattermost",
|
|
1156
1429
|
accountId
|
|
1157
1430
|
});
|
|
1158
|
-
message =
|
|
1431
|
+
message = convertMarkdownTables(message, tableMode);
|
|
1159
1432
|
}
|
|
1160
1433
|
if (!message && (!fileIds || fileIds.length === 0)) {
|
|
1161
1434
|
if (uploadError) throw new Error(`Mattermost media upload failed: ${uploadError.message}`, { cause: uploadError });
|
|
@@ -1168,39 +1441,26 @@ async function sendMessageMattermost(to, text, opts) {
|
|
|
1168
1441
|
fileIds,
|
|
1169
1442
|
props
|
|
1170
1443
|
});
|
|
1444
|
+
recordMattermostOutboundActivity(accountId);
|
|
1171
1445
|
const messageId = post.id ?? "unknown";
|
|
1172
|
-
|
|
1173
|
-
messageId,
|
|
1174
|
-
channelId,
|
|
1175
|
-
kind: resolveMattermostReceiptKind({
|
|
1176
|
-
fileIds,
|
|
1177
|
-
buttons: opts.buttons,
|
|
1178
|
-
props
|
|
1179
|
-
}),
|
|
1180
|
-
replyToId: opts.replyToId
|
|
1181
|
-
});
|
|
1182
|
-
const result = {
|
|
1446
|
+
return {
|
|
1183
1447
|
messageId,
|
|
1184
1448
|
channelId,
|
|
1185
|
-
receipt
|
|
1186
|
-
|
|
1449
|
+
receipt: createMattermostSendReceipt({
|
|
1450
|
+
messageId,
|
|
1451
|
+
channelId,
|
|
1452
|
+
kind: resolveMattermostReceiptKind({
|
|
1453
|
+
fileIds,
|
|
1454
|
+
buttons: opts.buttons,
|
|
1455
|
+
props
|
|
1456
|
+
}),
|
|
1457
|
+
replyToId: opts.replyToId
|
|
1458
|
+
})
|
|
1187
1459
|
};
|
|
1188
|
-
try {
|
|
1189
|
-
await opts.onDeliveryResult?.(result);
|
|
1190
|
-
recordMattermostOutboundActivity(accountId);
|
|
1191
|
-
} catch (error) {
|
|
1192
|
-
throw createChannelPartialDeliveryError(error, {
|
|
1193
|
-
messageIds: listMessageReceiptPlatformIds(receipt),
|
|
1194
|
-
receipt,
|
|
1195
|
-
visibleReplySent: true,
|
|
1196
|
-
content: result.content
|
|
1197
|
-
});
|
|
1198
|
-
}
|
|
1199
|
-
return result;
|
|
1200
1460
|
}
|
|
1201
1461
|
//#endregion
|
|
1202
1462
|
//#region extensions/mattermost/src/mattermost/slash-http.ts
|
|
1203
|
-
const MAX_BODY_BYTES =
|
|
1463
|
+
const MAX_BODY_BYTES = 65536;
|
|
1204
1464
|
const BODY_READ_TIMEOUT_MS = 5e3;
|
|
1205
1465
|
const COMMAND_LOOKUP_TIMEOUT_MS = 1e3;
|
|
1206
1466
|
const COMMAND_VALIDATION_FAILURE_CACHE_MS = 5e3;
|
|
@@ -1242,7 +1502,7 @@ function isDeletedMattermostCommand(command) {
|
|
|
1242
1502
|
return typeof command.delete_at === "number" && command.delete_at > 0;
|
|
1243
1503
|
}
|
|
1244
1504
|
function sanitizeCommandLookupError(error) {
|
|
1245
|
-
return
|
|
1505
|
+
return (error instanceof Error ? error.message : String(error)).replace(/[\r\n\t]/gu, " ").replace(/https?:\/\/[^\s)\]}]+/giu, (urlText) => {
|
|
1246
1506
|
try {
|
|
1247
1507
|
const url = new URL(urlText);
|
|
1248
1508
|
if (url.username || url.password) {
|
|
@@ -1254,10 +1514,10 @@ function sanitizeCommandLookupError(error) {
|
|
|
1254
1514
|
} catch {
|
|
1255
1515
|
return urlText;
|
|
1256
1516
|
}
|
|
1257
|
-
}).replace(/(^|[^\w-])(Bearer|Token)\s+[A-Za-z0-9._~+/=-]+/giu, "$1$2 [redacted]").replace(/\b(token|authorization|access_token|refresh_token|client_secret|botToken)\b(\s*["']?\s*(?:=|:)\s*["']?)[^"',\s;}]+/giu, "$1$2[redacted]"), 300);
|
|
1517
|
+
}).replace(/(^|[^\w-])(Bearer|Token)\s+[A-Za-z0-9._~+/=-]+/giu, "$1$2 [redacted]").replace(/\b(token|authorization|access_token|refresh_token|client_secret|botToken)\b(\s*["']?\s*(?:=|:)\s*["']?)[^"',\s;}]+/giu, "$1$2[redacted]").slice(0, 300);
|
|
1258
1518
|
}
|
|
1259
1519
|
function sanitizeMattermostLogValue(value) {
|
|
1260
|
-
return
|
|
1520
|
+
return value.replace(/[\r\n\t]/gu, " ").slice(0, 200);
|
|
1261
1521
|
}
|
|
1262
1522
|
async function withCommandLookupTimeout(task) {
|
|
1263
1523
|
const controller = new AbortController();
|
|
@@ -1334,7 +1594,8 @@ function sweepCommandValidationLookupRateLimit(now = Date.now()) {
|
|
|
1334
1594
|
}
|
|
1335
1595
|
}
|
|
1336
1596
|
function reserveCommandValidationLookup(params) {
|
|
1337
|
-
const
|
|
1597
|
+
const rawNow = params.now ?? Date.now();
|
|
1598
|
+
const now = asDateTimestampMs(rawNow);
|
|
1338
1599
|
if (now === void 0) {
|
|
1339
1600
|
commandValidationLookupRateLimit.clear();
|
|
1340
1601
|
return { allowed: true };
|
|
@@ -1344,7 +1605,7 @@ function reserveCommandValidationLookup(params) {
|
|
|
1344
1605
|
if (!existing) {
|
|
1345
1606
|
commandValidationLookupRateLimit.set(params.key, {
|
|
1346
1607
|
accountId: params.accountId,
|
|
1347
|
-
tokens:
|
|
1608
|
+
tokens: 19,
|
|
1348
1609
|
updatedAt: now,
|
|
1349
1610
|
lastLimitedLogAt: 0
|
|
1350
1611
|
});
|
|
@@ -1688,7 +1949,7 @@ async function handleSlashCommandAsync(params) {
|
|
|
1688
1949
|
runtime.log?.(`delivered model picker to ${to}`);
|
|
1689
1950
|
return;
|
|
1690
1951
|
}
|
|
1691
|
-
const ctxPayload = finalizeInboundContext({
|
|
1952
|
+
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
1692
1953
|
Body: commandText,
|
|
1693
1954
|
BodyForAgent: commandText,
|
|
1694
1955
|
RawBody: commandText,
|
|
@@ -1718,44 +1979,12 @@ async function handleSlashCommandAsync(params) {
|
|
|
1718
1979
|
channel: "mattermost",
|
|
1719
1980
|
accountId: account.accountId
|
|
1720
1981
|
});
|
|
1721
|
-
const
|
|
1722
|
-
const deliveryBarrier = createMattermostReplyDeliveryBarrier({
|
|
1723
|
-
isDirect: kind === "direct",
|
|
1724
|
-
dmRetryOptions: account.config.dmChannelRetry
|
|
1725
|
-
});
|
|
1726
|
-
await core.channel.inbound.dispatch({
|
|
1982
|
+
const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
|
|
1727
1983
|
cfg,
|
|
1984
|
+
agentId: route.agentId,
|
|
1728
1985
|
channel: "mattermost",
|
|
1729
1986
|
accountId: account.accountId,
|
|
1730
|
-
|
|
1731
|
-
agentId: route.agentId,
|
|
1732
|
-
dmScope: route.dmScope,
|
|
1733
|
-
sessionKey: route.sessionKey
|
|
1734
|
-
},
|
|
1735
|
-
ctxPayload,
|
|
1736
|
-
delivery: {
|
|
1737
|
-
observeMessageSent: true,
|
|
1738
|
-
deliver: async (payload) => {
|
|
1739
|
-
const result = await deliverMattermostReplyPayload({
|
|
1740
|
-
core,
|
|
1741
|
-
cfg,
|
|
1742
|
-
payload,
|
|
1743
|
-
to,
|
|
1744
|
-
accountId: account.accountId,
|
|
1745
|
-
agentId: route.agentId,
|
|
1746
|
-
textLimit,
|
|
1747
|
-
tableMode,
|
|
1748
|
-
sendMessage: sendMessageMattermost,
|
|
1749
|
-
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
|
|
1750
|
-
});
|
|
1751
|
-
if (result.visibleReplySent) runtime.log?.(`delivered slash reply to ${to}`);
|
|
1752
|
-
return result;
|
|
1753
|
-
},
|
|
1754
|
-
onError: (err, info) => {
|
|
1755
|
-
runtime.error?.(`mattermost slash ${info.kind} reply failed: ${sanitizeCommandLookupError(err)}`);
|
|
1756
|
-
}
|
|
1757
|
-
},
|
|
1758
|
-
replyPipeline: { typing: {
|
|
1987
|
+
typing: {
|
|
1759
1988
|
start: () => sendMattermostTyping(client, { channelId }),
|
|
1760
1989
|
onStartError: (err) => {
|
|
1761
1990
|
logTypingFailure({
|
|
@@ -1765,18 +1994,58 @@ async function handleSlashCommandAsync(params) {
|
|
|
1765
1994
|
error: err
|
|
1766
1995
|
});
|
|
1767
1996
|
}
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1997
|
+
}
|
|
1998
|
+
});
|
|
1999
|
+
const humanDelay = core.channel.reply.resolveHumanDelayConfig(cfg, route.agentId);
|
|
2000
|
+
const deliveryBarrier = createMattermostReplyDeliveryBarrier({
|
|
2001
|
+
isDirect: kind === "direct",
|
|
2002
|
+
dmRetryOptions: account.config.dmChannelRetry
|
|
2003
|
+
});
|
|
2004
|
+
const { dispatcher, replyOptions, markDispatchIdle } = core.channel.reply.createReplyDispatcherWithTyping({
|
|
2005
|
+
...replyPipeline,
|
|
2006
|
+
resolveFollowupAdmissionBarrierTimeoutPolicy: deliveryBarrier.resolveTimeoutPolicy,
|
|
2007
|
+
onDeliverySettled: deliveryBarrier.markDeliverySettled,
|
|
2008
|
+
humanDelay,
|
|
2009
|
+
deliver: async (payload) => {
|
|
2010
|
+
await deliverMattermostReplyPayload({
|
|
2011
|
+
core,
|
|
2012
|
+
cfg,
|
|
2013
|
+
payload,
|
|
2014
|
+
to,
|
|
2015
|
+
accountId: account.accountId,
|
|
2016
|
+
agentId: route.agentId,
|
|
2017
|
+
textLimit,
|
|
2018
|
+
tableMode,
|
|
2019
|
+
sendMessage: sendMessageMattermost,
|
|
2020
|
+
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
|
|
2021
|
+
});
|
|
2022
|
+
runtime.log?.(`delivered slash reply to ${to}`);
|
|
1773
2023
|
},
|
|
1774
|
-
|
|
2024
|
+
onError: (err, info) => {
|
|
2025
|
+
runtime.error?.(`mattermost slash ${info.kind} reply failed: ${sanitizeCommandLookupError(err)}`);
|
|
2026
|
+
},
|
|
2027
|
+
onReplyStart: typingCallbacks?.onReplyStart
|
|
2028
|
+
});
|
|
2029
|
+
await core.channel.reply.withReplyDispatcher({
|
|
2030
|
+
dispatcher,
|
|
2031
|
+
onSettled: () => {
|
|
2032
|
+
markDispatchIdle();
|
|
2033
|
+
},
|
|
2034
|
+
run: () => core.channel.reply.dispatchReplyFromConfig({
|
|
2035
|
+
ctx: ctxPayload,
|
|
2036
|
+
cfg,
|
|
2037
|
+
dispatcher,
|
|
2038
|
+
replyOptions: {
|
|
2039
|
+
...replyOptions,
|
|
2040
|
+
disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0,
|
|
2041
|
+
onModelSelected
|
|
2042
|
+
}
|
|
2043
|
+
})
|
|
1775
2044
|
});
|
|
1776
2045
|
}
|
|
1777
2046
|
//#endregion
|
|
1778
2047
|
//#region extensions/mattermost/src/mattermost/slash-state.ts
|
|
1779
|
-
const MULTI_ACCOUNT_BODY_MAX_BYTES =
|
|
2048
|
+
const MULTI_ACCOUNT_BODY_MAX_BYTES = 65536;
|
|
1780
2049
|
const MULTI_ACCOUNT_BODY_TIMEOUT_MS = 5e3;
|
|
1781
2050
|
/**
|
|
1782
2051
|
* Map from accountId → per-account slash command state.
|
|
@@ -1804,16 +2073,12 @@ function resolveSlashHandlerForToken(token) {
|
|
|
1804
2073
|
handler: state.handler
|
|
1805
2074
|
});
|
|
1806
2075
|
if (matches.length === 0) return { kind: "none" };
|
|
1807
|
-
if (matches.length === 1) {
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
handler: match.handler,
|
|
1814
|
-
accountIds: [match.accountId]
|
|
1815
|
-
};
|
|
1816
|
-
}
|
|
2076
|
+
if (matches.length === 1) return {
|
|
2077
|
+
kind: "single",
|
|
2078
|
+
source: "token",
|
|
2079
|
+
handler: matches[0].handler,
|
|
2080
|
+
accountIds: [matches[0].accountId]
|
|
2081
|
+
};
|
|
1817
2082
|
return {
|
|
1818
2083
|
kind: "ambiguous",
|
|
1819
2084
|
source: "token",
|
|
@@ -1829,16 +2094,12 @@ function resolveSlashHandlerForCommand(params) {
|
|
|
1829
2094
|
handler: state.handler
|
|
1830
2095
|
});
|
|
1831
2096
|
if (matches.length === 0) return { kind: "none" };
|
|
1832
|
-
if (matches.length === 1) {
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
handler: match.handler,
|
|
1839
|
-
accountIds: [match.accountId]
|
|
1840
|
-
};
|
|
1841
|
-
}
|
|
2097
|
+
if (matches.length === 1) return {
|
|
2098
|
+
kind: "single",
|
|
2099
|
+
source: "command",
|
|
2100
|
+
handler: matches[0].handler,
|
|
2101
|
+
accountIds: [matches[0].accountId]
|
|
2102
|
+
};
|
|
1842
2103
|
return {
|
|
1843
2104
|
kind: "ambiguous",
|
|
1844
2105
|
source: "command",
|
|
@@ -1937,8 +2198,8 @@ function registerSlashCommandRoute(api) {
|
|
|
1937
2198
|
return;
|
|
1938
2199
|
}
|
|
1939
2200
|
if (accountStates.size === 1) {
|
|
1940
|
-
const state = accountStates.
|
|
1941
|
-
if (!state
|
|
2201
|
+
const [, state] = [...accountStates.entries()][0];
|
|
2202
|
+
if (!state.handler) {
|
|
1942
2203
|
res.statusCode = 503;
|
|
1943
2204
|
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1944
2205
|
res.end(JSON.stringify({
|
|
@@ -2017,4 +2278,4 @@ function registerSlashCommandRoute(api) {
|
|
|
2017
2278
|
});
|
|
2018
2279
|
}
|
|
2019
2280
|
//#endregion
|
|
2020
|
-
export { isSlashCommandsEnabled as _, sendMessageMattermost as a,
|
|
2281
|
+
export { registerSlashCommands as C, isSlashCommandsEnabled as S, resolveSlashCommandConfig as T, renderMattermostModelsPickerView as _, sendMessageMattermost as a, DEFAULT_COMMAND_SPECS as b, computeInteractionCallbackUrl as c, setInteractionCallbackUrl as d, setInteractionSecret as f, parseMattermostModelPickerContext as g, buildMattermostAllowedModelRefs as h, registerSlashCommandRoute as i, createMattermostInteractionHandler as l, deliverMattermostReplyPayload as m, deactivateSlashCommands as n, resolveMattermostOpaqueTarget as o, createMattermostReplyDeliveryBarrier as p, getSlashCommandState as r, buildButtonProps as s, activateSlashCommands as t, resolveInteractionCallbackPath as u, renderMattermostProviderPickerView as v, resolveCallbackUrl as w, cleanupSlashCommands as x, resolveMattermostModelPickerCurrentModel as y };
|