@openclaw/mattermost 2026.10.10 → 2026.11.5-beta.1

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