@openclaw/mattermost 2026.11.3 → 2026.11.5-beta.2
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/.setup/channel-plugin-api-ClU67Wyc.mjs +1 -0
- package/dist/.setup/{channel-plugin-runtime-DJgVmmbD.mjs → channel-plugin-api-CuxSSPV8.mjs} +146 -130
- package/dist/.setup/{channel.runtime-Cl_09ZUI.mjs → channel.runtime-B3RvYLQi.mjs} +28 -34
- package/dist/.setup/{client-B_4C9q6z.mjs → client-CR-hGmGr.mjs} +11 -84
- package/dist/.setup/{interactions-LQ_rJSdf.mjs → interactions-D5hhyPam.mjs} +23 -36
- package/dist/.setup/{monitor-CmsQnrEk.mjs → monitor-Bw_pTSF8.mjs} +292 -400
- package/dist/.setup/{monitor-auth-rr4M-8gH.mjs → monitor-auth-BxpEUfvc.mjs} +5 -11
- package/dist/.setup/{normalize-Dli2PK7k.mjs → normalize-CNFRtT1O.mjs} +21 -7
- package/dist/.setup/secret-contract-api-Drz4m5pq.mjs +2 -0
- package/dist/.setup/{send-C_-GT5iF.mjs → send-BSae9PKV.mjs} +100 -198
- package/dist/.setup/{slash-state-DJN_cER0.mjs → slash-state-DpZH2wr6.mjs} +362 -409
- package/dist/.source-module-urls/8fb0cb1067b83fd2cf3f3ba0f7a23e627c27e8e3adf1a4ea18753ddb884ff71e.json +1 -0
- package/dist/api.js +2 -2
- package/dist/channel-plugin-api.js +1 -2
- package/dist/doctor-contract-api.js +1 -2
- package/dist/gateway-auth-api.js +1 -2
- package/dist/policy-api.js +1 -2
- package/dist/runtime-api.js +1 -2
- package/dist/secret-contract-api.js +1 -2
- package/dist/setup-entry.js +2 -2
- package/dist/slash-route-api.js +1 -2
- package/node_modules/zod/package.json +1 -1
- package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
- package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
- package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
- package/node_modules/zod/src/v4/core/compile.ts +9 -0
- package/node_modules/zod/src/v4/core/schemas.ts +35 -1
- package/node_modules/zod/src/v4/core/util.ts +13 -0
- package/node_modules/zod/src/v4/core/versions.ts +1 -1
- package/node_modules/zod/v4/core/compile.cjs +8 -0
- package/node_modules/zod/v4/core/compile.js +8 -0
- package/node_modules/zod/v4/core/schemas.cjs +30 -0
- package/node_modules/zod/v4/core/schemas.d.cts +3 -1
- package/node_modules/zod/v4/core/schemas.d.ts +3 -1
- package/node_modules/zod/v4/core/schemas.js +30 -0
- package/node_modules/zod/v4/core/util.cjs +15 -0
- package/node_modules/zod/v4/core/util.d.cts +2 -0
- package/node_modules/zod/v4/core/util.d.ts +2 -0
- package/node_modules/zod/v4/core/util.js +14 -0
- package/node_modules/zod/v4/core/versions.cjs +1 -1
- package/node_modules/zod/v4/core/versions.js +1 -1
- package/openclaw.plugin.json +172 -0
- package/package.json +5 -5
- package/dist/.setup/channel-plugin-api-BKpd51G7.mjs +0 -3
- package/dist/.setup/secret-contract-api-BGz5_6WD.mjs +0 -3
- package/dist/channel-plugin-runtime.js +0 -2
|
@@ -1,25 +1,27 @@
|
|
|
1
1
|
import { t as getMattermostRuntime } from "./runtime-CNB4YGqJ.mjs";
|
|
2
2
|
import { n as normalizeCallbackPath, r as resolveCallbackHost, t as collectMattermostCallbackPaths } from "./callback-host-Bu2cmtfI.mjs";
|
|
3
|
-
import { r as createMattermostClient, s as fetchMattermostChannel, v as sendMattermostTyping } from "./client-
|
|
4
|
-
import { O as sendHttpRequestRejection, S as readRequestBodyWithLimit, a as normalizeMattermostAllowList, b as logTypingFailure, g as isRequestBodyLimitError, m as createWebhookInFlightLimiter, n as authorizeMattermostCommandInvocation, t as MATTERMOST_PAIRING_QUEUE_FULL_TEXT, u as buildPreparedModelsProviderData } from "./monitor-auth-
|
|
5
|
-
import { a as resolveMattermostPresentation, i as requiresMattermostMediaUpload } from "./normalize-
|
|
6
|
-
import { t as sendMessageMattermost } from "./send-
|
|
3
|
+
import { g as parseMattermostApiStatus, r as createMattermostClient, s as fetchMattermostChannel, v as sendMattermostTyping } from "./client-CR-hGmGr.mjs";
|
|
4
|
+
import { O as sendHttpRequestRejection, S as readRequestBodyWithLimit, a as normalizeMattermostAllowList, b as logTypingFailure, g as isRequestBodyLimitError, m as createWebhookInFlightLimiter, n as authorizeMattermostCommandInvocation, t as MATTERMOST_PAIRING_QUEUE_FULL_TEXT, u as buildPreparedModelsProviderData } from "./monitor-auth-BxpEUfvc.mjs";
|
|
5
|
+
import { a as resolveMattermostPresentation, f as resolveMattermostReplyToMode, i as requiresMattermostMediaUpload } from "./normalize-CNFRtT1O.mjs";
|
|
6
|
+
import { t as sendMessageMattermost } from "./send-BSae9PKV.mjs";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
|
+
import { sendJson } from "openclaw/plugin-sdk/http-response-runtime";
|
|
8
9
|
import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
|
|
9
10
|
import { asFiniteNumber, normalizeOptionalString, normalizeStringifiedOptionalString, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { createChannelDeliveryAccumulator } from "openclaw/plugin-sdk/channel-outbound";
|
|
11
|
+
import { truncateUtf8Prefix } from "openclaw/plugin-sdk/text-utility-runtime";
|
|
12
|
+
import { parseStrictInteger } from "openclaw/plugin-sdk/number-runtime";
|
|
13
|
+
import { createChannelDeliveryAccumulator, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
|
|
13
14
|
import { resolveStoredModelOverrideAsync } from "openclaw/plugin-sdk/command-auth-native";
|
|
14
|
-
import { deliverTextOrMediaReply, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
|
|
15
|
+
import { countOutboundMedia, deliverTextOrMediaReply, isReasoningReplyPayload, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
|
|
15
16
|
import { resolveGlobalMap } from "openclaw/plugin-sdk/global-singleton";
|
|
16
17
|
import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
|
|
17
18
|
import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
|
|
18
19
|
import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
|
|
19
|
-
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
20
20
|
import { getSessionEntryAsync, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
|
|
21
|
-
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
|
|
22
21
|
import { recordDeliveredCommandExchange } from "openclaw/plugin-sdk/session-transcript-runtime";
|
|
22
|
+
import { normalizeProviderId } from "openclaw/plugin-sdk/provider-model-shared";
|
|
23
|
+
import { resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
|
|
24
|
+
import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime";
|
|
23
25
|
const MATTERMOST_COMMAND_DESCRIPTION_MAX_BYTES = 128;
|
|
24
26
|
/**
|
|
25
27
|
* Built-in OpenClaw commands to register as native slash commands.
|
|
@@ -212,7 +214,8 @@ function parseSlashCommandPayload(body, contentType) {
|
|
|
212
214
|
command,
|
|
213
215
|
text: read("text") ?? "",
|
|
214
216
|
trigger_id: read("trigger_id"),
|
|
215
|
-
response_url: read("response_url")
|
|
217
|
+
response_url: read("response_url"),
|
|
218
|
+
root_id: read("root_id")
|
|
216
219
|
};
|
|
217
220
|
} catch {
|
|
218
221
|
return null;
|
|
@@ -341,11 +344,6 @@ function parseMattermostModelPickerContext(context) {
|
|
|
341
344
|
}
|
|
342
345
|
return null;
|
|
343
346
|
}
|
|
344
|
-
function buildMattermostAllowedModelRefs(data) {
|
|
345
|
-
const refs = /* @__PURE__ */ new Set();
|
|
346
|
-
for (const provider of data.providers) for (const model of data.byProvider.get(provider) ?? []) refs.add(`${provider}/${model}`);
|
|
347
|
-
return refs;
|
|
348
|
-
}
|
|
349
347
|
async function resolveMattermostModelPickerCurrentModel(params) {
|
|
350
348
|
const fallback = `${params.data.resolvedDefault.provider}/${params.data.resolvedDefault.model}`;
|
|
351
349
|
try {
|
|
@@ -470,6 +468,59 @@ function renderMattermostModelsPickerView(params) {
|
|
|
470
468
|
};
|
|
471
469
|
}
|
|
472
470
|
//#endregion
|
|
471
|
+
//#region extensions/mattermost/src/mattermost/monitor-context.ts
|
|
472
|
+
function shouldUpdateMattermostDraftToolProgress(account) {
|
|
473
|
+
return account.streamingMode !== "off" && resolveChannelStreamingPreviewToolProgress(account.config, account.streamingMode !== "progress", account.streamingMode);
|
|
474
|
+
}
|
|
475
|
+
function buildMattermostButtonInteractionMessageSid(params) {
|
|
476
|
+
return `interaction:${params.postId}:${params.actionId}`;
|
|
477
|
+
}
|
|
478
|
+
function resolveMattermostReplyRootId(params) {
|
|
479
|
+
const threadRootId = normalizeOptionalString(params.threadRootId);
|
|
480
|
+
if (params.kind === "direct" && !threadRootId) return;
|
|
481
|
+
if (threadRootId) return threadRootId;
|
|
482
|
+
return normalizeOptionalString(params.replyToId);
|
|
483
|
+
}
|
|
484
|
+
function resolveMattermostInteractionReplyRootId(params) {
|
|
485
|
+
const interactionMessageSid = normalizeOptionalString(params.interactionMessageSid);
|
|
486
|
+
const replyToId = normalizeOptionalString(params.replyToId);
|
|
487
|
+
const providerReplyToId = replyToId === interactionMessageSid ? normalizeOptionalString(params.sourcePostId) : replyToId;
|
|
488
|
+
return resolveMattermostReplyRootId({
|
|
489
|
+
kind: params.kind,
|
|
490
|
+
threadRootId: params.threadRootId,
|
|
491
|
+
replyToId: providerReplyToId
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
function canFinalizeMattermostPreviewInPlace(params) {
|
|
495
|
+
return resolveMattermostReplyRootId({
|
|
496
|
+
kind: params.kind,
|
|
497
|
+
threadRootId: params.threadRootId,
|
|
498
|
+
replyToId: params.replyToId
|
|
499
|
+
}) === params.previewRootId?.trim();
|
|
500
|
+
}
|
|
501
|
+
function formatMattermostFinalDeliveryOutcomeLog(params) {
|
|
502
|
+
if (params.outcome === "text" || params.outcome === "media") return `delivered reply to ${params.to}`;
|
|
503
|
+
if (params.outcome === "empty") {
|
|
504
|
+
const finalText = params.payload.text?.trim() ?? "";
|
|
505
|
+
const mediaUrlCount = countOutboundMedia(params.payload);
|
|
506
|
+
if (finalText.length > 0 || mediaUrlCount > 0) return `mattermost no-visible-reply: no-visible-reply-after-final-delivery to=${params.to} accountId=${params.accountId} agentId=${params.agentId ?? "unknown"} outcome=${params.outcome} finalTextLength=${finalText.length} mediaUrlCount=${mediaUrlCount}`;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
function resolveMattermostThreadSessionContext(params) {
|
|
510
|
+
const effectiveReplyToId = params.kind === "direct" && params.replyToMode === "off" ? void 0 : normalizeOptionalString(params.threadRootId) ?? (params.replyToMode !== "off" ? normalizeOptionalString(params.postId) : void 0);
|
|
511
|
+
const threadKeys = resolveThreadSessionKeys({
|
|
512
|
+
baseSessionKey: params.baseSessionKey,
|
|
513
|
+
threadId: effectiveReplyToId,
|
|
514
|
+
normalizeThreadId: (threadId) => threadId,
|
|
515
|
+
parentSessionKey: effectiveReplyToId && params.kind !== "direct" ? params.baseSessionKey : void 0
|
|
516
|
+
});
|
|
517
|
+
return {
|
|
518
|
+
effectiveReplyToId,
|
|
519
|
+
sessionKey: threadKeys.sessionKey,
|
|
520
|
+
parentSessionKey: threadKeys.parentSessionKey
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
//#endregion
|
|
473
524
|
//#region extensions/mattermost/src/mattermost/reply-delivery.ts
|
|
474
525
|
/** Represents distinct provider posts without collapsing their visible boundary. */
|
|
475
526
|
function joinMattermostVisibleContent(contents) {
|
|
@@ -521,67 +572,6 @@ async function deliverMattermostReplyPayload(params) {
|
|
|
521
572
|
};
|
|
522
573
|
}
|
|
523
574
|
//#endregion
|
|
524
|
-
//#region extensions/mattermost/src/mattermost/slash-model-picker.ts
|
|
525
|
-
/** Returns whether the reply contains models, rather than an empty-catalog notice. */
|
|
526
|
-
async function deliverMattermostSlashModelPicker(params) {
|
|
527
|
-
const { cfg, route, accountId, channelId, senderId, commandText, messageSid, entry } = params;
|
|
528
|
-
const sessionEntry = await getSessionEntryAsync({
|
|
529
|
-
agentId: route.agentId,
|
|
530
|
-
storePath: resolveStorePath(cfg.session?.store, { agentId: route.agentId }),
|
|
531
|
-
sessionKey: route.sessionKey,
|
|
532
|
-
readConsistency: "latest"
|
|
533
|
-
});
|
|
534
|
-
const data = await buildPreparedModelsProviderData(cfg, route.agentId, { sessionEntry });
|
|
535
|
-
if (data.providers.length === 0) {
|
|
536
|
-
const delivered = await sendMessageMattermost(`channel:${channelId}`, [data.refreshWarning, "No models available."].filter(Boolean).join("\n\n"), {
|
|
537
|
-
cfg,
|
|
538
|
-
accountId
|
|
539
|
-
});
|
|
540
|
-
await recordDeliveredCommandExchange({
|
|
541
|
-
config: cfg,
|
|
542
|
-
agentId: route.agentId,
|
|
543
|
-
sessionKey: route.sessionKey,
|
|
544
|
-
expectedSessionId: sessionEntry?.sessionId,
|
|
545
|
-
commandText,
|
|
546
|
-
commandId: `mattermost:${accountId}:${channelId}:${messageSid}`,
|
|
547
|
-
replyId: "model-picker",
|
|
548
|
-
replyText: delivered.content
|
|
549
|
-
});
|
|
550
|
-
return false;
|
|
551
|
-
}
|
|
552
|
-
const viewParams = {
|
|
553
|
-
ownerUserId: senderId,
|
|
554
|
-
data,
|
|
555
|
-
currentModel: await resolveMattermostModelPickerCurrentModel({
|
|
556
|
-
cfg,
|
|
557
|
-
route,
|
|
558
|
-
data,
|
|
559
|
-
sessionEntry
|
|
560
|
-
})
|
|
561
|
-
};
|
|
562
|
-
const view = entry.kind === "summary" ? renderMattermostModelSummaryView(viewParams) : entry.kind === "providers" ? renderMattermostProviderPickerView(viewParams) : renderMattermostModelsPickerView({
|
|
563
|
-
...viewParams,
|
|
564
|
-
provider: entry.provider,
|
|
565
|
-
page: 1
|
|
566
|
-
});
|
|
567
|
-
const delivered = await sendMessageMattermost(`channel:${channelId}`, [data.refreshWarning, view.text].filter(Boolean).join("\n\n"), {
|
|
568
|
-
cfg,
|
|
569
|
-
accountId,
|
|
570
|
-
buttons: view.buttons
|
|
571
|
-
});
|
|
572
|
-
await recordDeliveredCommandExchange({
|
|
573
|
-
config: cfg,
|
|
574
|
-
agentId: route.agentId,
|
|
575
|
-
sessionKey: route.sessionKey,
|
|
576
|
-
expectedSessionId: sessionEntry?.sessionId,
|
|
577
|
-
commandText,
|
|
578
|
-
commandId: `mattermost:${accountId}:${channelId}:${messageSid}`,
|
|
579
|
-
replyId: "model-picker",
|
|
580
|
-
replyText: [delivered.content, ...view.buttons.map((row) => row.map((button) => button.text).join(", "))].join("\n")
|
|
581
|
-
});
|
|
582
|
-
return true;
|
|
583
|
-
}
|
|
584
|
-
//#endregion
|
|
585
575
|
//#region extensions/mattermost/src/mattermost/slash-http.ts
|
|
586
576
|
const MAX_BODY_BYTES = 65536;
|
|
587
577
|
const BODY_READ_TIMEOUT_MS = 5e3;
|
|
@@ -595,27 +585,17 @@ const COMMAND_VALIDATION_LOOKUP_RATE_LIMIT_MAX_KEYS = 2e3;
|
|
|
595
585
|
const commandLookupInflight = /* @__PURE__ */ new Map();
|
|
596
586
|
const commandValidationFailureCache = /* @__PURE__ */ new Map();
|
|
597
587
|
const commandValidationLookupRateLimit = /* @__PURE__ */ new Map();
|
|
598
|
-
const SECRET_LOG_KEYS = /* @__PURE__ */ new Set([
|
|
599
|
-
"access_token",
|
|
600
|
-
"authorization",
|
|
601
|
-
"bottoken",
|
|
602
|
-
"client_secret",
|
|
603
|
-
"refresh_token",
|
|
604
|
-
"token"
|
|
605
|
-
]);
|
|
606
588
|
function sendSlashCommandResponse(res, status, text) {
|
|
607
|
-
res
|
|
608
|
-
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
609
|
-
res.end(JSON.stringify({
|
|
589
|
+
sendJson(res, status, {
|
|
610
590
|
response_type: "ephemeral",
|
|
611
591
|
text
|
|
612
|
-
})
|
|
592
|
+
});
|
|
613
593
|
}
|
|
614
|
-
async function readSlashCommandBody(req, res
|
|
594
|
+
async function readSlashCommandBody(req, res) {
|
|
615
595
|
try {
|
|
616
596
|
return await readRequestBodyWithLimit(req, {
|
|
617
597
|
maxBytes: MAX_BODY_BYTES,
|
|
618
|
-
timeoutMs,
|
|
598
|
+
timeoutMs: BODY_READ_TIMEOUT_MS,
|
|
619
599
|
destroyOnLimit: false
|
|
620
600
|
});
|
|
621
601
|
} catch (error) {
|
|
@@ -631,25 +611,6 @@ function findRegisteredCommandForPayload(params) {
|
|
|
631
611
|
function isDeletedMattermostCommand(command) {
|
|
632
612
|
return typeof command.delete_at === "number" && command.delete_at > 0;
|
|
633
613
|
}
|
|
634
|
-
function sanitizeCommandLookupError(error) {
|
|
635
|
-
const sanitized = (error instanceof Error ? error.message : String(error)).replace(/[\r\n\t]/gu, " ").replace(/https?:\/\/[^\s)\]}]+/giu, (urlText) => {
|
|
636
|
-
try {
|
|
637
|
-
const url = new URL(urlText);
|
|
638
|
-
if (url.username || url.password) {
|
|
639
|
-
url.username = "redacted";
|
|
640
|
-
url.password = "redacted";
|
|
641
|
-
}
|
|
642
|
-
for (const key of url.searchParams.keys()) if (SECRET_LOG_KEYS.has(key.toLowerCase())) url.searchParams.set(key, "redacted");
|
|
643
|
-
return url.toString();
|
|
644
|
-
} catch {
|
|
645
|
-
return urlText;
|
|
646
|
-
}
|
|
647
|
-
}).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]");
|
|
648
|
-
return truncateUtf16Safe(sanitized, 300);
|
|
649
|
-
}
|
|
650
|
-
function sanitizeMattermostLogValue(value) {
|
|
651
|
-
return truncateUtf16Safe(value.replace(/[\r\n\t]/gu, " "), 200);
|
|
652
|
-
}
|
|
653
614
|
async function withCommandLookupTimeout(task) {
|
|
654
615
|
const controller = new AbortController();
|
|
655
616
|
const timeout = setTimeout(() => controller.abort(), COMMAND_LOOKUP_TIMEOUT_MS);
|
|
@@ -670,15 +631,7 @@ function clearMattermostSlashCommandValidationCacheForAccount(accountId) {
|
|
|
670
631
|
]) for (const [key, entry] of cache) if (entry.accountId === accountId) cache.delete(key);
|
|
671
632
|
}
|
|
672
633
|
function sweepCommandValidationFailureCache(now = Date.now()) {
|
|
673
|
-
const
|
|
674
|
-
if (validNow === void 0) {
|
|
675
|
-
commandValidationFailureCache.clear();
|
|
676
|
-
return;
|
|
677
|
-
}
|
|
678
|
-
for (const [key, entry] of commandValidationFailureCache) {
|
|
679
|
-
const expiresAt = asDateTimestampMs(entry.expiresAt);
|
|
680
|
-
if (expiresAt === void 0 || expiresAt <= validNow) commandValidationFailureCache.delete(key);
|
|
681
|
-
}
|
|
634
|
+
for (const [key, entry] of commandValidationFailureCache) if (entry.expiresAt <= now) commandValidationFailureCache.delete(key);
|
|
682
635
|
pruneMapToMaxSize(commandValidationFailureCache, COMMAND_VALIDATION_FAILURE_CACHE_MAX_KEYS);
|
|
683
636
|
}
|
|
684
637
|
function hasCachedCommandValidationFailure(key, now = Date.now()) {
|
|
@@ -688,36 +641,18 @@ function hasCachedCommandValidationFailure(key, now = Date.now()) {
|
|
|
688
641
|
function cacheCommandValidationFailure(key, accountId) {
|
|
689
642
|
const now = Date.now();
|
|
690
643
|
sweepCommandValidationFailureCache(now);
|
|
691
|
-
const expiresAt = resolveExpiresAtMsFromDurationMs(COMMAND_VALIDATION_FAILURE_CACHE_MS, { nowMs: now });
|
|
692
|
-
if (expiresAt === void 0) {
|
|
693
|
-
commandValidationFailureCache.delete(key);
|
|
694
|
-
return;
|
|
695
|
-
}
|
|
696
644
|
commandValidationFailureCache.set(key, {
|
|
697
645
|
accountId,
|
|
698
|
-
expiresAt
|
|
646
|
+
expiresAt: now + COMMAND_VALIDATION_FAILURE_CACHE_MS
|
|
699
647
|
});
|
|
700
648
|
}
|
|
701
649
|
function sweepCommandValidationLookupRateLimit(now = Date.now()) {
|
|
702
|
-
const validNow = asDateTimestampMs(now);
|
|
703
|
-
if (validNow === void 0) {
|
|
704
|
-
commandValidationLookupRateLimit.clear();
|
|
705
|
-
return;
|
|
706
|
-
}
|
|
707
650
|
const staleAfterMs = COMMAND_VALIDATION_LOOKUP_REFILL_MS * COMMAND_VALIDATION_LOOKUP_BURST * 2;
|
|
708
|
-
for (const [key, entry] of commandValidationLookupRateLimit)
|
|
709
|
-
const updatedAt = asDateTimestampMs(entry.updatedAt);
|
|
710
|
-
if (updatedAt === void 0 || validNow - updatedAt > staleAfterMs) commandValidationLookupRateLimit.delete(key);
|
|
711
|
-
}
|
|
651
|
+
for (const [key, entry] of commandValidationLookupRateLimit) if (now - entry.updatedAt > staleAfterMs) commandValidationLookupRateLimit.delete(key);
|
|
712
652
|
pruneMapToMaxSize(commandValidationLookupRateLimit, COMMAND_VALIDATION_LOOKUP_RATE_LIMIT_MAX_KEYS);
|
|
713
653
|
}
|
|
714
654
|
function reserveCommandValidationLookup(params) {
|
|
715
|
-
const
|
|
716
|
-
const now = asDateTimestampMs(rawNow);
|
|
717
|
-
if (now === void 0) {
|
|
718
|
-
commandValidationLookupRateLimit.clear();
|
|
719
|
-
return { allowed: true };
|
|
720
|
-
}
|
|
655
|
+
const now = Date.now();
|
|
721
656
|
sweepCommandValidationLookupRateLimit(now);
|
|
722
657
|
const existing = commandValidationLookupRateLimit.get(params.key);
|
|
723
658
|
if (!existing) {
|
|
@@ -752,127 +687,23 @@ async function fetchCurrentMattermostCommandUncached(params) {
|
|
|
752
687
|
try {
|
|
753
688
|
commandLookupResult = await withCommandLookupTimeout((signal) => getMattermostCommand(params.client, params.registered.id, { signal }));
|
|
754
689
|
if (!isDeletedMattermostCommand(commandLookupResult)) return commandLookupResult;
|
|
755
|
-
commandLookupFallbackDetail =
|
|
690
|
+
commandLookupFallbackDetail = "command lookup by id returned deleted command";
|
|
756
691
|
} catch (err) {
|
|
757
692
|
commandLookupError = err;
|
|
758
693
|
}
|
|
759
694
|
try {
|
|
760
695
|
const currentCommands = await withCommandLookupTimeout((signal) => listMattermostCommands(params.client, params.registered.teamId, { signal }));
|
|
761
|
-
if (commandLookupError) params.log?.(`mattermost: slash command lookup by id failed for /${
|
|
762
|
-
else if (commandLookupFallbackDetail) params.log?.(`mattermost: slash ${commandLookupFallbackDetail} for /${
|
|
696
|
+
if (commandLookupError) params.log?.(`mattermost: slash command lookup by id failed for /${params.registered.trigger}; using team list fallback (status=${parseMattermostApiStatus(commandLookupError) ?? "unknown"})`);
|
|
697
|
+
else if (commandLookupFallbackDetail) params.log?.(`mattermost: slash ${commandLookupFallbackDetail} for /${params.registered.trigger}; using team list fallback`);
|
|
763
698
|
return currentCommands.find((cmd) => cmd.id === params.registered.id) ?? commandLookupResult;
|
|
764
699
|
} catch (err) {
|
|
765
|
-
const primaryDetail = commandLookupError ? `; command lookup
|
|
766
|
-
params.log?.(`mattermost: slash command registration check failed for /${
|
|
700
|
+
const primaryDetail = commandLookupError ? `; command lookup status=${parseMattermostApiStatus(commandLookupError) ?? "unknown"}` : commandLookupFallbackDetail ? `; command lookup: ${commandLookupFallbackDetail}` : "";
|
|
701
|
+
params.log?.(`mattermost: slash command registration check failed for /${params.registered.trigger} (status=${parseMattermostApiStatus(err) ?? "unknown"})${primaryDetail}`);
|
|
767
702
|
return null;
|
|
768
703
|
}
|
|
769
704
|
}
|
|
770
|
-
async function fetchCurrentMattermostCommand(params) {
|
|
771
|
-
const key = commandLookupKey(params.client, params.registered, params.accountId);
|
|
772
|
-
const existing = commandLookupInflight.get(key);
|
|
773
|
-
if (existing) return await existing.promise;
|
|
774
|
-
const lookup = fetchCurrentMattermostCommandUncached(params).finally(() => {
|
|
775
|
-
commandLookupInflight.delete(key);
|
|
776
|
-
});
|
|
777
|
-
commandLookupInflight.set(key, {
|
|
778
|
-
accountId: params.accountId,
|
|
779
|
-
promise: lookup
|
|
780
|
-
});
|
|
781
|
-
return await lookup;
|
|
782
|
-
}
|
|
783
|
-
async function validateMattermostSlashCommandToken(params) {
|
|
784
|
-
const lookupKey = commandLookupKey(params.client, params.registeredCommand, params.accountId);
|
|
785
|
-
if (hasCachedCommandValidationFailure(lookupKey)) return false;
|
|
786
|
-
if (!commandLookupInflight.has(lookupKey)) {
|
|
787
|
-
const reservation = reserveCommandValidationLookup({
|
|
788
|
-
key: lookupKey,
|
|
789
|
-
accountId: params.accountId
|
|
790
|
-
});
|
|
791
|
-
if (!reservation.allowed) {
|
|
792
|
-
if (reservation.shouldLog) params.log?.(`mattermost: slash command validation lookup rate-limited for /${sanitizeMattermostLogValue(params.registeredCommand.trigger)}`);
|
|
793
|
-
return false;
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
const current = await fetchCurrentMattermostCommand({
|
|
797
|
-
accountId: params.accountId,
|
|
798
|
-
client: params.client,
|
|
799
|
-
registered: params.registeredCommand,
|
|
800
|
-
log: params.log
|
|
801
|
-
});
|
|
802
|
-
if (!current || isDeletedMattermostCommand(current)) {
|
|
803
|
-
cacheCommandValidationFailure(lookupKey, params.accountId);
|
|
804
|
-
return false;
|
|
805
|
-
}
|
|
806
|
-
if (current.id !== params.registeredCommand.id || current.team_id !== params.registeredCommand.teamId || current.trigger !== params.registeredCommand.trigger || current.method !== "P" || current.url !== params.registeredCommand.url) {
|
|
807
|
-
cacheCommandValidationFailure(lookupKey, params.accountId);
|
|
808
|
-
return false;
|
|
809
|
-
}
|
|
810
|
-
if (!current.token || !safeEqualSecret(params.payload.token, current.token)) {
|
|
811
|
-
cacheCommandValidationFailure(lookupKey, params.accountId);
|
|
812
|
-
return false;
|
|
813
|
-
}
|
|
814
|
-
commandValidationFailureCache.delete(lookupKey);
|
|
815
|
-
return true;
|
|
816
|
-
}
|
|
817
|
-
async function authorizeSlashInvocation(params) {
|
|
818
|
-
const { account, cfg, client, commandText, channelId, senderId, senderName, log } = params;
|
|
819
|
-
const core = getMattermostRuntime();
|
|
820
|
-
let channelInfo = null;
|
|
821
|
-
try {
|
|
822
|
-
channelInfo = await fetchMattermostChannel(client, channelId);
|
|
823
|
-
} catch (err) {
|
|
824
|
-
log?.(`mattermost: slash channel lookup failed for ${sanitizeMattermostLogValue(channelId)}: ${sanitizeCommandLookupError(err)}`);
|
|
825
|
-
}
|
|
826
|
-
if (!channelInfo) return {
|
|
827
|
-
ok: false,
|
|
828
|
-
denyText: "Temporary error: unable to determine channel type. Please try again."
|
|
829
|
-
};
|
|
830
|
-
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
|
|
831
|
-
cfg,
|
|
832
|
-
surface: "mattermost"
|
|
833
|
-
});
|
|
834
|
-
const hasControlCommand = core.channel.text.hasControlCommand(commandText, cfg);
|
|
835
|
-
const storeAllowFrom = normalizeMattermostAllowList(await core.channel.pairing.readAllowFromStore({
|
|
836
|
-
channel: "mattermost",
|
|
837
|
-
accountId: account.accountId
|
|
838
|
-
}).catch(() => []));
|
|
839
|
-
const decision = await authorizeMattermostCommandInvocation({
|
|
840
|
-
account,
|
|
841
|
-
cfg,
|
|
842
|
-
senderId,
|
|
843
|
-
senderName,
|
|
844
|
-
channelId,
|
|
845
|
-
channelInfo,
|
|
846
|
-
storeAllowFrom,
|
|
847
|
-
allowTextCommands,
|
|
848
|
-
hasControlCommand
|
|
849
|
-
});
|
|
850
|
-
if (!decision.ok) {
|
|
851
|
-
if (decision.denyReason === "dm-pairing") {
|
|
852
|
-
const { code } = await core.channel.pairing.upsertPairingRequest({
|
|
853
|
-
channel: "mattermost",
|
|
854
|
-
accountId: account.accountId,
|
|
855
|
-
id: senderId,
|
|
856
|
-
meta: { name: senderName }
|
|
857
|
-
});
|
|
858
|
-
return {
|
|
859
|
-
ok: false,
|
|
860
|
-
denyText: code ? core.channel.pairing.buildPairingReply({
|
|
861
|
-
channel: "mattermost",
|
|
862
|
-
idLine: `Your Mattermost user id: ${senderId}`,
|
|
863
|
-
code
|
|
864
|
-
}) : MATTERMOST_PAIRING_QUEUE_FULL_TEXT
|
|
865
|
-
};
|
|
866
|
-
}
|
|
867
|
-
return {
|
|
868
|
-
ok: false,
|
|
869
|
-
denyText: decision.denyReason === "unknown-channel" ? "Temporary error: unable to determine channel type. Please try again." : decision.denyReason === "dm-disabled" ? "This bot is not accepting direct messages." : decision.denyReason === "channels-disabled" ? "Slash commands are disabled in channels." : decision.denyReason === "channel-no-allowlist" ? "Slash commands are not configured for this channel (no allowlist)." : "Unauthorized."
|
|
870
|
-
};
|
|
871
|
-
}
|
|
872
|
-
return decision;
|
|
873
|
-
}
|
|
874
705
|
function createSlashCommandHttpHandler(params) {
|
|
875
|
-
const { account, cfg, runtime, registeredCommands, triggerMap, log
|
|
706
|
+
const { account, cfg, runtime, registeredCommands, triggerMap, log } = params;
|
|
876
707
|
return async (req, res, bufferedBody, onRequestAuthenticated) => {
|
|
877
708
|
if (req.method !== "POST") {
|
|
878
709
|
res.statusCode = 405;
|
|
@@ -880,7 +711,7 @@ function createSlashCommandHttpHandler(params) {
|
|
|
880
711
|
res.end("Method Not Allowed");
|
|
881
712
|
return;
|
|
882
713
|
}
|
|
883
|
-
const body = bufferedBody ?? await readSlashCommandBody(req, res
|
|
714
|
+
const body = bufferedBody ?? await readSlashCommandBody(req, res);
|
|
884
715
|
if (body === void 0) return;
|
|
885
716
|
const payload = parseSlashCommandPayload(body, req.headers["content-type"] ?? "");
|
|
886
717
|
if (!payload) {
|
|
@@ -900,179 +731,306 @@ function createSlashCommandHttpHandler(params) {
|
|
|
900
731
|
botToken: account.botToken ?? "",
|
|
901
732
|
allowPrivateNetwork: account.config.network?.dangerouslyAllowPrivateNetwork === true
|
|
902
733
|
});
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
734
|
+
const validationAccountId = account.accountId;
|
|
735
|
+
const admittedCommand = registeredCommand;
|
|
736
|
+
const token = payload.token;
|
|
737
|
+
async function validateMattermostSlashCommandToken() {
|
|
738
|
+
const lookupKey = commandLookupKey(client, admittedCommand, validationAccountId);
|
|
739
|
+
if (hasCachedCommandValidationFailure(lookupKey)) return false;
|
|
740
|
+
if (!commandLookupInflight.has(lookupKey)) {
|
|
741
|
+
const reservation = reserveCommandValidationLookup({
|
|
742
|
+
key: lookupKey,
|
|
743
|
+
accountId: validationAccountId
|
|
744
|
+
});
|
|
745
|
+
if (!reservation.allowed) {
|
|
746
|
+
if (reservation.shouldLog) log?.(`mattermost: slash command validation lookup rate-limited for /${admittedCommand.trigger}`);
|
|
747
|
+
return false;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
let current;
|
|
751
|
+
const existing = commandLookupInflight.get(lookupKey);
|
|
752
|
+
if (existing) current = await existing.promise;
|
|
753
|
+
else {
|
|
754
|
+
const lookup = fetchCurrentMattermostCommandUncached({
|
|
755
|
+
client,
|
|
756
|
+
registered: admittedCommand,
|
|
757
|
+
log
|
|
758
|
+
}).finally(() => {
|
|
759
|
+
commandLookupInflight.delete(lookupKey);
|
|
760
|
+
});
|
|
761
|
+
commandLookupInflight.set(lookupKey, {
|
|
762
|
+
accountId: validationAccountId,
|
|
763
|
+
promise: lookup
|
|
764
|
+
});
|
|
765
|
+
current = await lookup;
|
|
766
|
+
}
|
|
767
|
+
if (!current || isDeletedMattermostCommand(current)) {
|
|
768
|
+
cacheCommandValidationFailure(lookupKey, validationAccountId);
|
|
769
|
+
return false;
|
|
770
|
+
}
|
|
771
|
+
if (current.id !== admittedCommand.id || current.team_id !== admittedCommand.teamId || current.trigger !== admittedCommand.trigger || current.method !== "P" || current.url !== admittedCommand.url) {
|
|
772
|
+
cacheCommandValidationFailure(lookupKey, validationAccountId);
|
|
773
|
+
return false;
|
|
774
|
+
}
|
|
775
|
+
if (!current.token || !safeEqualSecret(token, current.token)) {
|
|
776
|
+
cacheCommandValidationFailure(lookupKey, validationAccountId);
|
|
777
|
+
return false;
|
|
778
|
+
}
|
|
779
|
+
commandValidationFailureCache.delete(lookupKey);
|
|
780
|
+
return true;
|
|
781
|
+
}
|
|
782
|
+
if (!await validateMattermostSlashCommandToken()) {
|
|
910
783
|
sendSlashCommandResponse(res, 401, "Unauthorized: invalid command token.");
|
|
911
784
|
return;
|
|
912
785
|
}
|
|
913
786
|
onRequestAuthenticated?.();
|
|
914
|
-
const
|
|
915
|
-
const commandText = resolveCommandText(trigger, payload.text, triggerMap);
|
|
787
|
+
const commandText = resolveCommandText(normalizeSlashCommandTrigger(payload.command), payload.text, triggerMap);
|
|
916
788
|
const channelId = payload.channel_id;
|
|
917
789
|
const senderId = payload.user_id;
|
|
918
790
|
const senderName = payload.user_name ?? senderId;
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
791
|
+
async function authorizeSlashInvocation() {
|
|
792
|
+
const core = getMattermostRuntime();
|
|
793
|
+
let channelInfo = null;
|
|
794
|
+
try {
|
|
795
|
+
channelInfo = await fetchMattermostChannel(client, channelId);
|
|
796
|
+
} catch (err) {
|
|
797
|
+
log?.(`mattermost: slash channel lookup failed (status=${parseMattermostApiStatus(err) ?? "unknown"})`);
|
|
798
|
+
}
|
|
799
|
+
if (!channelInfo) return {
|
|
800
|
+
ok: false,
|
|
801
|
+
denyText: "Temporary error: unable to determine channel type. Please try again."
|
|
802
|
+
};
|
|
803
|
+
const allowTextCommands = core.channel.commands.shouldHandleTextCommands({
|
|
804
|
+
cfg,
|
|
805
|
+
surface: "mattermost"
|
|
806
|
+
});
|
|
807
|
+
const hasControlCommand = core.channel.text.hasControlCommand(commandText, cfg);
|
|
808
|
+
const storeAllowFrom = normalizeMattermostAllowList(await core.channel.pairing.readAllowFromStore({
|
|
809
|
+
channel: "mattermost",
|
|
810
|
+
accountId: account.accountId
|
|
811
|
+
}).catch(() => []));
|
|
812
|
+
const decision = await authorizeMattermostCommandInvocation({
|
|
813
|
+
account,
|
|
814
|
+
cfg,
|
|
815
|
+
senderId,
|
|
816
|
+
senderName,
|
|
817
|
+
channelId,
|
|
818
|
+
channelInfo,
|
|
819
|
+
storeAllowFrom,
|
|
820
|
+
allowTextCommands,
|
|
821
|
+
hasControlCommand
|
|
822
|
+
});
|
|
823
|
+
if (!decision.ok) {
|
|
824
|
+
if (decision.denyReason === "dm-pairing") {
|
|
825
|
+
const { code } = await core.channel.pairing.upsertPairingRequest({
|
|
826
|
+
channel: "mattermost",
|
|
827
|
+
accountId: account.accountId,
|
|
828
|
+
id: senderId,
|
|
829
|
+
meta: { name: senderName }
|
|
830
|
+
});
|
|
831
|
+
return {
|
|
832
|
+
ok: false,
|
|
833
|
+
denyText: code ? core.channel.pairing.buildPairingReply({
|
|
834
|
+
channel: "mattermost",
|
|
835
|
+
idLine: `Your Mattermost user id: ${senderId}`,
|
|
836
|
+
code
|
|
837
|
+
}) : MATTERMOST_PAIRING_QUEUE_FULL_TEXT
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
ok: false,
|
|
842
|
+
denyText: decision.denyReason === "unknown-channel" ? "Temporary error: unable to determine channel type. Please try again." : decision.denyReason === "dm-disabled" ? "This bot is not accepting direct messages." : decision.denyReason === "channels-disabled" ? "Slash commands are disabled in channels." : decision.denyReason === "channel-no-allowlist" ? "Slash commands are not configured for this channel (no allowlist)." : "Unauthorized."
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
return decision;
|
|
846
|
+
}
|
|
847
|
+
const auth = await authorizeSlashInvocation();
|
|
929
848
|
if (!auth.ok) {
|
|
930
849
|
sendSlashCommandResponse(res, 200, auth.denyText);
|
|
931
850
|
return;
|
|
932
851
|
}
|
|
933
|
-
log?.(`mattermost: slash command /${sanitizeMattermostLogValue(trigger)} from ${sanitizeMattermostLogValue(senderName)} in ${sanitizeMattermostLogValue(channelId)}`);
|
|
934
852
|
sendSlashCommandResponse(res, 200, "Processing...");
|
|
853
|
+
let replyRootId;
|
|
935
854
|
try {
|
|
936
|
-
|
|
937
|
-
|
|
855
|
+
const { kind, chatType, channelDisplay, roomLabel, commandAuthorized } = auth;
|
|
856
|
+
const teamId = payload.team_id;
|
|
857
|
+
const triggerId = payload.trigger_id;
|
|
858
|
+
const core = getMattermostRuntime();
|
|
859
|
+
const channelRoute = core.channel.routing.resolveAgentRoute({
|
|
938
860
|
cfg,
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
861
|
+
channel: "mattermost",
|
|
862
|
+
accountId: account.accountId,
|
|
863
|
+
teamId,
|
|
864
|
+
peer: {
|
|
865
|
+
kind,
|
|
866
|
+
id: kind === "direct" ? senderId : channelId
|
|
867
|
+
}
|
|
868
|
+
});
|
|
869
|
+
const thread = resolveMattermostThreadSessionContext({
|
|
870
|
+
baseSessionKey: channelRoute.sessionKey,
|
|
871
|
+
kind,
|
|
872
|
+
replyToMode: resolveMattermostReplyToMode(account, kind),
|
|
873
|
+
threadRootId: payload.root_id
|
|
874
|
+
});
|
|
875
|
+
const route = {
|
|
876
|
+
...channelRoute,
|
|
877
|
+
sessionKey: thread.sessionKey
|
|
878
|
+
};
|
|
879
|
+
replyRootId = thread.effectiveReplyToId;
|
|
880
|
+
const fromLabel = kind === "direct" ? `Mattermost DM from ${senderName}` : `Mattermost message in ${roomLabel} from ${senderName}`;
|
|
881
|
+
const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
|
|
882
|
+
const messageSid = triggerId ?? `slash-${Date.now()}`;
|
|
883
|
+
const pickerEntry = resolveMattermostModelPickerEntry(commandText);
|
|
884
|
+
if (pickerEntry) {
|
|
885
|
+
const accountId = account.accountId;
|
|
886
|
+
const sessionEntry = await getSessionEntryAsync({
|
|
887
|
+
agentId: route.agentId,
|
|
888
|
+
storePath: resolveStorePath(cfg.session?.store, { agentId: route.agentId }),
|
|
889
|
+
sessionKey: route.sessionKey,
|
|
890
|
+
readConsistency: "latest"
|
|
891
|
+
});
|
|
892
|
+
const recordModelPickerExchange = (replyText) => recordDeliveredCommandExchange({
|
|
893
|
+
config: cfg,
|
|
894
|
+
agentId: route.agentId,
|
|
895
|
+
sessionKey: route.sessionKey,
|
|
896
|
+
expectedSessionId: sessionEntry?.sessionId,
|
|
897
|
+
commandText,
|
|
898
|
+
commandId: `mattermost:${accountId}:${channelId}:${messageSid}`,
|
|
899
|
+
replyId: "model-picker",
|
|
900
|
+
replyText
|
|
901
|
+
});
|
|
902
|
+
const data = await buildPreparedModelsProviderData(cfg, route.agentId, { sessionEntry });
|
|
903
|
+
if (data.providers.length === 0) {
|
|
904
|
+
await recordModelPickerExchange((await sendMessageMattermost(`channel:${channelId}`, [data.refreshWarning, "No models available."].filter(Boolean).join("\n\n"), {
|
|
905
|
+
cfg,
|
|
906
|
+
accountId,
|
|
907
|
+
replyToId: replyRootId
|
|
908
|
+
})).content);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
const viewParams = {
|
|
912
|
+
ownerUserId: senderId,
|
|
913
|
+
data,
|
|
914
|
+
currentModel: await resolveMattermostModelPickerCurrentModel({
|
|
915
|
+
cfg,
|
|
916
|
+
route,
|
|
917
|
+
data,
|
|
918
|
+
sessionEntry
|
|
919
|
+
})
|
|
920
|
+
};
|
|
921
|
+
const view = pickerEntry.kind === "summary" ? renderMattermostModelSummaryView(viewParams) : pickerEntry.kind === "providers" ? renderMattermostProviderPickerView(viewParams) : renderMattermostModelsPickerView({
|
|
922
|
+
...viewParams,
|
|
923
|
+
provider: pickerEntry.provider,
|
|
924
|
+
page: 1
|
|
925
|
+
});
|
|
926
|
+
await recordModelPickerExchange([(await sendMessageMattermost(`channel:${channelId}`, [data.refreshWarning, view.text].filter(Boolean).join("\n\n"), {
|
|
927
|
+
cfg,
|
|
928
|
+
accountId,
|
|
929
|
+
buttons: view.buttons,
|
|
930
|
+
replyToId: replyRootId
|
|
931
|
+
})).content, ...view.buttons.map((row) => row.map((button) => button.text).join(", "))].join("\n"));
|
|
932
|
+
runtime.log?.(`delivered model picker to ${to}`);
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
const ctxPayload = finalizeInboundContext({
|
|
936
|
+
Body: commandText,
|
|
937
|
+
BodyForAgent: commandText,
|
|
938
|
+
RawBody: commandText,
|
|
939
|
+
CommandBody: commandText,
|
|
940
|
+
From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
|
|
941
|
+
To: to,
|
|
942
|
+
SessionKey: route.sessionKey,
|
|
943
|
+
ParentSessionKey: thread.parentSessionKey,
|
|
944
|
+
AccountId: route.accountId,
|
|
945
|
+
ChatType: chatType,
|
|
946
|
+
ConversationRouteContextObserved: true,
|
|
947
|
+
ConversationRoutePeerId: kind === "direct" ? senderId : channelId,
|
|
948
|
+
ConversationLabel: fromLabel,
|
|
949
|
+
GroupSpace: teamId,
|
|
950
|
+
GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
|
|
951
|
+
SenderName: senderName,
|
|
952
|
+
SenderId: senderId,
|
|
953
|
+
Provider: "mattermost",
|
|
954
|
+
Surface: "mattermost",
|
|
955
|
+
MessageSid: messageSid,
|
|
956
|
+
Timestamp: Date.now(),
|
|
957
|
+
WasMentioned: true,
|
|
958
|
+
CommandAuthorized: commandAuthorized,
|
|
959
|
+
InboundAccessAuthorized: true,
|
|
960
|
+
CommandSource: "native",
|
|
961
|
+
OriginatingChannel: "mattermost",
|
|
962
|
+
OriginatingTo: to,
|
|
963
|
+
ReplyToId: replyRootId,
|
|
964
|
+
MessageThreadId: replyRootId
|
|
965
|
+
});
|
|
966
|
+
const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
|
|
967
|
+
const tableMode = core.channel.text.resolveMarkdownTableMode({
|
|
968
|
+
cfg,
|
|
969
|
+
channel: "mattermost",
|
|
970
|
+
accountId: account.accountId
|
|
971
|
+
});
|
|
972
|
+
await core.channel.inbound.dispatch({
|
|
973
|
+
cfg,
|
|
974
|
+
channel: "mattermost",
|
|
975
|
+
accountId: account.accountId,
|
|
976
|
+
route: {
|
|
977
|
+
agentId: route.agentId,
|
|
978
|
+
dmScope: route.dmScope,
|
|
979
|
+
sessionKey: route.sessionKey
|
|
980
|
+
},
|
|
981
|
+
ctxPayload,
|
|
982
|
+
delivery: {
|
|
983
|
+
observeMessageSent: true,
|
|
984
|
+
deliver: async (replyPayload) => {
|
|
985
|
+
const result = await deliverMattermostReplyPayload({
|
|
986
|
+
core,
|
|
987
|
+
cfg,
|
|
988
|
+
payload: replyPayload,
|
|
989
|
+
channelId,
|
|
990
|
+
accountId: account.accountId,
|
|
991
|
+
agentId: route.agentId,
|
|
992
|
+
replyToId: replyRootId,
|
|
993
|
+
textLimit,
|
|
994
|
+
tableMode,
|
|
995
|
+
sendMessage: sendMessageMattermost
|
|
996
|
+
});
|
|
997
|
+
if (result.visibleReplySent) runtime.log?.(`delivered slash reply to ${to}`);
|
|
998
|
+
return result;
|
|
999
|
+
},
|
|
1000
|
+
onError: (err, info) => {
|
|
1001
|
+
runtime.error?.(`mattermost slash ${info.kind} reply failed (status=${parseMattermostApiStatus(err) ?? "unknown"})`);
|
|
1002
|
+
}
|
|
1003
|
+
},
|
|
1004
|
+
replyPipeline: { typing: {
|
|
1005
|
+
start: () => sendMattermostTyping(client, {
|
|
1006
|
+
channelId,
|
|
1007
|
+
parentId: replyRootId
|
|
1008
|
+
}),
|
|
1009
|
+
onStartError: (err) => {
|
|
1010
|
+
logTypingFailure({
|
|
1011
|
+
log: (message) => log?.(message),
|
|
1012
|
+
channel: "mattermost",
|
|
1013
|
+
target: channelId,
|
|
1014
|
+
error: err
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
} },
|
|
1018
|
+
dispatcherOptions: { humanDelay: resolveHumanDelayConfig(cfg, route.agentId) },
|
|
1019
|
+
replyOptions: { disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0 }
|
|
953
1020
|
});
|
|
954
1021
|
} catch (err) {
|
|
955
|
-
log?.(`mattermost: slash command handler error
|
|
1022
|
+
log?.(`mattermost: slash command handler error (status=${parseMattermostApiStatus(err) ?? "unknown"})`);
|
|
956
1023
|
try {
|
|
957
1024
|
const to = `channel:${channelId}`;
|
|
958
1025
|
await sendMessageMattermost(to, "Sorry, something went wrong processing that command.", {
|
|
959
1026
|
cfg,
|
|
960
|
-
accountId: account.accountId
|
|
1027
|
+
accountId: account.accountId,
|
|
1028
|
+
replyToId: replyRootId
|
|
961
1029
|
});
|
|
962
1030
|
} catch {}
|
|
963
1031
|
}
|
|
964
1032
|
};
|
|
965
1033
|
}
|
|
966
|
-
async function handleSlashCommandAsync(params) {
|
|
967
|
-
const { account, cfg, runtime, client, commandText, channelId, senderId, senderName, teamId, kind, chatType, channelDisplay, roomLabel, commandAuthorized, triggerId, log } = params;
|
|
968
|
-
const core = getMattermostRuntime();
|
|
969
|
-
const route = core.channel.routing.resolveAgentRoute({
|
|
970
|
-
cfg,
|
|
971
|
-
channel: "mattermost",
|
|
972
|
-
accountId: account.accountId,
|
|
973
|
-
teamId,
|
|
974
|
-
peer: {
|
|
975
|
-
kind,
|
|
976
|
-
id: kind === "direct" ? senderId : channelId
|
|
977
|
-
}
|
|
978
|
-
});
|
|
979
|
-
const fromLabel = kind === "direct" ? `Mattermost DM from ${senderName}` : `Mattermost message in ${roomLabel} from ${senderName}`;
|
|
980
|
-
const to = kind === "direct" ? `user:${senderId}` : `channel:${channelId}`;
|
|
981
|
-
const messageSid = triggerId ?? `slash-${Date.now()}`;
|
|
982
|
-
const pickerEntry = resolveMattermostModelPickerEntry(commandText);
|
|
983
|
-
if (pickerEntry) {
|
|
984
|
-
if (await deliverMattermostSlashModelPicker({
|
|
985
|
-
cfg,
|
|
986
|
-
route,
|
|
987
|
-
accountId: account.accountId,
|
|
988
|
-
channelId,
|
|
989
|
-
senderId,
|
|
990
|
-
commandText,
|
|
991
|
-
messageSid,
|
|
992
|
-
entry: pickerEntry
|
|
993
|
-
})) runtime.log?.(`delivered model picker to ${to}`);
|
|
994
|
-
return;
|
|
995
|
-
}
|
|
996
|
-
const ctxPayload = finalizeInboundContext({
|
|
997
|
-
Body: commandText,
|
|
998
|
-
BodyForAgent: commandText,
|
|
999
|
-
RawBody: commandText,
|
|
1000
|
-
CommandBody: commandText,
|
|
1001
|
-
From: kind === "direct" ? `mattermost:${senderId}` : kind === "group" ? `mattermost:group:${channelId}` : `mattermost:channel:${channelId}`,
|
|
1002
|
-
To: to,
|
|
1003
|
-
SessionKey: route.sessionKey,
|
|
1004
|
-
AccountId: route.accountId,
|
|
1005
|
-
ChatType: chatType,
|
|
1006
|
-
ConversationRouteContextObserved: true,
|
|
1007
|
-
ConversationRoutePeerId: kind === "direct" ? senderId : channelId,
|
|
1008
|
-
ConversationLabel: fromLabel,
|
|
1009
|
-
GroupSpace: teamId,
|
|
1010
|
-
GroupSubject: kind !== "direct" ? channelDisplay || roomLabel : void 0,
|
|
1011
|
-
SenderName: senderName,
|
|
1012
|
-
SenderId: senderId,
|
|
1013
|
-
Provider: "mattermost",
|
|
1014
|
-
Surface: "mattermost",
|
|
1015
|
-
MessageSid: messageSid,
|
|
1016
|
-
Timestamp: Date.now(),
|
|
1017
|
-
WasMentioned: true,
|
|
1018
|
-
CommandAuthorized: commandAuthorized,
|
|
1019
|
-
InboundAccessAuthorized: true,
|
|
1020
|
-
CommandSource: "native",
|
|
1021
|
-
OriginatingChannel: "mattermost",
|
|
1022
|
-
OriginatingTo: to
|
|
1023
|
-
});
|
|
1024
|
-
const textLimit = core.channel.text.resolveTextChunkLimit(cfg, "mattermost", account.accountId, { fallbackLimit: account.textChunkLimit ?? 4e3 });
|
|
1025
|
-
const tableMode = core.channel.text.resolveMarkdownTableMode({
|
|
1026
|
-
cfg,
|
|
1027
|
-
channel: "mattermost",
|
|
1028
|
-
accountId: account.accountId
|
|
1029
|
-
});
|
|
1030
|
-
await core.channel.inbound.dispatch({
|
|
1031
|
-
cfg,
|
|
1032
|
-
channel: "mattermost",
|
|
1033
|
-
accountId: account.accountId,
|
|
1034
|
-
route: {
|
|
1035
|
-
agentId: route.agentId,
|
|
1036
|
-
dmScope: route.dmScope,
|
|
1037
|
-
sessionKey: route.sessionKey
|
|
1038
|
-
},
|
|
1039
|
-
ctxPayload,
|
|
1040
|
-
delivery: {
|
|
1041
|
-
observeMessageSent: true,
|
|
1042
|
-
deliver: async (payload) => {
|
|
1043
|
-
const result = await deliverMattermostReplyPayload({
|
|
1044
|
-
core,
|
|
1045
|
-
cfg,
|
|
1046
|
-
payload,
|
|
1047
|
-
channelId,
|
|
1048
|
-
accountId: account.accountId,
|
|
1049
|
-
agentId: route.agentId,
|
|
1050
|
-
textLimit,
|
|
1051
|
-
tableMode,
|
|
1052
|
-
sendMessage: sendMessageMattermost
|
|
1053
|
-
});
|
|
1054
|
-
if (result.visibleReplySent) runtime.log?.(`delivered slash reply to ${to}`);
|
|
1055
|
-
return result;
|
|
1056
|
-
},
|
|
1057
|
-
onError: (err, info) => {
|
|
1058
|
-
runtime.error?.(`mattermost slash ${info.kind} reply failed: ${sanitizeCommandLookupError(err)}`);
|
|
1059
|
-
}
|
|
1060
|
-
},
|
|
1061
|
-
replyPipeline: { typing: {
|
|
1062
|
-
start: () => sendMattermostTyping(client, { channelId }),
|
|
1063
|
-
onStartError: (err) => {
|
|
1064
|
-
logTypingFailure({
|
|
1065
|
-
log: (message) => log?.(message),
|
|
1066
|
-
channel: "mattermost",
|
|
1067
|
-
target: channelId,
|
|
1068
|
-
error: err
|
|
1069
|
-
});
|
|
1070
|
-
}
|
|
1071
|
-
} },
|
|
1072
|
-
dispatcherOptions: { humanDelay: resolveHumanDelayConfig(cfg, route.agentId) },
|
|
1073
|
-
replyOptions: { disableBlockStreaming: typeof account.blockStreaming === "boolean" ? !account.blockStreaming : void 0 }
|
|
1074
|
-
});
|
|
1075
|
-
}
|
|
1076
1034
|
//#endregion
|
|
1077
1035
|
//#region extensions/mattermost/src/mattermost/slash-state.ts
|
|
1078
1036
|
const slashRouteInFlightLimiter = createWebhookInFlightLimiter();
|
|
@@ -1098,9 +1056,7 @@ function resolveSlashHandler(source, matchesState) {
|
|
|
1098
1056
|
if (!match) return { kind: "none" };
|
|
1099
1057
|
return {
|
|
1100
1058
|
kind: "single",
|
|
1101
|
-
|
|
1102
|
-
handler: match.handler,
|
|
1103
|
-
accountIds: [match.accountId]
|
|
1059
|
+
handler: match.handler
|
|
1104
1060
|
};
|
|
1105
1061
|
}
|
|
1106
1062
|
return {
|
|
@@ -1122,7 +1078,7 @@ function getSlashCommandState(accountId) {
|
|
|
1122
1078
|
* Called from the monitor after bot connects.
|
|
1123
1079
|
*/
|
|
1124
1080
|
function activateSlashCommands(params) {
|
|
1125
|
-
const { account,
|
|
1081
|
+
const { account, registeredCommands, triggerMap, api, log } = params;
|
|
1126
1082
|
const accountId = account.accountId;
|
|
1127
1083
|
const handler = createSlashCommandHttpHandler({
|
|
1128
1084
|
account,
|
|
@@ -1133,18 +1089,15 @@ function activateSlashCommands(params) {
|
|
|
1133
1089
|
log
|
|
1134
1090
|
});
|
|
1135
1091
|
accountStates.set(accountId, {
|
|
1136
|
-
commandTokens: new Set(
|
|
1092
|
+
commandTokens: new Set(registeredCommands.map((command) => command.token).filter(Boolean)),
|
|
1137
1093
|
registeredCommands,
|
|
1138
1094
|
handler
|
|
1139
1095
|
});
|
|
1140
1096
|
log?.(`mattermost: slash commands activated for account ${accountId} (${registeredCommands.length} commands)`);
|
|
1141
1097
|
}
|
|
1142
1098
|
function deactivateSlashCommands(accountId) {
|
|
1143
|
-
for (const
|
|
1099
|
+
for (const stateAccountId of accountStates.keys()) {
|
|
1144
1100
|
if (accountId && stateAccountId !== accountId) continue;
|
|
1145
|
-
state.commandTokens.clear();
|
|
1146
|
-
state.registeredCommands = [];
|
|
1147
|
-
state.handler = null;
|
|
1148
1101
|
clearMattermostSlashCommandValidationCacheForAccount(stateAccountId);
|
|
1149
1102
|
accountStates.delete(stateAccountId);
|
|
1150
1103
|
}
|
|
@@ -1225,4 +1178,4 @@ function registerSlashCommandRoute(api) {
|
|
|
1225
1178
|
});
|
|
1226
1179
|
}
|
|
1227
1180
|
//#endregion
|
|
1228
|
-
export { resolveSlashCommandConfig as _, deliverMattermostReplyPayload as a,
|
|
1181
|
+
export { resolveSlashCommandConfig as C, resolveCallbackUrl as S, resolveMattermostModelPickerCurrentModel as _, deliverMattermostReplyPayload as a, isSlashCommandsEnabled as b, canFinalizeMattermostPreviewInPlace as c, resolveMattermostReplyRootId as d, resolveMattermostThreadSessionContext as f, renderMattermostProviderPickerView as g, renderMattermostModelsPickerView as h, registerSlashCommandRoute as i, formatMattermostFinalDeliveryOutcomeLog as l, parseMattermostModelPickerContext as m, deactivateSlashCommands as n, joinMattermostVisibleContent as o, shouldUpdateMattermostDraftToolProgress as p, getSlashCommandState as r, buildMattermostButtonInteractionMessageSid as s, activateSlashCommands as t, resolveMattermostInteractionReplyRootId as u, DEFAULT_COMMAND_SPECS as v, registerSlashCommands as x, cleanupSlashCommands as y };
|