@openclaw/mattermost 2026.7.2-beta.5 → 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-w0lkxuKh.js → .setup/accounts-CkvUBI7I.mjs} +100 -31
- 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-DLBTUlbh.js → .setup/channel-plugin-runtime-BLOKRsgT.mjs} +212 -215
- 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-BOh6zLW9.js → .setup/monitor-auth-CeakcTAO.mjs} +12 -13
- package/dist/.setup/secret-contract-Cx0LUNXy.mjs +44 -0
- package/dist/.setup/secret-contract-api-BLTnjVCZ.mjs +3 -0
- package/dist/{slash-state-VCRdqj5F.js → .setup/slash-state-D1e1_KaK.mjs} +534 -189
- 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 +215 -255
- package/package.json +6 -52
- package/dist/accounts-BR6Nl5Qf.js +0 -71
- package/dist/channel.runtime-CR1V5M8l.js +0 -2873
- package/dist/doctor-contract-BaUvVh8e.js +0 -19
- package/dist/interactions-B4gg-KRm.js +0 -375
- package/dist/secret-contract-B4R5Bmhv.js +0 -28
- /package/dist/{runtime-CNB4YGqJ.js → .setup/runtime-CNB4YGqJ.mjs} +0 -0
|
@@ -1,27 +1,22 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { c as setInteractionSecret, n as buildButtonProps, o as resolveInteractionCallbackUrl } from "./interactions-B4gg-KRm.js";
|
|
5
|
-
import { r as resolveMattermostAccount } from "./accounts-BR6Nl5Qf.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 { asDateTimestampMs, parseStrictInteger, resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
|
|
10
|
-
import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
11
5
|
import { createMessageReceiptFromOutboundResults } from "openclaw/plugin-sdk/channel-outbound";
|
|
12
6
|
import { resolveStoredModelOverride } from "openclaw/plugin-sdk/command-auth-native";
|
|
13
7
|
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
|
|
8
|
+
import { asDateTimestampMs, parseStrictInteger, resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
|
|
14
9
|
import { deliverTextOrMediaReply, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
|
|
15
|
-
import {
|
|
10
|
+
import { isPrivateNetworkOptInEnabled } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
11
|
+
import { convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";
|
|
16
12
|
import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
|
|
17
13
|
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
18
14
|
import { Readable } from "node:stream";
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
22
|
-
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
15
|
+
import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
|
|
16
|
+
import { createHash, createHmac } from "node:crypto";
|
|
23
17
|
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
|
|
24
18
|
import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
|
|
19
|
+
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
25
20
|
const MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES = 128;
|
|
26
21
|
function truncateMattermostCommandDescription(description) {
|
|
27
22
|
if (Buffer.byteLength(description, "utf8") <= MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES) return description;
|
|
@@ -375,9 +370,7 @@ const ACTION_IDS = {
|
|
|
375
370
|
function splitModelRef(modelRef) {
|
|
376
371
|
const match = normalizeOptionalString(modelRef)?.match(/^([^/]+)\/(.+)$/u);
|
|
377
372
|
if (!match) return null;
|
|
378
|
-
const
|
|
379
|
-
if (!rawProvider) return null;
|
|
380
|
-
const provider = normalizeProviderId(rawProvider);
|
|
373
|
+
const provider = normalizeProviderId(match[1]);
|
|
381
374
|
const model = normalizeOptionalString(match[2]);
|
|
382
375
|
if (!provider || !model) return null;
|
|
383
376
|
return {
|
|
@@ -661,12 +654,6 @@ function createMattermostReplyDeliveryBarrier(params) {
|
|
|
661
654
|
resolveTimeoutPolicy
|
|
662
655
|
};
|
|
663
656
|
}
|
|
664
|
-
function toMattermostChannelDeliveryResult(outcome) {
|
|
665
|
-
return outcome === "text" || outcome === "media" ? { visibleReplySent: true } : {
|
|
666
|
-
visibleReplySent: false,
|
|
667
|
-
suppression: { reason: "no_visible_result" }
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
657
|
async function deliverMattermostReplyPayload(params) {
|
|
671
658
|
if (isReasoningReplyPayload(params.payload)) return "reasoning_skipped";
|
|
672
659
|
const reply = resolveSendableOutboundReplyParts(params.payload, { text: params.core.channel.text.convertMarkdownTables(params.payload.text ?? "", params.tableMode) });
|
|
@@ -697,6 +684,376 @@ async function deliverMattermostReplyPayload(params) {
|
|
|
697
684
|
});
|
|
698
685
|
}
|
|
699
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;
|
|
755
|
+
}
|
|
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
|
+
};
|
|
822
|
+
});
|
|
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
|
+
}
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
//#endregion
|
|
700
1057
|
//#region extensions/mattermost/src/mattermost/target-resolution.ts
|
|
701
1058
|
const MATTERMOST_OPAQUE_TARGET_CACHE_MAX_ENTRIES = 1024;
|
|
702
1059
|
const mattermostOpaqueTargetCache = /* @__PURE__ */ new Map();
|
|
@@ -711,71 +1068,6 @@ function cacheKey$1(baseUrl, token, id) {
|
|
|
711
1068
|
function isMattermostId(value) {
|
|
712
1069
|
return /^[a-z0-9]{26}$/.test(value);
|
|
713
1070
|
}
|
|
714
|
-
function parseMattermostTarget(raw) {
|
|
715
|
-
const trimmed = raw.trim();
|
|
716
|
-
if (!trimmed) throw new Error("Recipient is required for Mattermost sends");
|
|
717
|
-
const lower = normalizeLowercaseStringOrEmpty(trimmed);
|
|
718
|
-
if (lower.startsWith("channel:")) {
|
|
719
|
-
const id = trimmed.slice(8).trim();
|
|
720
|
-
if (!id) throw new Error("Channel id is required for Mattermost sends");
|
|
721
|
-
if (id.startsWith("#")) {
|
|
722
|
-
const name = id.slice(1).trim();
|
|
723
|
-
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
724
|
-
return {
|
|
725
|
-
kind: "channel-name",
|
|
726
|
-
name
|
|
727
|
-
};
|
|
728
|
-
}
|
|
729
|
-
if (!isMattermostId(id)) return {
|
|
730
|
-
kind: "channel-name",
|
|
731
|
-
name: id
|
|
732
|
-
};
|
|
733
|
-
return {
|
|
734
|
-
kind: "channel",
|
|
735
|
-
id
|
|
736
|
-
};
|
|
737
|
-
}
|
|
738
|
-
if (lower.startsWith("user:")) {
|
|
739
|
-
const id = trimmed.slice(5).trim();
|
|
740
|
-
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
741
|
-
return {
|
|
742
|
-
kind: "user",
|
|
743
|
-
id
|
|
744
|
-
};
|
|
745
|
-
}
|
|
746
|
-
if (lower.startsWith("mattermost:")) {
|
|
747
|
-
const id = trimmed.slice(11).trim();
|
|
748
|
-
if (!id) throw new Error("User id is required for Mattermost sends");
|
|
749
|
-
return {
|
|
750
|
-
kind: "user",
|
|
751
|
-
id
|
|
752
|
-
};
|
|
753
|
-
}
|
|
754
|
-
if (trimmed.startsWith("@")) {
|
|
755
|
-
const username = trimmed.slice(1).trim();
|
|
756
|
-
if (!username) throw new Error("Username is required for Mattermost sends");
|
|
757
|
-
return {
|
|
758
|
-
kind: "user",
|
|
759
|
-
username
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
if (trimmed.startsWith("#")) {
|
|
763
|
-
const name = trimmed.slice(1).trim();
|
|
764
|
-
if (!name) throw new Error("Channel name is required for Mattermost sends");
|
|
765
|
-
return {
|
|
766
|
-
kind: "channel-name",
|
|
767
|
-
name
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
if (!isMattermostId(trimmed)) return {
|
|
771
|
-
kind: "channel-name",
|
|
772
|
-
name: trimmed
|
|
773
|
-
};
|
|
774
|
-
return {
|
|
775
|
-
kind: "channel",
|
|
776
|
-
id: trimmed
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
1071
|
function isExplicitMattermostTarget(raw) {
|
|
780
1072
|
const trimmed = raw.trim();
|
|
781
1073
|
if (!trimmed) return false;
|
|
@@ -796,7 +1088,6 @@ async function resolveMattermostOpaqueTarget(params) {
|
|
|
796
1088
|
cfg: params.cfg,
|
|
797
1089
|
accountId: params.accountId
|
|
798
1090
|
}) : null;
|
|
799
|
-
if (account && !account.enabled) throw new Error(`Mattermost account "${account.accountId}" is disabled`);
|
|
800
1091
|
const token = normalizeOptionalString(params.token) ?? normalizeOptionalString(account?.botToken);
|
|
801
1092
|
const baseUrl = normalizeMattermostBaseUrl(params.baseUrl ?? account?.baseUrl);
|
|
802
1093
|
if (!token || !baseUrl) return null;
|
|
@@ -831,27 +1122,10 @@ async function resolveMattermostOpaqueTarget(params) {
|
|
|
831
1122
|
}
|
|
832
1123
|
//#endregion
|
|
833
1124
|
//#region extensions/mattermost/src/mattermost/send.ts
|
|
834
|
-
const MATTERMOST_BOT_USER_CACHE_MAX_ENTRIES = 64;
|
|
835
|
-
const MATTERMOST_TARGET_CACHE_MAX_ENTRIES = 1024;
|
|
836
|
-
const MATTERMOST_FORMAT_PROFILE = FormatCapabilityProfile.define({
|
|
837
|
-
mechanism: "markdown",
|
|
838
|
-
chunk: {
|
|
839
|
-
limit: 16383,
|
|
840
|
-
unit: "chars"
|
|
841
|
-
}
|
|
842
|
-
});
|
|
843
|
-
function renderMattermostMarkdown(markdown, tableMode) {
|
|
844
|
-
return tableMode === "off" && MATTERMOST_FORMAT_PROFILE.constructs.table === "native" ? markdown : convertMarkdownTables(markdown, tableMode);
|
|
845
|
-
}
|
|
846
1125
|
const botUserCache = /* @__PURE__ */ new Map();
|
|
847
1126
|
const userByNameCache = /* @__PURE__ */ new Map();
|
|
848
1127
|
const channelByNameCache = /* @__PURE__ */ new Map();
|
|
849
1128
|
const dmChannelCache = /* @__PURE__ */ new Map();
|
|
850
|
-
function cacheOutboundEntry(cache, key, value, maxEntries) {
|
|
851
|
-
cache.delete(key);
|
|
852
|
-
cache.set(key, value);
|
|
853
|
-
pruneMapToMaxSize(cache, maxEntries);
|
|
854
|
-
}
|
|
855
1129
|
const getCore = () => getMattermostRuntime();
|
|
856
1130
|
function createMattermostSendReceipt(params) {
|
|
857
1131
|
const messageIds = params.messageId.trim() && params.messageId !== "unknown" ? [params.messageId] : [];
|
|
@@ -890,16 +1164,82 @@ function normalizeMessage(text, mediaUrl) {
|
|
|
890
1164
|
function isHttpUrl(value) {
|
|
891
1165
|
return /^https?:\/\//i.test(value);
|
|
892
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
|
+
}
|
|
893
1232
|
async function resolveBotUser(baseUrl, token, allowPrivateNetwork) {
|
|
894
1233
|
const key = cacheKey(baseUrl, token);
|
|
895
1234
|
const cached = botUserCache.get(key);
|
|
896
1235
|
if (cached) return cached;
|
|
897
|
-
const
|
|
1236
|
+
const client = createMattermostClient({
|
|
898
1237
|
baseUrl,
|
|
899
1238
|
botToken: token,
|
|
900
1239
|
allowPrivateNetwork
|
|
901
|
-
})
|
|
902
|
-
|
|
1240
|
+
});
|
|
1241
|
+
const user = await fetchMattermostMe(client);
|
|
1242
|
+
botUserCache.set(key, user);
|
|
903
1243
|
return user;
|
|
904
1244
|
}
|
|
905
1245
|
async function resolveUserIdByUsername(params) {
|
|
@@ -907,12 +1247,13 @@ async function resolveUserIdByUsername(params) {
|
|
|
907
1247
|
const key = `${cacheKey(baseUrl, token)}::${normalizeLowercaseStringOrEmpty(username)}`;
|
|
908
1248
|
const cached = userByNameCache.get(key);
|
|
909
1249
|
if (cached?.id) return cached.id;
|
|
910
|
-
const
|
|
1250
|
+
const client = createMattermostClient({
|
|
911
1251
|
baseUrl,
|
|
912
1252
|
botToken: token,
|
|
913
1253
|
allowPrivateNetwork: params.allowPrivateNetwork
|
|
914
|
-
})
|
|
915
|
-
|
|
1254
|
+
});
|
|
1255
|
+
const user = await fetchMattermostUserByUsername(client, username);
|
|
1256
|
+
userByNameCache.set(key, user);
|
|
916
1257
|
return user.id;
|
|
917
1258
|
}
|
|
918
1259
|
async function resolveChannelIdByName(params) {
|
|
@@ -925,11 +1266,12 @@ async function resolveChannelIdByName(params) {
|
|
|
925
1266
|
botToken: token,
|
|
926
1267
|
allowPrivateNetwork: params.allowPrivateNetwork
|
|
927
1268
|
});
|
|
928
|
-
const
|
|
1269
|
+
const me = await fetchMattermostMe(client);
|
|
1270
|
+
const teams = await fetchMattermostUserTeams(client, me.id);
|
|
929
1271
|
for (const team of teams) try {
|
|
930
1272
|
const channel = await fetchMattermostChannelByName(client, team.id, name);
|
|
931
1273
|
if (channel?.id) {
|
|
932
|
-
|
|
1274
|
+
channelByNameCache.set(key, channel.id);
|
|
933
1275
|
return channel.id;
|
|
934
1276
|
}
|
|
935
1277
|
} catch {}
|
|
@@ -964,11 +1306,12 @@ async function resolveTargetChannelId(params) {
|
|
|
964
1306
|
const cachedDm = dmChannelCache.get(dmKey);
|
|
965
1307
|
if (cachedDm) return cachedDm;
|
|
966
1308
|
const botUser = await resolveBotUser(params.baseUrl, params.token, params.allowPrivateNetwork);
|
|
967
|
-
const
|
|
1309
|
+
const client = createMattermostClient({
|
|
968
1310
|
baseUrl: params.baseUrl,
|
|
969
1311
|
botToken: params.token,
|
|
970
1312
|
allowPrivateNetwork: params.allowPrivateNetwork
|
|
971
|
-
})
|
|
1313
|
+
});
|
|
1314
|
+
const resolution = createMattermostDirectChannelWithRetry(client, [botUser.id, userId], {
|
|
972
1315
|
...params.dmRetryOptions,
|
|
973
1316
|
onRetry: (attempt, delayMs, error) => {
|
|
974
1317
|
params.dmRetryOptions?.onRetry?.(attempt, delayMs, error);
|
|
@@ -977,7 +1320,7 @@ async function resolveTargetChannelId(params) {
|
|
|
977
1320
|
});
|
|
978
1321
|
params.onDmChannelResolution?.(resolution);
|
|
979
1322
|
const channel = await resolution;
|
|
980
|
-
|
|
1323
|
+
dmChannelCache.set(dmKey, channel.id);
|
|
981
1324
|
return channel.id;
|
|
982
1325
|
}
|
|
983
1326
|
async function resolveMattermostSendContext(to, opts) {
|
|
@@ -1085,7 +1428,7 @@ async function sendMessageMattermost(to, text, opts) {
|
|
|
1085
1428
|
channel: "mattermost",
|
|
1086
1429
|
accountId
|
|
1087
1430
|
});
|
|
1088
|
-
message =
|
|
1431
|
+
message = convertMarkdownTables(message, tableMode);
|
|
1089
1432
|
}
|
|
1090
1433
|
if (!message && (!fileIds || fileIds.length === 0)) {
|
|
1091
1434
|
if (uploadError) throw new Error(`Mattermost media upload failed: ${uploadError.message}`, { cause: uploadError });
|
|
@@ -1117,7 +1460,7 @@ async function sendMessageMattermost(to, text, opts) {
|
|
|
1117
1460
|
}
|
|
1118
1461
|
//#endregion
|
|
1119
1462
|
//#region extensions/mattermost/src/mattermost/slash-http.ts
|
|
1120
|
-
const MAX_BODY_BYTES =
|
|
1463
|
+
const MAX_BODY_BYTES = 65536;
|
|
1121
1464
|
const BODY_READ_TIMEOUT_MS = 5e3;
|
|
1122
1465
|
const COMMAND_LOOKUP_TIMEOUT_MS = 1e3;
|
|
1123
1466
|
const COMMAND_VALIDATION_FAILURE_CACHE_MS = 5e3;
|
|
@@ -1159,7 +1502,7 @@ function isDeletedMattermostCommand(command) {
|
|
|
1159
1502
|
return typeof command.delete_at === "number" && command.delete_at > 0;
|
|
1160
1503
|
}
|
|
1161
1504
|
function sanitizeCommandLookupError(error) {
|
|
1162
|
-
return
|
|
1505
|
+
return (error instanceof Error ? error.message : String(error)).replace(/[\r\n\t]/gu, " ").replace(/https?:\/\/[^\s)\]}]+/giu, (urlText) => {
|
|
1163
1506
|
try {
|
|
1164
1507
|
const url = new URL(urlText);
|
|
1165
1508
|
if (url.username || url.password) {
|
|
@@ -1171,10 +1514,10 @@ function sanitizeCommandLookupError(error) {
|
|
|
1171
1514
|
} catch {
|
|
1172
1515
|
return urlText;
|
|
1173
1516
|
}
|
|
1174
|
-
}).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);
|
|
1175
1518
|
}
|
|
1176
1519
|
function sanitizeMattermostLogValue(value) {
|
|
1177
|
-
return
|
|
1520
|
+
return value.replace(/[\r\n\t]/gu, " ").slice(0, 200);
|
|
1178
1521
|
}
|
|
1179
1522
|
async function withCommandLookupTimeout(task) {
|
|
1180
1523
|
const controller = new AbortController();
|
|
@@ -1251,7 +1594,8 @@ function sweepCommandValidationLookupRateLimit(now = Date.now()) {
|
|
|
1251
1594
|
}
|
|
1252
1595
|
}
|
|
1253
1596
|
function reserveCommandValidationLookup(params) {
|
|
1254
|
-
const
|
|
1597
|
+
const rawNow = params.now ?? Date.now();
|
|
1598
|
+
const now = asDateTimestampMs(rawNow);
|
|
1255
1599
|
if (now === void 0) {
|
|
1256
1600
|
commandValidationLookupRateLimit.clear();
|
|
1257
1601
|
return { allowed: true };
|
|
@@ -1261,7 +1605,7 @@ function reserveCommandValidationLookup(params) {
|
|
|
1261
1605
|
if (!existing) {
|
|
1262
1606
|
commandValidationLookupRateLimit.set(params.key, {
|
|
1263
1607
|
accountId: params.accountId,
|
|
1264
|
-
tokens:
|
|
1608
|
+
tokens: 19,
|
|
1265
1609
|
updatedAt: now,
|
|
1266
1610
|
lastLimitedLogAt: 0
|
|
1267
1611
|
});
|
|
@@ -1605,7 +1949,7 @@ async function handleSlashCommandAsync(params) {
|
|
|
1605
1949
|
runtime.log?.(`delivered model picker to ${to}`);
|
|
1606
1950
|
return;
|
|
1607
1951
|
}
|
|
1608
|
-
const ctxPayload = finalizeInboundContext({
|
|
1952
|
+
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
1609
1953
|
Body: commandText,
|
|
1610
1954
|
BodyForAgent: commandText,
|
|
1611
1955
|
RawBody: commandText,
|
|
@@ -1635,43 +1979,12 @@ async function handleSlashCommandAsync(params) {
|
|
|
1635
1979
|
channel: "mattermost",
|
|
1636
1980
|
accountId: account.accountId
|
|
1637
1981
|
});
|
|
1638
|
-
const
|
|
1639
|
-
const deliveryBarrier = createMattermostReplyDeliveryBarrier({
|
|
1640
|
-
isDirect: kind === "direct",
|
|
1641
|
-
dmRetryOptions: account.config.dmChannelRetry
|
|
1642
|
-
});
|
|
1643
|
-
await core.channel.inbound.dispatch({
|
|
1982
|
+
const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
|
|
1644
1983
|
cfg,
|
|
1984
|
+
agentId: route.agentId,
|
|
1645
1985
|
channel: "mattermost",
|
|
1646
1986
|
accountId: account.accountId,
|
|
1647
|
-
|
|
1648
|
-
agentId: route.agentId,
|
|
1649
|
-
dmScope: route.dmScope,
|
|
1650
|
-
sessionKey: route.sessionKey
|
|
1651
|
-
},
|
|
1652
|
-
ctxPayload,
|
|
1653
|
-
delivery: {
|
|
1654
|
-
deliver: async (payload) => {
|
|
1655
|
-
const result = toMattermostChannelDeliveryResult(await deliverMattermostReplyPayload({
|
|
1656
|
-
core,
|
|
1657
|
-
cfg,
|
|
1658
|
-
payload,
|
|
1659
|
-
to,
|
|
1660
|
-
accountId: account.accountId,
|
|
1661
|
-
agentId: route.agentId,
|
|
1662
|
-
textLimit,
|
|
1663
|
-
tableMode,
|
|
1664
|
-
sendMessage: sendMessageMattermost,
|
|
1665
|
-
onDmChannelResolution: deliveryBarrier.trackDmChannelResolution
|
|
1666
|
-
}));
|
|
1667
|
-
if (result.visibleReplySent) runtime.log?.(`delivered slash reply to ${to}`);
|
|
1668
|
-
return result;
|
|
1669
|
-
},
|
|
1670
|
-
onError: (err, info) => {
|
|
1671
|
-
runtime.error?.(`mattermost slash ${info.kind} reply failed: ${sanitizeCommandLookupError(err)}`);
|
|
1672
|
-
}
|
|
1673
|
-
},
|
|
1674
|
-
replyPipeline: { typing: {
|
|
1987
|
+
typing: {
|
|
1675
1988
|
start: () => sendMattermostTyping(client, { channelId }),
|
|
1676
1989
|
onStartError: (err) => {
|
|
1677
1990
|
logTypingFailure({
|
|
@@ -1681,18 +1994,58 @@ async function handleSlashCommandAsync(params) {
|
|
|
1681
1994
|
error: err
|
|
1682
1995
|
});
|
|
1683
1996
|
}
|
|
1684
|
-
}
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
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}`);
|
|
2023
|
+
},
|
|
2024
|
+
onError: (err, info) => {
|
|
2025
|
+
runtime.error?.(`mattermost slash ${info.kind} reply failed: ${sanitizeCommandLookupError(err)}`);
|
|
1689
2026
|
},
|
|
1690
|
-
|
|
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
|
+
})
|
|
1691
2044
|
});
|
|
1692
2045
|
}
|
|
1693
2046
|
//#endregion
|
|
1694
2047
|
//#region extensions/mattermost/src/mattermost/slash-state.ts
|
|
1695
|
-
const MULTI_ACCOUNT_BODY_MAX_BYTES =
|
|
2048
|
+
const MULTI_ACCOUNT_BODY_MAX_BYTES = 65536;
|
|
1696
2049
|
const MULTI_ACCOUNT_BODY_TIMEOUT_MS = 5e3;
|
|
1697
2050
|
/**
|
|
1698
2051
|
* Map from accountId → per-account slash command state.
|
|
@@ -1720,16 +2073,12 @@ function resolveSlashHandlerForToken(token) {
|
|
|
1720
2073
|
handler: state.handler
|
|
1721
2074
|
});
|
|
1722
2075
|
if (matches.length === 0) return { kind: "none" };
|
|
1723
|
-
if (matches.length === 1) {
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
handler: match.handler,
|
|
1730
|
-
accountIds: [match.accountId]
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
2076
|
+
if (matches.length === 1) return {
|
|
2077
|
+
kind: "single",
|
|
2078
|
+
source: "token",
|
|
2079
|
+
handler: matches[0].handler,
|
|
2080
|
+
accountIds: [matches[0].accountId]
|
|
2081
|
+
};
|
|
1733
2082
|
return {
|
|
1734
2083
|
kind: "ambiguous",
|
|
1735
2084
|
source: "token",
|
|
@@ -1745,16 +2094,12 @@ function resolveSlashHandlerForCommand(params) {
|
|
|
1745
2094
|
handler: state.handler
|
|
1746
2095
|
});
|
|
1747
2096
|
if (matches.length === 0) return { kind: "none" };
|
|
1748
|
-
if (matches.length === 1) {
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
handler: match.handler,
|
|
1755
|
-
accountIds: [match.accountId]
|
|
1756
|
-
};
|
|
1757
|
-
}
|
|
2097
|
+
if (matches.length === 1) return {
|
|
2098
|
+
kind: "single",
|
|
2099
|
+
source: "command",
|
|
2100
|
+
handler: matches[0].handler,
|
|
2101
|
+
accountIds: [matches[0].accountId]
|
|
2102
|
+
};
|
|
1758
2103
|
return {
|
|
1759
2104
|
kind: "ambiguous",
|
|
1760
2105
|
source: "command",
|
|
@@ -1853,8 +2198,8 @@ function registerSlashCommandRoute(api) {
|
|
|
1853
2198
|
return;
|
|
1854
2199
|
}
|
|
1855
2200
|
if (accountStates.size === 1) {
|
|
1856
|
-
const state = accountStates.
|
|
1857
|
-
if (!state
|
|
2201
|
+
const [, state] = [...accountStates.entries()][0];
|
|
2202
|
+
if (!state.handler) {
|
|
1858
2203
|
res.statusCode = 503;
|
|
1859
2204
|
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1860
2205
|
res.end(JSON.stringify({
|
|
@@ -1933,4 +2278,4 @@ function registerSlashCommandRoute(api) {
|
|
|
1933
2278
|
});
|
|
1934
2279
|
}
|
|
1935
2280
|
//#endregion
|
|
1936
|
-
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 };
|