@openclaw/mattermost 2026.10.5-beta.4 → 2026.10.10-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.
@@ -1,11 +1,11 @@
1
- import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, l as gateway_config_runtime_exports, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-AdorvrsQ.mjs";
1
+ import { a as resolveInteractionCallbackPath, c as setInteractionSecret, i as createMattermostInteractionHandler, l as gateway_config_runtime_exports, n as buildButtonProps, r as computeInteractionCallbackUrl, s as setInteractionCallbackUrl } from "./interactions-D2MJ2Tnp.mjs";
2
2
  import { n as getOptionalMattermostRuntime, t as getMattermostRuntime } from "./runtime-CNB4YGqJ.mjs";
3
- import { a as createMattermostPost, d as fetchMattermostUser, h as normalizeMattermostBaseUrl, m as isRetryableError, n as buildMattermostApiUrl, o as deleteMattermostPost, p as fetchMattermostUserTeams, r as createMattermostClient, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostMe, v as sendMattermostTyping, y as updateMattermostPost } from "./client-tv20cXIL.mjs";
4
- import { C as resolveAllowlistProviderRuntimeGroupPolicy, E as resolveDefaultGroupPolicy, O as warnMissingProviderGroupPolicyFallbackOnce, S as registerPluginHttpRoute, _ as listSkillCommandsForAgents, a as resolveMattermostMonitorInboundAccess, b as logTypingFailure, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, l as buildPreparedModelsProviderData, m as isDangerousNameMatchingEnabled, n as formatMattermostDirectMessageDropLog, o as resolveMattermostTrustedChatKind, s as shouldRetainMattermostSenderHistory, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, w as resolveChannelMediaMaxBytes, y as logInboundDrop } from "./monitor-auth-ChM45AzT.mjs";
3
+ import { a as createMattermostPost, d as fetchMattermostUser, h as normalizeMattermostBaseUrl, m as isRetryableError, n as buildMattermostApiUrl, o as deleteMattermostPost, p as fetchMattermostUserTeams, r as createMattermostClient, s as fetchMattermostChannel, t as MattermostPostSchema, u as fetchMattermostMe, v as sendMattermostTyping, y as updateMattermostPost } from "./client-CW26CnSc.mjs";
4
+ import { C as resolveAllowlistProviderRuntimeGroupPolicy, E as resolveDefaultGroupPolicy, O as warnMissingProviderGroupPolicyFallbackOnce, S as registerPluginHttpRoute, a as resolveMattermostMonitorInboundAccess, b as prepareSkillCommandsForAgents, c as DEFAULT_GROUP_HISTORY_LIMIT, d as createChannelMessageReplyPipeline, f as createChannelPairingController, l as buildPreparedModelsProviderData, m as isDangerousNameMatchingEnabled, n as formatMattermostDirectMessageDropLog, o as resolveMattermostTrustedChatKind, s as shouldRetainMattermostSenderHistory, t as authorizeMattermostCommandInvocation, u as createChannelHistoryWindow, v as logInboundDrop, w as resolveChannelMediaMaxBytes, y as logTypingFailure } from "./monitor-auth-C5XBx6E0.mjs";
5
5
  import { n as normalizeMattermostAllowEntry } from "./ingress-identity-D6hxfxvo.mjs";
6
- import { d as resolveMattermostReplyToMode, r as parseMattermostQuestionContext, u as resolveMattermostAccount } from "./normalize-B0VHjEFE.mjs";
7
- import { _ as resolveSlashCommandConfig, a as deliverMattermostReplyPayload, c as parseMattermostModelPickerContext, d as resolveMattermostModelPickerCurrentModel, f as DEFAULT_COMMAND_SPECS, g as resolveCallbackUrl, h as registerSlashCommands, l as renderMattermostModelsPickerView, m as isSlashCommandsEnabled, n as deactivateSlashCommands, o as joinMattermostVisibleContent, p as cleanupSlashCommands, r as getSlashCommandState, s as buildMattermostAllowedModelRefs, t as activateSlashCommands, u as renderMattermostProviderPickerView } from "./slash-state-CaHXPR0j.mjs";
8
- import { t as sendMessageMattermost } from "./send-BAUVI-1U.mjs";
6
+ import { d as resolveMattermostReplyToMode, r as parseMattermostQuestionContext, u as resolveMattermostAccount } from "./normalize-ttaISanW.mjs";
7
+ import { _ as resolveSlashCommandConfig, a as deliverMattermostReplyPayload, c as parseMattermostModelPickerContext, d as resolveMattermostModelPickerCurrentModel, f as DEFAULT_COMMAND_SPECS, g as resolveCallbackUrl, h as registerSlashCommands, l as renderMattermostModelsPickerView, m as isSlashCommandsEnabled, n as deactivateSlashCommands, o as joinMattermostVisibleContent, p as cleanupSlashCommands, r as getSlashCommandState, s as buildMattermostAllowedModelRefs, t as activateSlashCommands, u as renderMattermostProviderPickerView } from "./slash-state-D55i54L4.mjs";
8
+ import { t as sendMessageMattermost } from "./send-BLBZqBzq.mjs";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { resolvePinnedMainDmOwnerFromAllowlist, sanitizeUntrustedFileName } from "openclaw/plugin-sdk/security-runtime";
11
11
  import { normalizeLowercaseStringOrEmpty, normalizeOptionalString, normalizeStringEntries, normalizeTrimmedStringList, uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
@@ -13,7 +13,7 @@ import { escapeRegExp, sliceUtf16Safe, truncateUtf16Safe } from "openclaw/plugin
13
13
  import { createAcceptedChannelDeliveryResult, createChannelPartialDeliveryError, formatInboundEnvelope, formatInboundFromLabel, formatInboundMediaUnavailableText, formatMediaPlaceholderText, implicitMentionKindWhen, isChannelPartialDeliveryError, resolveInboundMentionDecision, resolveInboundSessionEnvelopeContextAsync, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
14
14
  import { formatErrorMessage, toErrorObject } from "openclaw/plugin-sdk/error-runtime";
15
15
  import { safeParseJsonWithSchema, safeParseWithSchema } from "openclaw/plugin-sdk/extension-shared";
16
- import { asDateTimestampMs, resolveExpiresAtMsFromDurationMs, resolvePromptHistoryLimit } from "openclaw/plugin-sdk/number-runtime";
16
+ import { resolvePromptHistoryLimit } from "openclaw/plugin-sdk/number-runtime";
17
17
  import { z } from "zod";
18
18
  import { bindIngressLifecycleToReplyOptions, createChannelIngressError, createChannelIngressMonitor, createChannelProgressDraftCompositor, createFinalizableDraftLifecycle, createLivePreviewLifecycle, createMessageReceiptFromOutboundResults, createPreviewMessageReceipt, listMessageReceiptPlatformIds, resolveChannelStreamingPreviewToolProgress } from "openclaw/plugin-sdk/channel-outbound";
19
19
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
@@ -25,11 +25,11 @@ import { isRecord } from "openclaw/plugin-sdk/channel-secret-basic-runtime";
25
25
  import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
26
26
  import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
27
27
  import { finalizeInboundContext } from "openclaw/plugin-sdk/reply-runtime";
28
- import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
28
+ import { getSessionEntryAsync, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
29
+ import { recordDeliveredCommandExchange, scopeCommandTranscriptId } from "openclaw/plugin-sdk/session-transcript-runtime";
29
30
  import { channelReadyPatch, isLoopbackHost } from "openclaw/plugin-sdk/gateway-runtime";
30
31
  import { createRuntimeConfigReader } from "openclaw/plugin-sdk/runtime-config-snapshot";
31
- import * as proxyCaptureSdk from "openclaw/plugin-sdk/proxy-capture";
32
- import { createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
32
+ import { captureWsEventAsync, createDebugProxyWebSocketAgent, resolveDebugProxySettings } from "openclaw/plugin-sdk/proxy-capture";
33
33
  import { WebSocket } from "openclaw/plugin-sdk/websocket-runtime";
34
34
  import { questionGatewayRuntime } from "openclaw/plugin-sdk/question-gateway-runtime";
35
35
  import { resolveInboundLastRouteSessionKey, resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing";
@@ -80,7 +80,6 @@ function shouldDropEmptyMattermostBody(params) {
80
80
  }
81
81
  //#endregion
82
82
  //#region extensions/mattermost/src/mattermost/monitor-websocket.ts
83
- const captureSdk = proxyCaptureSdk;
84
83
  const MATTERMOST_WEBSOCKET_MAX_PAYLOAD_BYTES = 16777216;
85
84
  const MATTERMOST_WEBSOCKET_HANDSHAKE_TIMEOUT_MS = 3e4;
86
85
  const MATTERMOST_WEBSOCKET_AUTH_TIMEOUT_MS = 3e4;
@@ -142,7 +141,7 @@ function createMattermostConnectOnce(opts) {
142
141
  return async () => {
143
142
  const flowId = randomUUID();
144
143
  const captureEvent = (event) => {
145
- captureSdk.captureWsEventAsync?.({
144
+ captureWsEventAsync({
146
145
  ...event,
147
146
  url: opts.wsUrl,
148
147
  flowId,
@@ -163,37 +162,25 @@ function createMattermostConnectOnce(opts) {
163
162
  return await new Promise((resolve, reject) => {
164
163
  let opened = false;
165
164
  let authenticated = false;
166
- let settled = false;
167
- let healthCheckEnabled = getBotUpdateAt != null;
168
- let healthCheckInFlight = false;
165
+ let stopped = false;
169
166
  let healthCheckTimer;
170
- let protocolKeepaliveEnabled = true;
171
167
  let protocolPingTimer;
172
168
  let protocolPongTimer;
173
169
  let initialUpdateAt;
174
170
  let authenticationSeq;
175
171
  let authTimer;
176
- const clearTimers = () => {
172
+ const stopHealthChecks = () => {
173
+ stopped = true;
177
174
  clearTimeout(healthCheckTimer);
178
- healthCheckTimer = void 0;
179
175
  clearTimeout(authTimer);
180
- authTimer = void 0;
181
176
  clearTimeout(protocolPingTimer);
182
- protocolPingTimer = void 0;
183
177
  clearTimeout(protocolPongTimer);
184
- protocolPongTimer = void 0;
185
- };
186
- const stopHealthChecks = () => {
187
- healthCheckEnabled = false;
188
- protocolKeepaliveEnabled = false;
189
- clearTimers();
190
178
  };
191
179
  const sendProtocolPing = () => {
192
- if (!protocolKeepaliveEnabled || settled) return;
180
+ if (stopped) return;
193
181
  clearTimeout(protocolPongTimer);
194
182
  protocolPongTimer = setTimeout(() => {
195
183
  protocolPongTimer = void 0;
196
- if (!protocolKeepaliveEnabled || settled) return;
197
184
  opts.runtime.error?.("mattermost websocket pong timeout — reconnecting");
198
185
  stopHealthChecks();
199
186
  ws.terminate();
@@ -201,32 +188,30 @@ function createMattermostConnectOnce(opts) {
201
188
  try {
202
189
  ws.ping();
203
190
  } catch (err) {
204
- if (!protocolKeepaliveEnabled || settled) return;
205
191
  opts.runtime.error?.(`mattermost websocket ping failed: ${String(err)}`);
206
192
  stopHealthChecks();
207
193
  ws.terminate();
208
194
  }
209
195
  };
210
196
  const scheduleProtocolPing = () => {
211
- if (!protocolKeepaliveEnabled || settled || protocolPingTimer !== void 0) return;
197
+ if (stopped || protocolPingTimer !== void 0) return;
212
198
  protocolPingTimer = setTimeout(() => {
213
199
  protocolPingTimer = void 0;
214
200
  sendProtocolPing();
215
201
  }, pingIntervalMs);
216
202
  };
217
203
  const scheduleHealthCheck = () => {
218
- if (!getBotUpdateAt || !healthCheckEnabled || settled || healthCheckInFlight) return;
204
+ if (!getBotUpdateAt || stopped) return;
219
205
  healthCheckTimer = setTimeout(() => {
220
206
  healthCheckTimer = void 0;
221
207
  runHealthCheck();
222
208
  }, healthCheckIntervalMs);
223
209
  };
224
210
  const runHealthCheck = async () => {
225
- if (!getBotUpdateAt || !healthCheckEnabled || settled || healthCheckInFlight) return;
226
- healthCheckInFlight = true;
211
+ if (!getBotUpdateAt || stopped) return;
227
212
  try {
228
213
  const current = await getBotUpdateAt();
229
- if (!healthCheckEnabled || settled) return;
214
+ if (stopped) return;
230
215
  if (initialUpdateAt === void 0) {
231
216
  initialUpdateAt = current;
232
217
  return;
@@ -237,26 +222,13 @@ function createMattermostConnectOnce(opts) {
237
222
  ws.terminate();
238
223
  }
239
224
  } catch (err) {
240
- if (!healthCheckEnabled || settled) return;
225
+ if (stopped) return;
241
226
  const label = initialUpdateAt === void 0 ? "mattermost: failed to get initial update_at" : "mattermost: health check error";
242
227
  opts.runtime.error?.(`${label}: ${String(err)}`);
243
228
  } finally {
244
- healthCheckInFlight = false;
245
229
  scheduleHealthCheck();
246
230
  }
247
231
  };
248
- const resolveOnce = () => {
249
- if (settled) return;
250
- settled = true;
251
- stopHealthChecks();
252
- resolve();
253
- };
254
- const rejectOnce = (error) => {
255
- if (settled) return;
256
- settled = true;
257
- stopHealthChecks();
258
- reject(error);
259
- };
260
232
  ws.on("open", () => {
261
233
  opened = true;
262
234
  captureEvent({
@@ -282,7 +254,6 @@ function createMattermostConnectOnce(opts) {
282
254
  ws.send(authPayload);
283
255
  authTimer = setTimeout(() => {
284
256
  authTimer = void 0;
285
- if (settled) return;
286
257
  opts.runtime.error?.("mattermost websocket authentication timed out — reconnecting");
287
258
  stopHealthChecks();
288
259
  ws.terminate();
@@ -347,14 +318,14 @@ function createMattermostConnectOnce(opts) {
347
318
  }
348
319
  });
349
320
  if (opened && authenticated) {
350
- resolveOnce();
321
+ resolve();
351
322
  return;
352
323
  }
353
324
  if (opened) {
354
- rejectOnce(new WebSocketClosedBeforeAuthenticationError(code, message || void 0));
325
+ reject(new WebSocketClosedBeforeAuthenticationError(code, message || void 0));
355
326
  return;
356
327
  }
357
- rejectOnce(new WebSocketClosedBeforeOpenError(code, message || void 0));
328
+ reject(new WebSocketClosedBeforeOpenError(code, message || void 0));
358
329
  });
359
330
  ws.on("error", (err) => {
360
331
  captureEvent({
@@ -649,6 +620,60 @@ async function buildMattermostEventPlan(monitor, params) {
649
620
  };
650
621
  }
651
622
  //#endregion
623
+ //#region extensions/mattermost/src/mattermost/monitor-interaction-dispatch.ts
624
+ async function dispatchMattermostInteractionReply(monitor, eventPlan, params) {
625
+ const { account, cfg, core, runtime } = monitor;
626
+ const { channelId, kind, route, thread, to } = eventPlan;
627
+ const { replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
628
+ const isModelPicker = params.kind === "model picker";
629
+ await core.channel.inbound.dispatch({
630
+ cfg,
631
+ channel: "mattermost",
632
+ accountId: account.accountId,
633
+ route: {
634
+ agentId: route.agentId,
635
+ dmScope: route.dmScope,
636
+ sessionKey: thread.sessionKey
637
+ },
638
+ ctxPayload: params.ctxPayload,
639
+ delivery: {
640
+ observeMessageSent: true,
641
+ deliver: async (payload) => {
642
+ const reply = isModelPicker ? {
643
+ ...payload,
644
+ text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
645
+ } : payload;
646
+ const result = await deliverMattermostReplyPayload({
647
+ core,
648
+ cfg,
649
+ payload: reply,
650
+ channelId,
651
+ accountId: account.accountId,
652
+ agentId: route.agentId,
653
+ replyToId: resolveMattermostInteractionReplyRootId({
654
+ kind,
655
+ threadRootId: thread.effectiveReplyToId,
656
+ replyToId: reply.replyToId,
657
+ interactionMessageSid: params.interactionMessageSid,
658
+ sourcePostId: params.sourcePostId
659
+ }),
660
+ textLimit,
661
+ tableMode: isModelPicker ? "off" : tableMode,
662
+ sendMessage: sendMessageMattermost
663
+ });
664
+ if (!isModelPicker && result.visibleReplySent) runtime.log?.(`delivered button-click reply to ${to}`);
665
+ return result;
666
+ },
667
+ onError: (err, info) => {
668
+ runtime.error?.(`mattermost ${params.kind} ${info.kind} reply failed: ${String(err)}`);
669
+ }
670
+ },
671
+ replyPipeline,
672
+ ...!isModelPicker ? { dispatcherOptions: { humanDelay: resolveHumanDelayConfig(cfg, route.agentId) } } : {},
673
+ replyOptions
674
+ });
675
+ }
676
+ //#endregion
652
677
  //#region extensions/mattermost/src/mattermost/monitor-interactions.ts
653
678
  /**
654
679
  * Answer an ask_user question from the button its own prompt offered.
@@ -768,7 +793,7 @@ function registerMattermostInteractions(params) {
768
793
  dropLabel: "interaction dispatch"
769
794
  });
770
795
  if (!eventPlan) return;
771
- const { channelDisplay, channelId, kind, route, thread, to } = eventPlan;
796
+ const { channelDisplay, kind } = eventPlan;
772
797
  const bodyText = `[Button click: user @${button.userName} selected "${button.actionName}"]`;
773
798
  const ctxPayload = eventPlan.finalizeContext({
774
799
  Body: bodyText,
@@ -782,48 +807,11 @@ function registerMattermostInteractions(params) {
782
807
  WasMentioned: true,
783
808
  CommandAuthorized: false
784
809
  });
785
- const { replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
786
- await core.channel.inbound.dispatch({
787
- cfg,
788
- channel: "mattermost",
789
- accountId: account.accountId,
790
- route: {
791
- agentId: route.agentId,
792
- dmScope: route.dmScope,
793
- sessionKey: thread.sessionKey
794
- },
810
+ await dispatchMattermostInteractionReply(monitor, eventPlan, {
795
811
  ctxPayload,
796
- delivery: {
797
- observeMessageSent: true,
798
- deliver: async (payload) => {
799
- const result = await deliverMattermostReplyPayload({
800
- core,
801
- cfg,
802
- payload,
803
- channelId,
804
- accountId: account.accountId,
805
- agentId: route.agentId,
806
- replyToId: resolveMattermostInteractionReplyRootId({
807
- kind,
808
- threadRootId: thread.effectiveReplyToId,
809
- replyToId: payload.replyToId,
810
- interactionMessageSid,
811
- sourcePostId
812
- }),
813
- textLimit,
814
- tableMode,
815
- sendMessage: sendMessageMattermost
816
- });
817
- if (result.visibleReplySent) runtime.log?.(`delivered button-click reply to ${to}`);
818
- return result;
819
- },
820
- onError: (err, info) => {
821
- runtime.error?.(`mattermost button-click ${info.kind} reply failed: ${String(err)}`);
822
- }
823
- },
824
- replyPipeline,
825
- dispatcherOptions: { humanDelay: resolveHumanDelayConfig(cfg, route.agentId) },
826
- replyOptions
812
+ interactionMessageSid,
813
+ sourcePostId,
814
+ kind: "button-click"
827
815
  });
828
816
  },
829
817
  log: (message) => runtime.log?.(message)
@@ -892,24 +880,50 @@ function createMattermostModelPickerInteractionHandler(monitor) {
892
880
  agentId: eventPlan.route.agentId,
893
881
  sessionKey: eventPlan.thread.sessionKey
894
882
  };
895
- const sessionEntry = getSessionEntry({
883
+ const sessionEntry = await getSessionEntryAsync({
884
+ agentId: modelSessionRoute.agentId,
896
885
  storePath: resolveStorePath(cfg.session?.store, { agentId: modelSessionRoute.agentId }),
897
886
  sessionKey: modelSessionRoute.sessionKey,
898
887
  readConsistency: "latest"
899
888
  });
900
889
  const data = await buildPreparedModelsProviderData(cfg, eventPlan.route.agentId, { sessionEntry });
901
- const updatePickerPost = (message, buttons) => updateModelPickerPost({
902
- channelId: params.payload.channel_id,
890
+ const interactionId = params.payload.trigger_id ?? `${params.payload.post_id}:${params.payload.user_id}:${pickerCommandText}:${"page" in pickerState ? pickerState.page : 1}`;
891
+ const messageSid = pickerState.action === "select" ? buildMattermostModelPickerSelectMessageSid({
903
892
  postId: params.payload.post_id,
904
- message: [data.refreshWarning, message].filter(Boolean).join("\n\n"),
905
- buttons
906
- });
893
+ provider: pickerState.provider,
894
+ model: pickerState.model
895
+ }) : interactionId;
896
+ const commandId = pickerState.action === "select" ? scopeCommandTranscriptId(messageSid, {
897
+ channelId: "mattermost",
898
+ accountId: account.accountId,
899
+ conversationId: eventPlan.to
900
+ }) : `mattermost:${account.accountId}:${params.payload.channel_id}:${interactionId}`;
901
+ const updatePickerPost = async (message, buttons) => {
902
+ const text = [data.refreshWarning, message].filter(Boolean).join("\n\n");
903
+ const response = await updateModelPickerPost({
904
+ channelId: params.payload.channel_id,
905
+ postId: params.payload.post_id,
906
+ message: text,
907
+ buttons
908
+ });
909
+ await recordDeliveredCommandExchange({
910
+ config: cfg,
911
+ ...modelSessionRoute,
912
+ expectedSessionId: sessionEntry?.sessionId,
913
+ commandText: pickerCommandText,
914
+ commandId,
915
+ replyId: "picker-update",
916
+ replyText: [text, ...(buttons ?? []).map((row) => row.map((button) => button.text).join(", "))].join("\n")
917
+ });
918
+ return response;
919
+ };
907
920
  if (data.providers.length === 0) return await updatePickerPost("No models available.");
908
921
  if (pickerState.action !== "select") {
909
- const currentModel = resolveMattermostModelPickerCurrentModel({
922
+ const currentModel = await resolveMattermostModelPickerCurrentModel({
910
923
  cfg,
911
924
  route: modelSessionRoute,
912
- data
925
+ data,
926
+ sessionEntry
913
927
  });
914
928
  const viewParams = {
915
929
  ownerUserId: pickerState.ownerUserId,
@@ -925,15 +939,10 @@ function createMattermostModelPickerInteractionHandler(monitor) {
925
939
  }
926
940
  const targetModelRef = `${pickerState.provider}/${pickerState.model}`;
927
941
  if (!buildMattermostAllowedModelRefs(data).has(targetModelRef)) return { ephemeral_text: `That model is no longer available: ${targetModelRef}` };
928
- const messageSid = buildMattermostModelPickerSelectMessageSid({
929
- postId: params.payload.post_id,
930
- provider: pickerState.provider,
931
- model: pickerState.model
932
- });
933
942
  runDetachedWebhookWork(async () => {
934
943
  const commandText = `/model ${targetModelRef}`;
935
944
  const sourcePostId = params.post.id || params.payload.post_id;
936
- const { channelDisplay, channelId, kind, roomLabel, route, thread } = eventPlan;
945
+ const { channelDisplay, kind, roomLabel } = eventPlan;
937
946
  const fromLabel = kind === "direct" ? `Mattermost DM from ${params.userName}` : `Mattermost message in ${roomLabel} from ${params.userName}`;
938
947
  const ctxPayload = eventPlan.finalizeContext({
939
948
  Body: commandText,
@@ -949,55 +958,21 @@ function createMattermostModelPickerInteractionHandler(monitor) {
949
958
  CommandAuthorized: auth.commandAuthorized,
950
959
  CommandSource: "native"
951
960
  });
952
- const { replyOptions, replyPipeline, tableMode, textLimit } = eventPlan.createReplyPlan();
953
- await core.channel.inbound.dispatch({
954
- cfg,
955
- channel: "mattermost",
956
- accountId: account.accountId,
957
- route: {
958
- agentId: route.agentId,
959
- dmScope: route.dmScope,
960
- sessionKey: thread.sessionKey
961
- },
961
+ await dispatchMattermostInteractionReply(monitor, eventPlan, {
962
962
  ctxPayload,
963
- delivery: {
964
- observeMessageSent: true,
965
- deliver: async (payload) => {
966
- const trimmedPayload = {
967
- ...payload,
968
- text: core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode).trim()
969
- };
970
- return await deliverMattermostReplyPayload({
971
- core,
972
- cfg,
973
- payload: trimmedPayload,
974
- channelId,
975
- accountId: account.accountId,
976
- agentId: route.agentId,
977
- replyToId: resolveMattermostInteractionReplyRootId({
978
- kind,
979
- threadRootId: thread.effectiveReplyToId,
980
- replyToId: trimmedPayload.replyToId,
981
- interactionMessageSid: messageSid,
982
- sourcePostId
983
- }),
984
- textLimit,
985
- tableMode: "off",
986
- sendMessage: sendMessageMattermost
987
- });
988
- },
989
- onError: (err, info) => {
990
- runtime.error?.(`mattermost model picker ${info.kind} reply failed: ${String(err)}`);
991
- }
992
- },
993
- replyPipeline,
994
- replyOptions
963
+ interactionMessageSid: messageSid,
964
+ sourcePostId,
965
+ kind: "model picker"
995
966
  });
996
- const currentModel = resolveMattermostModelPickerCurrentModel({
967
+ const currentModel = await resolveMattermostModelPickerCurrentModel({
997
968
  cfg,
998
969
  route: modelSessionRoute,
999
970
  data,
1000
- readConsistency: "latest"
971
+ sessionEntry: await getSessionEntryAsync({
972
+ agentId: modelSessionRoute.agentId,
973
+ storePath: resolveStorePath(cfg.session?.store, { agentId: modelSessionRoute.agentId }),
974
+ sessionKey: modelSessionRoute.sessionKey
975
+ })
1001
976
  });
1002
977
  const view = renderMattermostModelsPickerView({
1003
978
  ownerUserId: pickerState.ownerUserId,
@@ -1102,23 +1077,18 @@ function createMattermostMonitorResources(params) {
1102
1077
  function createCachedLookup(label, ttlMs, fetchValue) {
1103
1078
  const cache = /* @__PURE__ */ new Map();
1104
1079
  return async (id) => {
1105
- const rawNow = Date.now();
1106
- const now = asDateTimestampMs(rawNow);
1080
+ const now = Date.now();
1107
1081
  const cached = cache.get(id);
1108
- if (cached && now !== void 0 && cached.expiresAt > now) {
1109
- if (cached.value !== void 0) return cached.value;
1110
- } else cache.delete(id);
1082
+ if (cached && cached.expiresAt > now) return cached.value;
1083
+ cache.delete(id);
1111
1084
  try {
1112
1085
  const value = await fetchValue(id);
1113
- const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs, { nowMs: rawNow });
1114
- if (expiresAt !== void 0) {
1115
- cache.delete(id);
1116
- cache.set(id, {
1117
- value,
1118
- expiresAt
1119
- });
1120
- pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
1121
- }
1086
+ cache.delete(id);
1087
+ cache.set(id, {
1088
+ value,
1089
+ expiresAt: now + ttlMs
1090
+ });
1091
+ pruneMapToMaxSize(cache, MONITOR_RESOURCE_CACHE_MAX_ENTRIES);
1122
1092
  return value;
1123
1093
  } catch (err) {
1124
1094
  logger.debug?.(`mattermost: ${label} lookup failed: ${String(err)}`);
@@ -1229,8 +1199,8 @@ function createMattermostThreadBackfill(params) {
1229
1199
  const histories = createChannelHistoryWindow({ historyMap: channelHistories });
1230
1200
  const recoveries = /* @__PURE__ */ new Map();
1231
1201
  const inFlight = /* @__PURE__ */ new Set();
1232
- const readIdentity = (turn) => {
1233
- const entry = getSessionEntry({
1202
+ const readIdentity = async (turn) => {
1203
+ const entry = await getSessionEntryAsync({
1234
1204
  agentId: turn.agentId,
1235
1205
  storePath: resolveStorePath(cfg.session?.store, { agentId: turn.agentId }),
1236
1206
  sessionKey: turn.historyKey,
@@ -1238,14 +1208,6 @@ function createMattermostThreadBackfill(params) {
1238
1208
  });
1239
1209
  return entry ? JSON.stringify([entry.sessionId ?? null, entry.lifecycleRevision ?? null]) : null;
1240
1210
  };
1241
- const owns = (turn, recovery) => {
1242
- if (recoveries.get(turn.historyKey) !== recovery) return false;
1243
- try {
1244
- return readIdentity(turn) === recovery.identity;
1245
- } catch {
1246
- return false;
1247
- }
1248
- };
1249
1211
  const touch = (key, recovery) => {
1250
1212
  recoveries.delete(key);
1251
1213
  recoveries.set(key, recovery);
@@ -1326,42 +1288,34 @@ function createMattermostThreadBackfill(params) {
1326
1288
  }));
1327
1289
  };
1328
1290
  return async (turn) => {
1329
- if (historyLimit <= 0 || !Number.isFinite(turn.currentPostTimestamp) || turn.currentPostTimestamp <= 0) return { current: true };
1291
+ if (historyLimit <= 0 || !Number.isFinite(turn.currentPostTimestamp) || turn.currentPostTimestamp <= 0) return {};
1330
1292
  let identity;
1331
1293
  try {
1332
- identity = readIdentity(turn);
1294
+ identity = await readIdentity(turn);
1333
1295
  } catch {
1334
1296
  monitor.logVerboseMessage("mattermost: thread recovery skipped (session store unavailable)");
1335
- return { current: true };
1297
+ return {};
1336
1298
  }
1337
1299
  const previous = recoveries.get(turn.historyKey);
1338
1300
  let recovery = previous;
1339
1301
  if (!recovery || recovery.identity !== identity) {
1340
- const adopting = previous?.identity === null && identity !== null;
1341
1302
  recovery = {
1342
1303
  identity,
1343
- attempts: adopting ? previous.attempts : 0,
1344
- nextAttemptAt: adopting ? previous.nextAttemptAt : 0,
1345
- status: adopting && !previous.completion && previous.attempts > 0 ? previous.status : "pending"
1304
+ attempts: 0,
1305
+ nextAttemptAt: 0,
1306
+ status: "pending"
1346
1307
  };
1347
1308
  if (!previous && (channelHistories.get(turn.historyKey)?.length ?? 0) > 0) recovery.status = "seeded";
1348
1309
  }
1349
1310
  touch(turn.historyKey, recovery);
1350
- if (recovery.completion) {
1351
- const history = await recovery.completion;
1352
- return {
1353
- current: owns(turn, recovery),
1354
- history
1355
- };
1356
- }
1357
- if (recovery.status === "settled") return { current: true };
1358
- if (recovery.status === "seeded" && channelHistories.has(turn.historyKey)) return { current: true };
1359
- if (recovery.attempts >= MAX_ATTEMPTS || Date.now() < recovery.nextAttemptAt || inFlight.size >= MAX_IN_FLIGHT) return { current: true };
1311
+ if (recovery.completion) return { history: await recovery.completion };
1312
+ if (recovery.status === "settled") return {};
1313
+ if (recovery.status === "seeded" && channelHistories.has(turn.historyKey)) return {};
1314
+ if (recovery.attempts >= MAX_ATTEMPTS || Date.now() < recovery.nextAttemptAt || inFlight.size >= MAX_IN_FLIGHT) return {};
1360
1315
  recovery.attempts++;
1361
1316
  recovery.nextAttemptAt = Date.now() + COOLDOWN_MS;
1362
1317
  const owner = recovery;
1363
1318
  const controller = new AbortController();
1364
- const deadlineAt = performance.now() + TIMEOUT_MS;
1365
1319
  const boundedOperation = raceWithTimeout(() => {
1366
1320
  const operation = fetchEntries(turn, controller.signal);
1367
1321
  inFlight.add(operation);
@@ -1375,8 +1329,6 @@ function createMattermostThreadBackfill(params) {
1375
1329
  owner.completion = (async () => {
1376
1330
  try {
1377
1331
  const entries = await boundedOperation;
1378
- if (performance.now() >= deadlineAt) throw new DOMException("Mattermost thread recovery deadline", "TimeoutError");
1379
- if (!owns(turn, owner)) return;
1380
1332
  const live = channelHistories.get(turn.historyKey) ?? [];
1381
1333
  const merged = /* @__PURE__ */ new Map();
1382
1334
  for (const entry of [...entries, ...live]) merged.set(entry.messageId ?? entry, entry);
@@ -1399,7 +1351,6 @@ function createMattermostThreadBackfill(params) {
1399
1351
  monitor.logVerboseMessage(`mattermost: thread recovery retained ${entries.length} entries historyKey=${turn.historyKey}`);
1400
1352
  return snapshot;
1401
1353
  } catch (error) {
1402
- if (!owns(turn, owner)) return;
1403
1354
  owner.status = error instanceof Error && isRetryableError(error) && owner.attempts < MAX_ATTEMPTS ? "pending" : "settled";
1404
1355
  monitor.logVerboseMessage(`mattermost: thread recovery ${owner.status === "pending" ? "retry scheduled" : "gave up"} attempt=${owner.attempts}/${MAX_ATTEMPTS}`);
1405
1356
  return;
@@ -1407,11 +1358,7 @@ function createMattermostThreadBackfill(params) {
1407
1358
  owner.completion = void 0;
1408
1359
  }
1409
1360
  })();
1410
- const history = await owner.completion;
1411
- return {
1412
- current: owns(turn, owner),
1413
- history
1414
- };
1361
+ return { history: await owner.completion };
1415
1362
  };
1416
1363
  }
1417
1364
  //#endregion
@@ -1798,7 +1745,7 @@ const threadParticipation = createPersistentDedupeCache({
1798
1745
  persistent: {
1799
1746
  namespace: "mattermost.thread-participation",
1800
1747
  maxEntries: 1e3,
1801
- openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStore(options),
1748
+ openStore: (options) => getOptionalMattermostRuntime()?.state.openKeyedStoreV2(options),
1802
1749
  logError: createPluginStateErrorReporter(getOptionalMattermostRuntime, "mattermost", "thread-participation-state", "Mattermost persistent thread participation state failed"),
1803
1750
  readTimestamp: ({ repliedAt }) => repliedAt
1804
1751
  }
@@ -2438,10 +2385,6 @@ function createMattermostPostHandler(monitor) {
2438
2385
  channelId,
2439
2386
  kind
2440
2387
  }) : void 0;
2441
- if (backfill && !backfill.current) {
2442
- monitor.logVerboseMessage("mattermost: drop stale thread turn after session rotation");
2443
- return;
2444
- }
2445
2388
  const turnHistories = new Map(historyKey ? [[historyKey, (backfill?.history ?? channelHistories.get(historyKey) ?? []).filter((entry) => !allMessageIds.includes(entry.messageId ?? "") && (entry.timestamp === void 0 || post.create_at == null || entry.timestamp <= post.create_at)).slice(-historyLimit)]] : []);
2446
2389
  let combinedBody = body;
2447
2390
  if (historyKey) combinedBody = createChannelHistoryWindow({ historyMap: turnHistories }).buildPendingContext({
@@ -2487,8 +2430,7 @@ function createMattermostPostHandler(monitor) {
2487
2430
  allowFrom: account.config.allowFrom,
2488
2431
  normalizeEntry: normalizeMattermostAllowEntry
2489
2432
  }) : null;
2490
- const previewLine = truncateUtf16Safe(bodyText, 200).replace(/\n/g, "\\n");
2491
- monitor.logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} len=${bodyText.length} preview="${previewLine}"`);
2433
+ monitor.logVerboseMessage(`mattermost inbound: from=${ctxPayload.From} id=${post.id} len=${bodyText.length}`);
2492
2434
  await dispatchMattermostInboundTurn(monitor, {
2493
2435
  post,
2494
2436
  rawText,
@@ -2568,11 +2510,11 @@ function createMattermostReactionHandler(monitor) {
2568
2510
  }
2569
2511
  //#endregion
2570
2512
  //#region extensions/mattermost/src/mattermost/monitor-slash.ts
2571
- function buildSlashCommands(params) {
2513
+ async function buildSlashCommands(params) {
2572
2514
  const commandsToRegister = [...DEFAULT_COMMAND_SPECS];
2573
2515
  if (!params.nativeSkills) return commandsToRegister;
2574
2516
  try {
2575
- const skillCommands = listSkillCommandsForAgents({ cfg: params.cfg });
2517
+ const skillCommands = await prepareSkillCommandsForAgents({ cfg: params.cfg });
2576
2518
  for (const spec of skillCommands) {
2577
2519
  const name = typeof spec.name === "string" ? spec.name.trim() : "";
2578
2520
  if (!name) continue;
@@ -2627,7 +2569,7 @@ async function registerMattermostMonitorSlashCommands(params) {
2627
2569
  baseUrl: params.baseUrl,
2628
2570
  callbackUrl: slashCallbackUrl
2629
2571
  });
2630
- const dedupedCommands = dedupeSlashCommands(buildSlashCommands({
2572
+ const dedupedCommands = dedupeSlashCommands(await buildSlashCommands({
2631
2573
  cfg: params.cfg,
2632
2574
  runtime: params.runtime,
2633
2575
  nativeSkills: slashConfig.nativeSkills === true
@@ -2866,17 +2808,12 @@ async function monitorMattermostProvider(opts = {}) {
2866
2808
  dispatch: async (admissionLifecycle) => {
2867
2809
  if (!last) return;
2868
2810
  try {
2869
- if (entries.length === 1) {
2870
- await handlePost(last.post, last.payload, admissionLifecycle);
2871
- await settle();
2872
- return;
2873
- }
2874
- const mergedPost = {
2811
+ const mergedPost = entries.length === 1 ? last.post : {
2875
2812
  ...last.post,
2876
2813
  message: entries.map((entry) => normalizeOptionalString(entry.post.message) ?? "").filter(Boolean).join("\n"),
2877
2814
  file_ids: []
2878
2815
  };
2879
- await handlePost(mergedPost, last.payload, admissionLifecycle, entries.map((entry) => entry.post.id));
2816
+ await handlePost(mergedPost, last.payload, admissionLifecycle, entries.length > 1 ? entries.map((entry) => entry.post.id) : void 0);
2880
2817
  await settle();
2881
2818
  } catch (error) {
2882
2819
  await admissionLifecycle.onAbandoned();
@@ -2948,8 +2885,7 @@ async function monitorMattermostProvider(opts = {}) {
2948
2885
  await ingress.stop();
2949
2886
  unregisterInteractions();
2950
2887
  }
2951
- const slashShutdownCleanupPromise = slashShutdownCleanup;
2952
- if (slashShutdownCleanupPromise) await Promise.resolve(slashShutdownCleanupPromise);
2888
+ await Promise.resolve(slashShutdownCleanup);
2953
2889
  }
2954
2890
  //#endregion
2955
2891
  export { monitorMattermostProvider };